为什么要创建一个flask.Response对象似乎丢失了我的数据?

时间:2016-05-27 23:26:03

标签: python flask

我有一个使用flask.jsonify()

的Python / Flask应用程序

以下是我的应用程序中的代码:我使用flask.Response创建jsonify()对象并打印其值。请注意我发送给jsonify()的3个参数。我想稍后让他们退出:

x = jsonify(message="Hello World!", status_code=90210, status=404)
print "x = %s\n" % str(x))
print "x.status_code = %s\n" % str(x.status_code))
print "x.status = %s\n" % str(x.status))
print "dir(x) = %s\n" % str(dir(x))

上面的输出是什么?如下所示。这没有道理。

x = <Response 82 bytes [200 OK]>
x.status_code = 200
x.status = 200 OK
dir(x) = ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_ensure_sequence', '_get_mimetype_params', '_on_close', '_status', '_status_code', 'accept_ranges', 'add_etag', 'age', 'allow', 'autocorrect_location_header', 'automatically_set_content_length', 'cache_control', 'calculate_content_length', 'call_on_close', 'charset', 'close', 'content_encoding', 'content_language', 'content_length', 'content_location', 'content_md5', 'content_range', 'content_type', 'data', 'date', 'default_mimetype', 'default_status', 'delete_cookie', 'direct_passthrough', 'expires', 'force_type', 'freeze', 'from_app', 'get_app_iter', 'get_data', 'get_etag', 'get_wsgi_headers', 'get_wsgi_response', 'headers', 'implicit_sequence_conversion', 'is_sequence', 'is_streamed', 'iter_encoded', 'last_modified', 'location', 'make_conditional', 'make_sequence', 'mimetype', 'mimetype_params', 'response', 'retry_after', 'set_cookie', 'set_data', 'set_etag', 'status', 'status_code', 'stream', 'vary', 'www_authenticate']

它显示statusstatus_code都是200,即使我发送了不同的值。为什么我丢失了这些数据?我在哪里可以找到之前输入的"Hello World"字符串?没有.message()

1 个答案:

答案 0 :(得分:3)

jsonify()的关键字参数是 JSON有效负载的一部分,而不是响应元数据。您使用messagestatus_codestatus密钥创建了一个JSON对象,这些对象与Response对象属性完全分开

>>> x.get_data()
'{\n  "message": "Hello World!", \n  "status": 404, \n  "status_code": 90210\n}'
>>> x.headers
Headers([('Content-Type', u'application/json'), ('Content-Length', u'74')])

Response.get_data()方法显示响应的实际有效负载。

请参阅jsonify() documentation

  

使用 application / json mimetype,使用给定参数的 JSON表示创建Response。此函数的参数与dict构造函数的参数相同。

(大胆强调我的)

之后设置状态,或将结果包装在新的Response对象中。以下作品:

x = jsonify(message="Hello World!", status_code=90210, status=404)
x.status_code = 404

请参阅Werkzeug Response documentation了解支持哪些属性和方法。