通过Flask测试客户端请求传递Cookie标头 [英] Pass cookie header with Flask test client request
问题描述
我无法让Flask测试客户端通过Cookie.这段代码曾经可以正常工作,并且我认为环境中的某些内容已更改,这打破了这一点.我最近创建了一个新的Python 3.7 virtualenv并安装了Flask 1.0.2.
从flask导入Flask,jsonify,请求app = Flask(__ name__)@ app.route('/cookie_echo')def cookie_echo():返回jsonify(request.cookies)使用app.test_client()作为客户端:响应= client.get("/cookie_echo",标头= {"Cookie":"abc = 123; def = 456"})打印(response.get_data(as_text = True))
运行示例将打印 {}
,但是我希望它可以打印 {"abc":"123","def":"456"}
.>
如果我通过 flask run
运行我的应用程序,则发送带有curl的标头:
<代码> $ curl -H"Cookie:abc = 123; def = 456" http://localhost:5000/cookie_echo{"abc":"123","def":"456"}
Client
管理cookie,您不应在 headers = {}
中手动传递它们.由于Werkzeug 0.15中的更改,因此不希望手动传递 Cookie
标头,该标头不再起作用.使用 client.set_cookie
设置cookie,或在响应中设置cookie,它将与下一个请求一起发送.
c = app.test_client()c.set_cookie('localhost','abc','123')c.set_cookie('localhost','def','456')c.get('/cookie_echo')
I am having trouble getting the Flask test client to pass cookies. This code used to work and I presume something in my environment changed, which breaks this. I recently created a new Python 3.7 virtualenv and installed Flask 1.0.2.
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/cookie_echo')
def cookie_echo():
return jsonify(request.cookies)
with app.test_client() as client:
response = client.get("/cookie_echo", headers={"Cookie": "abc=123; def=456"})
print(response.get_data(as_text=True))
Running the example prints {}
, but I expect it to print {"abc":"123","def":"456"}
.
If I run my app via flask run
, sending headers with curl works:
$ curl -H "Cookie: abc=123; def=456" http://localhost:5000/cookie_echo
{"abc":"123","def":"456"}
The Client
manages cookies, you should not pass them manually in headers={}
. Due to changes in Werkzeug 0.15, passing a Cookie
header manually, which was not intended, no longer works. Use client.set_cookie
to set a cookie, or set the cookie in a response and it will be sent with the next request.
c = app.test_client()
c.set_cookie('localhost', 'abc', '123')
c.set_cookie('localhost', 'def', '456')
c.get('/cookie_echo')
这篇关于通过Flask测试客户端请求传递Cookie标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!