Get request parameters
from flask import request
It is the request object in Flask that represents the current request. The request object stores all the information of an HTTP request.
python2 String type str "utf-8" "gbk" unicode a = "China" # str a = u"China" # unicode Common errors: ASCII cannot decode \xxx\xx Solutions are used u"xxx" u"China" % "sa"
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post" enctype="multipart/form-data"> <input type="text" name="city"> <input type="text" name="age"> <input type="file" name="gender"> <input type="submit"> </form> </body> </html> # Data in form format city=xxx&age=xxx&gender=xxx
request.py
# coding:utf-8 from flask import Flask, request app = Flask(__name__) # Interface api # 127.0.0.1:5000 / index? City = Shenzhen & country = China query string QueryString @app.route("/index", methods=["GET", "POST"]) def index(): # The request contains all the request data sent by the front end # form and data are used to extract request body data # Through requset.form, you can directly extract the data in the form format in the request body, which is an object like a dictionary # Only the first of multiple parameters with the same name can be obtained through the get method name = request.form.get("name") age = request.form.get("age") name_li = request.form.getlist("name") # If the data of the request body is not in form format (such as json format), it can be obtained through request.data print("request.data: %s" % request.data) # args is used to extract the parameters (query string) in the url city = request.args.get("city") return "hello name=%s, age=%s, city=%s, name_li=%s" % (name, age, city, name_li) # def register(): # if request.method == 'GET': # return render(request, "register.html") # else: # if __name__ == '__main__': app.run(debug=True)
Upload file
The uploaded file is stored in memory or a temporary location in the file system. You can access them through the files property of the request object. Each uploaded file is stored in this dictionary. It behaves like a standard Python file object, but it also has a save() method that allows you to save files to the server's file system. Here is an example of using it to save files:
from flask import request @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['the_file'] f.save('/var/www/uploads/uploaded_file.txt') ...
If you want to know the file name of the file on the client before uploading, you can access the filename attribute. But remember, never trust this value, it can be forged. If you want to store the file on the server according to the file name provided by the client, please pass it to secure provided by Werkzeug_ Filename() function:
from flask import request from werkzeug import secure_filename @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['the_file'] f.save('/var/www/uploads/' + secure_filename(f.filename))
upload.py
# coding:utf-8 from flask import Flask, request app = Flask(__name__) @app.route("/upload", methods=["POST"]) def upload(): """Accept files transmitted from the front end""" file_obj = request.files.get("pic") if file_obj is None: # Indicates that the file was not sent return "File not uploaded" # Save file locally # # 1. Create a file # f = open("./demo.png", "wb") # # 2. Write content to the document # data = file_obj.read() # f.write(data) # # 3. Close the file # f.close() # Save directly using the uploaded file object file_obj.save("./demo1.png") return "Upload succeeded" if __name__ == '__main__': app.run(debug=True)
_ Use of with
# coding:utf-8 # f = open("./1.txt", "wb") # # 2. Write content to the document # try: # f.write("hello flask") # except Exception: # pass # finally: # # 3. Close the file # f.close() # Context manager # with open("./1.txt", "wb") as f: # f.write("hello flask") # f.write("hello flask") # f.write("hello flask") # f.write("hello flask") class Foo(object): def __enter__(self): """get into with Statement is with call""" print("enter called") def __exit__(self, exc_type, exc_val, exc_tb): """leave with Statement is with call""" print("exit called") print("exc_type: %s" % exc_type) print("exc_val: %s" % exc_val) print("exc_tb: %s" % exc_tb) with Foo() as foo: print("hello python") a = 1 / 0 print("hello end") # When entering the with statement, with helps us call the object__ enter__ method, # When leaving the with statement, with helps us call the object__ exit__ method
bort function and custom exception handling
abort function
from flask import abort
Custom exception handling
@app.errorhandler(404) def error(e): return 'The page you requested does not exist, please confirm and visit again!%s'%e
# coding:utf-8 from flask import Flask, request, abort, Response app = Flask(__name__) @app.route("/login", methods=["GET"]) def login(): # name = request.form.get() # pwd = request.form.get() name = "" pwd = "" if name != "zhangsan" or pwd != "admin": # Use the abort function to immediately terminate the execution of the view function # And can return specific information to the front end # 1. The status code information must be a standard http status code abort(404) # # 2. Transfer responder information # resp = Response("login failed") # abort(resp) return "login success" # Define error handling methods @app.errorhandler(404) def handle_404_error(err): """Custom error handling methods""" # The return value of this function will be the final result seen by the front-end user return u"A 404 error occurred with the following message:%s" % err if __name__ == '__main__': app.run(debug=True)
Returned response data
tuple
A tuple can be returned. Such a tuple must be in the form of (response, status, headers) and contain at least one element. The status value overrides the status code, and the headers can be a list or dictionary as an additional message header value.
make_response
resp = make_response() resp.headers["sample"] = "value" resp.status = "404 not found"
# coding:utf-8 from flask import Flask, request, abort, Response, make_response app = Flask(__name__) @app.route("/index") def index(): # 1 use Yuanzu to return customized response information # Response body status code response header # return "index page", 400, [("Itcast", "pyton"), ("City", "shenzhen")] wrap the response header with a list # return "index page", 400, {"Itcast1": "python1", "City1": "sz1"} wrap the response header with a dictionary # return "index page", 666, {"Itcast1": "python1", "City1": "sz1"} you can customize the status code # return "index page", "666 itcast status", {"Itcast1": "python1", "City1": "sz1"} you can customize the status code description # return "index page", "666 itcast status" you can omit the response header # 2 use make_response to construct response information resp = make_response("index page 2") resp.status = "999 itcast" # Set status code resp.headers["city"] = "sz" # Set response header return resp if __name__ == '__main__': app.run(debug=True)
Use of json module
Return json data using jsonify
# coding:utf-8 from flask import Flask, jsonify import json app = Flask(__name__) @app.route("/index") def index(): # json is a string data = { "name": "python", "age": 24 } # # json. Dumps (Dictionary) converts python's dictionary to a json string # # JSON. Loads (string) converts a string to a dictionary in python # # json_str = json.dumps(data) # # return json_str, 200, {"Content-Type": "application/json"} # The jsonify help is converted to json data, and the content type of the response header is set to application/json # return jsonify(data) return jsonify(city="sz", country="china") if __name__ == '__main__': app.run(debug=True)
redirect
from flask import redirect
Setting and reading cookie s
make_response set_cookie(key, value='', max_age=None) delete_cookie(key)
# coding:utf-8 from flask import Flask, make_response, request app = Flask(__name__) @app.route("/set_cookie") def set_cookie(): resp = make_response("success") # Set a cookie. The default validity period is a temporary cookie. It will expire when the browser is closed resp.set_cookie("Itcast", "Python") resp.set_cookie("Itcast1", "Python1") # max_age sets the validity period in seconds resp.set_cookie("Itcast2", "Python1", max_age=3600) # Set the cookie by setting the request header resp.headers["Set-Cookie"] = "Itcast3=Python3; Expires=Sat, 18-Nov-2017 04:36:04 GMT; Max-Age=3600; Path=/" return resp @app.route("/get_cookie") def get_cookie(): c = request.cookies.get("Itcast") return c @app.route("/delete_cookie") def delete_cookie(): resp = make_response("del success") # delete cookie resp.delete_cookie("Itcast1") return resp if __name__ == '__main__': app.run(debug=True)
session
from flask import session
Need to set secret_key
The session can be set through Url without using cookie s. The disadvantage is that the session will become invalid when the browser is closed.
Session cross server problem: Nginx will divert the request and save the session data in the server memory. The first access generates session data in 192.168.1.2, and the second request may be diverted to 192.168.1.3, resulting in failure to obtain session data.
You can set nginx different regions to access the same server, including Hebei IP access 192.168.1.2 and Shanghai IP access 192.168.1.3.
Or store the session in the Redis server.
# coding:utf-8 from flask import Flask, session, current_app app = Flask(__name__) # The secret key string required for the flash session app.config["SECRET_KEY"] = "dhsodfhisfhosdhf29fy989" # Flash saves the session to a cookie by default @app.route("/login") def login(): # Set session data session["name"] = "python" session["mobile"] = "18611111111" return "login success" @app.route("/index") def index(): # Get session data name = session.get("name") return "hello %s" % name if __name__ == '__main__': app.run(debug=True)
Request context and application context
Request context
Both request and session belong to the request context object.
Application context
current_app and g are application context objects.
current_app: represents the program instance of the currently running program file.
g: When processing a request, the object used for temporary storage will reset this variable every request.
Facilitate parameter transfer between functions.
request hook
A hook is a reserved space for code calls.
Request hooks are implemented in the form of decorators. Flask supports the following four request hooks:
before_first_request: run before processing the first request.
@app.before_first_request
before_request: run before each request.
after_request(response): run after each request if no unhandled exception is thrown.
teardown_request(response): runs after each request, even if an unhandled exception is thrown.
# coding:utf-8 from flask import Flask, session, current_app, request, url_for app = Flask(__name__) @app.route("/index") def index(): print("index Executed") a = 1 / 0 return "index page" @app.route("/hello") def hello(): print("hello Executed") return "hello page" @app.before_first_request def handle_before_first_request(): """It is executed before the first request processing""" print("handle_before_first_request Executed") @app.before_request def handle_before_request(): """Executed before each request""" print("handle_before_request Executed") @app.after_request def handle_after_request(response): """At each request(View function processing)Then it was executed, The premise is that there is no exception in the view function""" print("handle_after_request Executed") return response @app.teardown_request def handle_teardown_request(response): """At each request (View function processing)After that, it is executed, regardless of whether the view function has an exception or not, When working in non debug mode debug=False""" path = request.path if path == url_for("index"): # if path in [url_for("index"),url_for("hello")]: print("Judge the view logic of the request in the request hook: index") elif path == url_for("hello"): print("Judge the view logic of the request in the request hook: hello") print("handle_teardown_request Executed") return response if __name__ == '__main__': app.run()
Flash script extended command line
pip install Flask-Script
# coding:utf-8 from flask import Flask from flask_script import Manager # Management class of startup command app = Flask(__name__) # Create an object for the Manager management class manager = Manager(app) @app.route("/index") def index(): return "index page" if __name__ == '__main__': # app.run(debug=True) # Start flash by managing objects manager.run()
Start command
python xx.py runserver python xx.py runserver -h 0.0.0.0 -p 6000 # Specify Ip and port number python xx.py shell # Direct operation