#Reference
https://www.jianshu.com/p/6452596c4edb
#Chinese Manual http://docs.jinkan.org/docs/flask/quickstart.html http://docs.jinkan.org/docs/flask/index.html
w3cschool: https://www.w3cschool.cn/flask/
flask is a web micro framework of python demo / or simple web tool is very convenient
install flask:pip install flask
Do you need a well configured directory structure to make a formal website
flask-demo/ ├ run.py # Application launcher ├ config.py # Environment configuration ├ requirements.txt # List all Python packages the application depends on ├ tests/ # Test code package │ ├ __init__.py │ └ test_*.py # test case └ myapp/ ├ admin/ # Blueprint catalog ├ static/ │ ├ css/ # css file directory │ ├ img/ # Picture file directory │ └ js/ # js file directory ├ templates/ # Template file directory ├ __init__.py ├ forms.py # Store all forms and, if more, turn them into one package ├ models.py # Store all data models, and if there are many, turn them into one package └ views.py # Store all view functions. If there are many, change them into one package
Simplest test: test.py
python test.py After, the browser enters localhost:5000 You can see the web page showing Hello world. Or enter: 127.0.0.1:5000
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Hello World' if __name__ == '__main__': app.debug = True # Set debug mode, and turn off debug in production mode app.run()
Jinja2 is a widely used template engine, which can easily embed data into web price inquiry
from flask import Flask from flask import render_template app = Flask(__name__) @app.route('/hello') @app.route('/hello/<name>') def hello(name=None): #Rendering hello.html Template, pass name data in return render_template('hello.html', name=name) if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)
#Template file: hello.html " http://localhost:5000/hello/world"
<!doctype html> <title>Hello Sample</title> {% if name %} <h1>Hello {{ name }}!</h1> {% else %} <h1>Hello World!</h1> {% endif %}
#Template inheritance# father.html
<!doctype html> <title>Hello Sample</title> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}"> <div class="page"> {% block body %} {% endblock %} </div>
#Inherit the above template
{% extends "father.html" %} {% block body %} {% if name %} <h1>Hello {{ name }}!</h1> {% else %} <h1>Hello World!</h1> {% endif %} {% endblock %}
session records the logged in information to avoid repeatedly entering the login page
from flask import Flask,url_for,request,render_template,redirect,session @app.route('/login', methods=['POST', 'GET']) def login(): if request.method == 'POST': if request.form['user'] == 'admin': session['user'] = request.form['user'] return 'Admin login successfully!' else: return 'No such user!' if 'user' in session: return 'Hello %s!' % session['user'] else: title = request.args.get('title', 'Default') return render_template('login.html', title=title) @app.route('/logout') def logout(): session.pop('user', None) return redirect(url_for('login')) app.secret_key = '123456' if __name__ == "__main__": app.run(debug=True)
Use cookies
from flask import Flask,url_for,request,render_template,redirect,session,make_response import time @app.route('/login', methods=['POST', 'GET']) def login(): response = None if request.method == 'POST': if request.form['user'] == 'admin': session['user'] = request.form['user'] response = make_response('Admin login successfully!') #Set Cookie, save in browser, the third parameter max_age sets the validity period (seconds). If it is not set, the browser will be invalid after closing response.set_cookie('login_time', time.strftime('%Y-%m-%d %H:%M:%S')) ... else: if 'user' in session: #" request.cookies ”Object is a dictionary that holds the Cookie of the browser. Use its "get()" function to get the corresponding key value. login_time = request.cookies.get('login_time') response = make_response('Hello %s, you logged in on %s' % (session['user'], login_time)) ... return response app.secret_key = '123456' #Set secret key, preferably random if __name__ == "__main__": app.run(debug=True)
error handling
from flask import Flask,abort app = Flask(__name__) @app.route('/error') def error(): abort(404) #immediate withdrawal @app.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 #Return to rewritten error page if __name__ == "__main__": app.run(debug=True)
URL redirection:
#Without /, Flask will automatically redirect to the correct address.
@app.route('/projects/') def projects(): return 'The project page' #Flag will directly report 404 NOT FOUND error after / after the end @app.route('/about') def about(): return 'The about page' --------------------------------------------- from flask import session, redirect @app.route('/') def index(): if 'user' in session: return 'Hello %s!' % session['user'] else: #The redirect() "function directs a client to another web address when browsing it #The second parameter of "redirect()" is the HTTP status code. The available values are 301, 302, 303, 305 and 307. The default value is 302 return redirect(url_for('login'), 302)
#Upload file #werkzeug determines whether the file name is safe pip install werkzeug #Server:
from flask import Flask, request from werkzeug.utils import secure_filename import os app = Flask(__name__) #Configuration information upload directory app.config['UPLOAD_FOLDER'] = 'static/uploads/' #Control the size of uploaded files app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 #16MB #Upload file format, suffix app.config['ALLOWED_EXTENSIONS'] = set(['png', 'jpg', 'jpeg', 'gif']) # For a given file, return whether it's an allowed type or not def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS'] @app.route('/') def hello_world(): return 'hello world' @app.route('/upload', methods=['POST']) def upload(): upload_file = request.files['image01']#Image is marked with "image01" file_content = request.files['image01'].stream.read()#Get the content of the uploaded file if upload_file and allowed_file(upload_file.filename): filename = secure_filename(upload_file.filename) #route upload_file.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename)) return 'hello, '+request.form.get('name', 'little apple')+'. success' else: return 'hello, '+request.form.get('name', 'little apple')+'. failed' if __name__ == '__main__': app.run(debug=True)
client
import requests #Upload 01.jpg under the current directory to the server files = {'image01': open('01.jpg', 'rb')} user_info = {'name': 'letian'} r = requests.post("http://127.0.0.1:5000/upload", data=user_info, files=files) #coding=utf-8 from flask import Flask from flask import request app = Flask(__name__)
#Routing means that url/register only accepts POST methods. You can also modify the methods parameter as needed
@app.route("/login", methods=["GET", "POST"]) def hello_str(): if request.method == "POST": print(request.headers) #Request header #Multiple methods of receiving data username = request.form['username'] username = request.form.get("username",type = str,default="admin") #Get form data #Corresponding request requests.post(url, json.dumps(params)) as_text=True becomes Unicode use json.loads() conversion dictionary params = request.get_data(as_text=True) params = request.get_json() params = request.data elif request.method == "GET": username = request.args.get("username") #Get get request parameters username = request.values.get("username") #Get all requested parameters return redirect(url_for('home',username=request.form['username'])) @app.route('/home') def home(): return render_template('home.html', username=request.args.get('username')) if __name__ == "__main__": #To control the size of the upper production file, you can set the size of the request entity, file app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 #16MB app.debug = True app.run('0.0.0.0',80)
#post request
import requests, json
user_info = {'name': 'letian'}
headers = {'content-type': 'application/json'}
r = requests.post("http://127.0.0.1:5000/json", data=json.dumps(user_info), headers=headers)
print r.headers
print r.json()
Build corresponding parameters and set corresponding parameters to return from flask import Flask,url_for,request,render_template,redirect,session,make_response @app.route('/login', methods=['POST', 'GET']) def login(): if request.method == 'POST': ... if 'user' in session: ... else: title = request.args.get('title', 'Default') response = make_response(render_template('login.html', title=title), 200) response.headers['key'] = 'value' return response if __name__ == "__main__": app.run(debug=True)
request related properties
form receives POST/PUT request data, MultiDict Targets multidict such as searchword= request.args.get ('key', '') values can replace form and args Cookies requested by cookies, type of which is dict headers request header, type is dict Data contains the requested data, which is converted to a string, and cannot handle mimetype Files multidict with files uploaded by POST/PUT request Environ WSGI environment configuration Method request method, such as GET,POST Path get request file path base_url get domain name and request file path url get all URLs url_root get domain name blueprint name Endpoint endpoint match request JSON if the mimetype is application/json, it will parse JSON. If it is not, it will return None instead of get_json() MAX_CONTENT_LENGTH back to Max_ CONTENT_ Configuration key for length view_args = None a dictionary that matches the view parameter of the request. When an exception occurs during the matching, None will be returned. get_json(force=False, silent=False, cache=True) The lower one should not be used. Carry it on_json_loading_failed(e) Module if the request is sent to an actual module, this parameter returns the name of the current module. This is a deprecated feature, replaced by blueprints. routing_exception = None if the matching URL fails, this exception will / has been thrown as part of the request processing. This is usually used for NotFound exceptions or similar situations. url_rule = None internal rule matches the requested URL. This can be used to check whether the method allows before / after the URL( request.url_ rule.methods )Wait. By default, write "print" (' request.url_ rule.methods ', request.url_ rule.methods ) Will print: request.url_rule.methods {'GET', 'OPTIONS', 'HEAD'}