简体   繁体   中英

How to customize response content type in flask-restful?

I want to be able to return something other than application/json ie kml.

I have the following:

@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

Why is this still returning application/json? Also, if I have different formats, can I dynamically change the Content-Type of the respone within class mykml without the decorator?

Imports: from flask import Flask, request, Response, session,make_response

If you need a specific response type from an API method, then you'll have to use flask.make_response() to return a 'pre-baked' response object:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM