http request and response in Flask

Reference: "Flask web development."

Flask context of global variables

Flask context of temporary use certain objects become globally accessible. There are two contexts in the Flask: Application Context and request context .

variable name Context Explanation
current_app Application Context Application examples of the current application
g Application Context Objects as temporary storage when the processing request, each request to reset the object
request Request context Request object encapsulates content of the HTTP request sent by the client in
session Request context User session, the dictionary is a need to "remember" between the storage request value

Request Object

Flask request by a context variable opening request object, this object contains all the information of the HTTP request sent by the client. There are common attributes and methods:

Property or method Explanation
form A dictionary, all the form fields to store requests submitted (post request)
args All parameters of a dictionary to store a URL query string passed (get request)
values A dictionary, form the collection and args
cookies All a cookie dictionary, the storage request
headers All HTTP headers a dictionary, the storage request
files A dictionary, uploads all the files stored requests
get_data() Returns the requested data in the buffer body
get_json() It returns a dictionary, comprising parsing the request to obtain body JSON
blueprint Flask name of a processing request blueprint
endpoint Name of the endpoint processing request, Flask the view function name as the name of the endpoint routing
method The method of HTTP request, such as a GET or POST
scheme URL method (http or https)
ts_secure Returns True transmission request via a secure connection (HTTPS) (Note: This is the original book method, error)
host Request definition hostname, port number may comprise
path Path portion of the URL
query_string The query string part of the URL, return to the original binary value
full_path Path of the URL and query string section
url Full URL requested by the client
base_url With the url, but no query string section
remote_addr IP address of the client
about WSGI environment of the original request dictionary

Code demonstrates

from flask import Flask, request

app = Flask(__name__)


@app.route('/index/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':  # post参数{'name': 'flask'}
        print(request.form.get('name'))  # flask
        return 'post succeed'
    elif request.method == 'GET':   # 以url http://127.0.0.1:5000/index/?name=flask 为例
        print(request.args.get('name'))  # flask
        print(request.values.get('name'))  # flask
        print(request.cookies)           # {}
        print(request.headers.get('User-Agent'))  # Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0
        print(request.get_data())        # b''
        print(request.get_json())        # None
        print(request.blueprint)         # None
        print(request.endpoint)          # index
        print(request.scheme)            # http
        print(request.is_secure)         # False
        print(request.host)              # 127.0.0.1:5000
        print(request.path)              # /index/
        print(request.query_string)      # b'name=flask'
        print(request.full_path)         # /index/?name=flask
        print(request.url)               # http://127.0.0.1:5000/index/?name=flask
        print(request.base_url)          # http://127.0.0.1:5000/index/
        print(request.remote_addr)       # 127.0.0.1
        print(request.environ)
        return 'get succeed'


if __name__ == '__main__':
    app.run(debug=True)

Response Object

Common response:

return  "字符串"
return render_template # 返回模板
return redirect()

If you do not want to return several tuples of values, may be used in view make_response function () function returns a response object.

Common response object properties and methods are:

Property or method Explanation
status_code Digital HTTP status code
headers A dictionary-like object that contains all the response header transmitted with
set_cookie() Add a cookie in response to
delete_cookie() To delete a cookie
content_length In response to the length of the body
content_type A media type of the body
set_data() String or byte values ​​set in response to
get_data() Get the response body

And a special type of redirection.

from flask import Flask, request, make_response

app = Flask(__name__)


@app.route('/index/')
def index():
    data = {
        'msg': 'this document carries a cookie!'
    }
    response = make_response(data)
    response.set_cookie('answer', '42')
    response.headers['Content-Length'] = 100  # 默认为返回数据长度,可修改
    response.headers['token'] = 'asd343asd'  # 添加编辑header信息
    print(request.cookies.get('answer'))     # 第二次请求时会返回 42
    return response


if __name__ == '__main__':
    app.run(debug=True)

Guess you like

Origin www.cnblogs.com/rendan/p/11886447.html