Site Backend _python+flask.0008.flask response-related implicit explicit vs. custom response?

Source: Internet
Author: User
Tags wrappers

Implicit response:

1. The return value of the view function is implicitly converted to a response object

2. If a valid response object is returned, it is returned directly from the view function

3. If a string is returned, the string is created with the string data and the default argument as the body, and the status code is a Werkzeug.wrappers.Response response object of type 200,mime text/html

4. If a tuple is returned (response, status, headers) and contains at least one element, the status value overrides the state code, headers can be a list or a dictionary, as an additional message header

5. If none of the above conditions are met, flask will be forced to return via Werkzeug.wrappers.Response.force_type (RV, Request.environ)

#!/usr/bin/env python#-*-coding:utf-8-*-"" "# # authors:limanman# 51ctobg:http://xmdevops.blog.51cto.com/# Purpose:# "" "# Description: Import public module from Flask import flask, render_template, make_response# Description: Import other modules app = Flask (__name__) @app. ErrorHandler ( 404) def not_found (Error): Return render_template (' errors/404.html '), 404


An explicit response:

Note: An explicit response is to create a response object through Flask.make_response, which receives three parameters, response, status, headers and then returns the Response object, which can be called by Rsp.set_cookie (key, value= ' ', Max_age=none, Expires=none, path= '/', Domain=none, Secure=none, Httponly=false) and Rsp.delete_cookie (key, path= '/', Domain=none) to set or delete cookies, and can also be returned by adding additional header information

#!/usr/bin/env python#-*-coding:utf-8-*-"" "# # authors:limanman# 51ctobg:http://xmdevops.blog.51cto.com/# Purpose:# "" "# Description: Import public module from Flask import flask, render_template, make_response# Description: Import other modules app = Flask (__name__) @app. ErrorHandler ( 404) def server_err (Error): Return Make_response (render_template (' errors/404.html '), if __name__ = = ' __main__ ': a Pp.run (host= ' 0.0.0.0 ', port=9000, Debug=true)

Description: In fact, it is more recommended to use Make_response explicit response, because it can return a response object, can do many things through the response object, such as setting browser client cookie, etc.


Custom response:

#!/usr/bin/env python# -*- coding: utf-8 -*-"" "## authors: limanman#  51ctobg: http://xmdevops.blog.51cto.com/# purpose:# "" "#  Description:  Import public module Import jsonfrom  flask import flask, request, make_responsefrom werkzeug.wrappers import  Response#  Description:  Import other modules Class jsonpresponse (Response):     @classmethod     def force_type (Cls, response, environ=none):         if isinstance (response, dict):             response =  ' {0} ({1}) '. Format (Response.get (' callback '),  json.dumps (Response.get (' data ')))             response = make_response ( Response)         return super (JSONPRESPONSE, CLS). Force_type (responsE, environ) App = flask (__name__) app.response_class = jsonpresponse@app.route ('/api/ Hosts/jsonp ') Def jsonp ():     rm_hosts = [' 192.168.1.1 ',  ' 192.168.1.2 ',   ' 192.168.1.3 ',                  ' 192.168.1.4 ',  ' 192.168.1.5 ',  ' 192.168.1.6 ']    callback =  Request.args.get (' callback ')     return {' callback ': callback,  ' data ':  rm_hosts}if __name__ ==  ' __main__ ':     app.run (host= ' 0.0.0.0 ',  port= 9000, debug=true)
<! doctype html>

Note: If you implement a JSNP cross-domain with a custom response above, you need to be aware that inheriting from the response class requires only overriding the Force_type class method of a Baseresponse base class, Force_type receiving two parameters, and the original data returned by the view function. , one is Request object information, if NULL is used by default is Request.environ, but it needs to be noted that because our custom dictionary response does not meet the default response criteria, Response.force_type (response is called automatically, Request.environ) to convert to a Request object, so above we use Make_response (response) to directly generate a response object passed to the base class. Force_type method to generate a response

HTTP GET Http://127.0.0.1:9000/api/hosts/jsonp callback==hostscallbackhttp/1.0 okcontent-length:105content-type : Text/plain; Charset=utf-8date:thu, Oct 03:09:32 gmtserver:werkzeug/0.11.11 python/2.7.11hostscallback (["192.168.1.1", " 192.168.1.2 "," 192.168.1.3 "," 192.168.1.4 "," 192.168.1.5 "," 192.168.1.6 "])



This article is from "@Can up and No BB ..." Blog, be sure to keep this source http://xmdevops.blog.51cto.com/11144840/1866219

Site Backend _python+flask.0008.flask response-related implicit explicit vs. custom response?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.