如何在flask-restful中自定义响应内容类型?

时间:2014-09-24 18:11:30

标签: python flask flask-restful

我希望能够返回application / json以外的其他内容,即kml。

我有以下内容:

@api.representation('application/vnd.google-earth.kml+xml')
def kml(data):
    return Response(data, mimetype='application/vnd.google-earth.kml+xml')

class mykml(restful.Resource):

    def get(self):
        r = requests.get("http://myurl/kml") # This retrieves a .kml file   
        response = make_response(r.content)
        response.headers['Content-Type'] = "application/vnd.google-earth.kml+xml"

        return response

为什么这仍然是返回的应用程序/ json?另外,如果我有不同的格式,我可以在没有装饰器的情况下动态更改类mykml中的respone的Content-Type吗?

导入:from flask import Flask, request, Response, session,make_response

1 个答案:

答案 0 :(得分:1)

如果您需要API方法中的特定响应类型,则必须使用flask.make_response()返回“预烘焙”响应对象:

def get(self):
    response = flask.make_response(something)
    response.headers['content-type'] = 'application/vnd.google-earth.kml'
    return response