Python Flask, how to set content type

前端 未结 7 1603
走了就别回头了
走了就别回头了 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 05:51

    Use the make_response method to get a response with your data. Then set the mimetype attribute. Finally return this response:

    @app.route('/ajax_ddl')
    def ajax_ddl():
        xml = 'foo'
        resp = app.make_response(xml)
        resp.mimetype = "text/xml"
        return resp
    

    If you use Response directly, you lose the chance to customize the responses by setting app.response_class. The make_response method uses the app.responses_class to make the response object. In this you can create your own class, add make your application uses it globally:

    class MyResponse(app.response_class):
        def __init__(self, *args, **kwargs):
            super(MyResponse, self).__init__(*args, **kwargs)
            self.set_cookie("last-visit", time.ctime())
    
    app.response_class = MyResponse  
    

提交回复
热议问题