Trầ*_* Dự 5 multipartform-data tornado
我正在使用多部分请求为用户上传文件编写 API。我看到 Tornado 4.5 版已经支持多部分请求。但在那之后,我想测试这个API。
我的问题是:
谢谢
Tornado 没有对发出多部分请求的内置支持。您必须手动编译多部分请求。
让我们首先看看multipart/form-data请求的样子。
样本表格:
<form method="POST" enctype="multipart/form-data">
<input type="text" name="field1">
<input type="file" name="field2">
<input type="submit">
</form>
Run Code Online (Sandbox Code Playgroud)
如果输入Hello的field1,并选择一个名为myfile.png为field2,HTTP请求看起来就像这样:
POST /url HTTP/1.1
Content-Type: multipart/form-data; boundary="boundary"
--boundary
Content-Disposition: form-data; name="field1"
Hello
--boundary
Content-Disposition: form-data; name="field2"; filename="myfile.png"
Conent-Type: image/png
<binary content of myfile.png>
--boundary--
Run Code Online (Sandbox Code Playgroud)
您所要做的就是编译一个类似的请求。
在我向您展示示例之前,让我向您说明一下,如果您还不知道 - 在上面的原始 HTTP 请求示例中,在每一行的末尾都有这些字符 - \r\n。它们在此处不可见,但它们存在于实际的 HTTP 请求中。即使是空行也有\r\n
字符存在。
了解这一点很重要。如果您要手动编译 HTTP 请求,则必须\r\n在每一行的末尾添加字符。
让我们来看看这个例子。
class MyTestCase(AsyncHTTPTestCase):
def test_something(self):
# create a boundary
boundary = 'SomeRandomBoundary'
# set the Content-Type header
headers = {
'Content-Type': 'multipart/form-data; boundary=%s' % boundary
}
# create the body
# opening boundary
body = '--%s\r\n' % boundary
# data for field1
body += 'Content-Disposition: form-data; name="field1"\r\n'
body += '\r\n' # blank line
body += 'Hello\r\n'
# separator boundary
body += '--%s\r\n' % boundary
# data for field2
body += 'Content-Disposition: form-data; name="field2"; filename="myfile.png"\r\n'
body += '\r\n' # blank line
# now read myfile.png and add that data to the body
with open('myfile.png', 'rb') as f:
body += '%s\r\n' % f.read()
# the closing boundary
body += "--%s--\r\n" % boundary
# make a request
self.fetch(url, method='POST', headers=headers, body=body)
Run Code Online (Sandbox Code Playgroud)
上面的代码非常基础。如果您有多个文件和参数,您应该考虑为此编写一个单独的函数并使用for循环。单击此处获取 Tornado 的 github 存储库中的示例代码。
| 归档时间: |
|
| 查看次数: |
841 次 |
| 最近记录: |