python - 将 HTTP 上传的数据返回到 sanic 服务器
问题描述
我正在尝试将数据上传到sanic
Web 服务器。为此,我使用 curl 发出 POST 请求。我尝试在 POST 请求后返回一些数据。这背后的基本原理是返回一些现在代表服务器端上传的 ID。但这似乎不起作用。现在我想知道:我的程序错了吗?不curl
写输出?或者这是一个错误sanic
?有人可以在这里帮助我吗?谢谢!
这是 Python 程序:
import signal
import asyncio
import uvloop
import sanic
app = sanic.Sanic(__name__)
loop = asyncio.get_event_loop()
server = app.create_server(host="localhost", port=3002)
task = asyncio.ensure_future(server)
@app.post("/testUpload", stream=True)
async def api_testUpload(request):
async def doStream(response):
while True:
body = await request.stream.get()
if body is None:
break
sanic.response.json({
"result": "good!"
})
return sanic.response.stream(doStream)
signal.signal(signal.SIGINT, lambda s, f: loop.stop())
try:
loop.run_forever()
except:
loop.stop()
您可以像这样调用curl
:
curl -v --data-binary "@somefile.data" http://localhost:3002/testUpload
这是curl
写入 STDOUT 的内容:
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 3002 (#0)
> POST /testUpload HTTP/1.1
> Host: localhost:3002
> User-Agent: curl/7.47.0
> Accept: */*
> Content-Length: 334504
> Content-Type: application/x-www-form-urlencoded
> Expect: 100-continue
>
< HTTP/1.1 200 OK
< Keep-Alive: 5
< Transfer-Encoding: chunked
< Content-Type: text/plain; charset=utf-8
<
* Done waiting for 100-continue
* We are completely uploaded and fine
* Connection #0 to host localhost left intact
如您所见,text/plain
生成了响应。这应该是application/json
我的数据,不是吗?
解决方案
这不是正确的做法。API在sanic
这里不能直观地工作。为了在接收到发送的字节后写入数据,您必须在流功能中这样做doStream()
:
await response.write(json.dumps({
"result": "good!"
}))
推荐阅读
- firebase - Firebase 仅托管以前版本的 Flutter Web 应用
- javascript - 将 mapStateToProps 转换为钩子
- node.js - ng-select 和 ng-option 验证
- r - 如何将列附加到列表中的 data.frames,其中该列应包含计算读取的那些 data.frames 的结构信息?
- php - 将所有可重复的字段转换为数组 - laravel 背包(假字段)
- php - 我想得到我的目录。信息到多维数组 - PHP
- multi-tenant - 为白标签/多租户站点应用样式的最佳方式
- google-apps-script - 带有日期(今天)的 Google 表格(脚本)中的 IF 函数
- html - 无论内容如何,RMarkdown 编织到 HTML 都会失败
- ajax - 如何在没有 AJAX 的情况下根据表单请求将 v-model 数据发送到服务器