Python Flask 和 Werkzeug:使用自定义标头测试发布请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18263844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask and Werkzeug: Testing a post request with custom headers
提问by theicfire
I'm currently testing my app with suggestions from http://flask.pocoo.org/docs/testing/, but I would like to add a header to a post request.
我目前正在使用来自http://flask.pocoo.org/docs/testing/ 的建议测试我的应用程序,但我想向发布请求添加标头。
My request is currently:
我的要求目前是:
self.app.post('/v0/scenes/test/foo', data=dict(image=(StringIO('fake image'), 'image.png')))
but I would like to add a content-md5 to the request. Is this possible?
但我想在请求中添加一个 content-md5。这可能吗?
My investigations:
我的调查:
Flask Client (in flask/testing.py) extends Werkzeug's Client, documented here: http://werkzeug.pocoo.org/docs/test/
Flask 客户端(在flask/testing.py 中)扩展了Werkzeug 的客户端,记录在这里:http: //werkzeug.pocoo.org/docs/test/
As you can see, post
uses open
. But open
only has:
如您所见,post
使用open
. 但open
只有:
Parameters:
as_tuple – Returns a tuple in the form (environ, result)
buffered – Set this to True to buffer the application run. This will automatically close the application for you as well.
follow_redirects – Set this to True if the Client should follow HTTP redirects.
So it looks like it's not supported. How might I get such a feature working, though?
所以看起来它不受支持。但是,我如何才能使这样的功能正常工作?
采纳答案by tbicr
open
also take *args
and **kwargs
which used as EnvironBuilder
arguments. So you can add just headers
argument to your first post request:
open
也将*args
和**kwargs
用作EnvironBuilder
参数。所以你可以headers
在你的第一个 post 请求中添加参数:
with self.app.test_client() as client:
client.post('/v0/scenes/test/foo',
data=dict(image=(StringIO('fake image'), 'image.png')),
headers={'content-md5': 'some hash'});
回答by theicfire
Werkzeug to the rescue!
Werkzeug 来救援!
from werkzeug.test import EnvironBuilder, run_wsgi_app
from werkzeug.wrappers import Request
builder = EnvironBuilder(path='/v0/scenes/bucket/foo', method='POST', data={'image': (StringIO('fake image'), 'image.png')}, \
headers={'content-md5': 'some hash'})
env = builder.get_environ()
(app_iter, status, headers) = run_wsgi_app(http.app.wsgi_app, env)
status = int(status[:3]) # output will be something like 500 INTERNAL SERVER ERROR