我有一个响应对象作为结果GET请求和我已经转换这JSON与jsonify().当我将它传递给模板时,我得到的是一个JSON对象,如:<Response 1366 bytes [200 OK]>this.
#request.py
...
response = requests.get('http://www.example.com')
response_json = jsonify(all=response.text)
return render_template(
'results.html',
form=ReqForm(request.form),
response=response_json,
date=datetime.datetime.now()
)
Run Code Online (Sandbox Code Playgroud)
和模板..
#results.html
...
<div class="results">
{{ response }} # --> gives <Response 1366 bytes [200 OK]>
</div>
...
Run Code Online (Sandbox Code Playgroud)
我怎样才能在模板中显示这个JSON?
使用 json.dumps
response = json.dumps(response.text, sort_keys = False, indent = 2)
Run Code Online (Sandbox Code Playgroud)
或使它更漂亮
response = json.dumps(response.text, sort_keys = True, indent = 4, separators = (',', ': '))
Run Code Online (Sandbox Code Playgroud)
模板
#results.html
...
<div class="results">
<pre>{{ response }}</pre>
</div>
...
Run Code Online (Sandbox Code Playgroud)
jsonify()flask中的函数返回flask.Response()已经具有适当内容类型头的对象'application/json'以用于json响应,而json.dumps()will将返回一个编码字符串,这需要手动添加mime类型头.
资料来源:https://stackoverflow.com/a/13172658/264802
| 归档时间: |
|
| 查看次数: |
8486 次 |
| 最近记录: |