我在 falcon 框架的 request.py 中添加了更改,以解析 application/x-www-form-urlencoded 和 multipart/from-data。我提出了拉取请求 - https://github.com/falconry/falcon/pull/1236但它尚未合并到 master 中。检查这个 - https://github.com/branelmoro/falcon
我添加了新代码来解析 POST、PUT 和 DELETE application/x-www-form-urlencoded 和 multipart/form-data。文本字段将在 req.form_data 字典中可用,上传文件缓冲流将在 req.files 字典中可用。
我希望这将有助于分别访问 POST 和 GET 参数,我们也将能够上传文件。更改的好处是它不会将整个上传的文件加载到内存中。
下面是展示如何使用 POST、PUT 和 DELETE application/x-www-form-urlencoded 和 multipart/form-data 的示例代码:
import falcon
class Resource(object):
def on_post(self, req, resp):
# req.form_data will return dictionary of text field names and their values
print(req.form_data)
# req.form_data will return dictionary of file field names and
# their buffer class FileStream objects as values
print(req.files)
# support we are uploading a image.jpg in `pancard` file field then
# req.files["pancard"] will be FileStream buffer object
# We can use set_max_upload_size method to set maximum allowed
# file size let say 1Mb = 1*1024*1024 bytes for this file
req.files["pancard"].set_max_upload_size(1*1024*1024)
# We can use uploadto method to upload file on required path (Note: absolute filepath is required)
# This method returns boolean - `True` on successful upload
# and if upload is unsuccessful then it returns `False` and sets error on failure.
path = "/tmp/" + req.files["pancard"].name
response = req.files["pancard"].uploadto("/tmp/" + path)
print(response)
# Once file is uploaded sucessfully, we can check it's size
print(req.files["pancard"].size)
# If file is not uploaded sucessfully, we can check it's error
print(req.files["pancard"].error)
resp.body = "Done file upload"
resp.status = falcon.HTTP_200
# falcon.API instances are callable WSGI apps
app = falcon.API()
things = Resource()
# things will handle post requests to the '/post_path' URL path
app.add_route('/post_path', things)
如果您有任何疑问,请告诉我。