Python Flask, how to set content type

前端 未结 7 1604
走了就别回头了
走了就别回头了 2020-12-02 05:10

I am using Flask and I return an XML file from a get request. How do I set the content type to xml ?

e.g.

@app.route(\'/ajax_ddl\')
def ajax_ddl():
          


        
7条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 06:09

    Usually you don’t have to create the Response object yourself because make_response() will take care of that for you.

    from flask import Flask, make_response                                      
    app = Flask(__name__)                                                       
    
    @app.route('/')                                                             
    def index():                                                                
        bar = 'foo'                                                
        response = make_response(bar)                                           
        response.headers['Content-Type'] = 'text/xml; charset=utf-8'            
        return response
    

    One more thing, it seems that no one mentioned the after_this_request, I want to say something:

    after_this_request

    Executes a function after this request. This is useful to modify response objects. The function is passed the response object and has to return the same or a new one.

    so we can do it with after_this_request, the code should look like this:

    from flask import Flask, after_this_request
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        @after_this_request
        def add_header(response):
            response.headers['Content-Type'] = 'text/xml; charset=utf-8'
            return response
        return 'foobar'
    

提交回复
热议问题