在视图中强制应用程序/ json MIME类型(Flask) [英] Forcing application/json MIME type in a view (Flask)

查看:290
本文介绍了在视图中强制应用程序/ json MIME类型(Flask)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何在Flask中强制使用MIME类型 application / json 来查看视图。这里有一个简单的视图,我把它们放在一起进行演示:

$ $ $ $ $ $ $ $ $ b def testView():
ret ='{data:JSON string example}'
return ret

JSON字符串(保存在变量 ret 中)从其他地方收集(使用另一个程序的stdout使用 subprocess )所以我不能使用

我看过返回Json文档这个 Stackoverflow的问题,但我到目前为止还没有任何运气。我一直在寻找一下现在&将继续搜索,但认为我会问在这里,以防万一有人遇到这个。



谢谢。






请参阅下面的答案

解决方案:

  @ app.route(/)
def testView()
ret ='{data:JSON string example}'

resp = Response(response = ret,
status = 200,
mimetype =应用程序/ json)

return resp

我发现这个网站很有用: 使用Python实现REST风格的Web API Flask

解决方案

看起来可以直接使用Response对象。



请参阅其中一个评论 - 在视图中强制应用程序/ json MIME类型(Flask)


I can't figure out how to force the MIME type application/json for a view in Flask. Here is a simple view I've thrown together for demonstration purposes:

@app.route("/")
def testView():
    ret = '{"data": "JSON string example"}'
    return ret

The JSON string (held in variable ret) is gathered from elsewhere (using stdout from another program using subprocess) so I can't use jsonify provided with Flask.

I've had a look at the "Returning Json" Documentation and this Stackoverflow question but I haven't had any luck so far. I've been looking around for awhile now & will continue searching but thought I'd ask here just in case anyone has come across this.

Thanks.


See the answer below

The solution:

@app.route("/")
def testView():
    ret = '{"data": "JSON string example"}'

    resp = Response(response=ret,
                    status=200,
                    mimetype="application/json")

    return resp

I found this website useful: Implementing a RESTful Web API with Python & Flask

解决方案

Looks like you can use the Response object directly.

Please see one of the comments - Forcing application/json MIME type in a view (Flask)

这篇关于在视图中强制应用程序/ json MIME类型(Flask)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆