flask-response
- About Response:
- View of the function return value will be automatically converted into a response object, flask conversion logic is as follows:
- If it returns a string, then the flask is re-created object of werkzeug.wrappers.Response, the string as a host Response status code 200, MIME is text / html, and then return Response
- If a return is ancestral, the data type of the ancestral should be (response, status, headers). Status overrides the default value of the status code 200, header may be a list or dictionary, as a response to the first message.
- If it returns a Response object is returned directly.
- If the above conditions are not met, flask will try to call Response.force_type be converted to such a request
-
1 from flask import Flask, Response, jsonify 2 3 app = Flask(__name__) 4 5 6 class JsonResponse(Response): 7 @classmethod 8 def force_type(cls, response, environ=None): 9 if isinstance(response, dict): 10 response = jsonify(response) 11 return super(JsonResponse, cls).force_type(response, environ) 12 13 14 app.response_class = JsonResponse 15 16 17 @app.route('/') 18 def index(): 19 response = Response(response='HELLO', status=200, content_type='text/html;charset=utf-8') 20 return response 21 22 23 @app.route('/json') 24 def json_test(): 25 return {'hello': 'world'} 26 27 28 if __name__ == '__main__': 29 app.run()
-
flask custom return object classes
- Create a custom object class needs to inherit Response class
- When you need to return the original to meet the flask does not support the return of a certain type of data, you need to override a class method force_type
- The response is then processed so that the object of the parent class to handle Response
- The app class to return to return a custom class
- View of the function return value will be automatically converted into a response object, flask conversion logic is as follows: