gpt4 book ai didi

django - http流实际上是由http chunk实现的吗?

转载 作者:行者123 更新时间:2023-12-04 15:37:17 26 4
gpt4 key购买 nike

一开始我以为http stream其实就是实现了http chunk。

所以我做了一个测试来学习。

这是一个django View

def test_stream(request):

return StreamingHttpResponse(func)

函数返回可迭代这是使用 curl 访问 View 的输出

curl -vv -raw http://172.25.44.238:8004/api/v1/admin/restart_all_agent?cluster_id='dd5aef9cbe7311e99585f000ac192cee' -i
Warning: Invalid character is found in given range. A specified range MUST
Warning: have only digits in 'start'-'stop'. The server's response to this
Warning: request is uncertain.
* About to connect() to 172.25.44.238 port 8004 (#0)
* Trying 172.25.44.238...
* Connected to 172.25.44.238 (172.25.44.238) port 8004 (#0)
> GET /api/v1/admin/restart_all_agent?cluster_id=dd5aef9cbe7311e99585f000ac192cee HTTP/1.1
> Range: bytes=aw
> User-Agent: curl/7.29.0
> Host: 172.25.44.238:8004
> Accept: */*
>
< HTTP/1.1 200 OK
HTTP/1.1 200 OK
< Content-Type: text/html; charset=utf-8
Content-Type: text/html; charset=utf-8
< X-Frame-Options: SAMEORIGIN
X-Frame-Options: SAMEORIGIN
* no chunk, no close, no size. Assume close to signal end

<

some http response body.

* Closing connection 0

从输出中您可以看到没有分块 header 。看起来Http stream和chunk没有关系。

问题来了

  • http流是由http chunk实现的吗?
  • 如何在 Django 中返回分块响应?

最佳答案

不,流与分块没有任何关系。你可以有一个有或没有另一个。

流式响应的优点是您不需要将整个响应作为字符串一次加载到内存中。

这篇博客文章很好地解释了用例是什么:https://andrewbrookins.com/django/how-does-djangos-streaminghttpresponse-work-exactly/

它还涵盖了返回分块响应所需的内容,我将对其进行总结:

  • 使用 StreamingHttpResponse 类,但提供可迭代(列表、生成器...)作为第一个参数而不是字符串。
  • 不要设置Content-Length header 。
  • 您需要使用网络服务器来为您分块响应。 Django 本身不会这样做,manage.py runserver 也不会发生这种情况(但是 uvicorngunicorn 会,例如)<
from django.urls import path
from django.http import StreamingHttpResponse

def generator():
for i in range(0, 100):
yield str(i) * 1024 * 1024

def chunked_view(request):
return StreamingHttpResponse(generator(), content_type='text/plain')

urlpatterns = [path('chunked', chunked_view)]

使用 uvicorn myapp.asgi:application 运行 Django 应用程序。

curl -v http://127.0.0.1:8000/chunked >/dev/null 在响应 header 中显示 transfer-encoding: chunked

关于django - http流实际上是由http chunk实现的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59349913/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com