Flask和Werkzeug:使用自定义标头测试发布请求

the*_*ire 35 python werkzeug flask

我目前正在使用来自http://flask.pocoo.org/docs/testing/的建议测试我的应用,但我想在帖子请求中添加标题.

我的要求目前是:

self.app.post('/v0/scenes/test/foo', data=dict(image=(StringIO('fake image'), 'image.png')))
Run Code Online (Sandbox Code Playgroud)

但我想在请求中添加一个内容-md5.这可能吗?

我的调查:

Flask Client(在flask/testing.py中)扩展了Werkzeug的客户端,在此处记录:http: //werkzeug.pocoo.org/docs/test/

如你所见,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.
Run Code Online (Sandbox Code Playgroud)

所以看起来它不受支持.但是,我怎么可以使用这样的功能呢?

tbi*_*icr 64

open也采取*args**kwargs用作EnvironBuilder参数.所以你可以只headers为你的第一个帖子请求添加参数:

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'});
Run Code Online (Sandbox Code Playgroud)


the*_*ire 6

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
Run Code Online (Sandbox Code Playgroud)

  • 为什么要额外导入Request? (2认同)