💡 出于大创的需要,跑去看了一下flask的官方文档,并且简单记录了一下。不过现在回过头看发现好像只是把标题翻译了一下。这种记录似乎没啥意义,可能还是先跟着实战教程跑,跑的过程中记录自己遇到的问题以及解决问题的文档好一点
简单使用
基本示例:
1 2 3 4 5 6 7 8 9 10 from flask import Flaskapp = Flask(__name__) @app.route("/hello" ) def hello_world (): return "<p>Hello, World!</p>" @app.route('/' ) def index (): return 'Index Page'
启动项目:
1 2 3 4 5 6 7 //方法1: //将application实例所在文件命名为app.py, 而后在终端中执行 $ flask run //方法2: //application实例的所在的文件名为name.py或wsgi.py,则在终端中执行 $ flask --app name run
将项目部署到局域网
1 $ flask --app name run --host=0.0.0.0
路由设置 1 2 3 4 5 6 7 8 9 10 @app.route('/projects/' ) def projects (): return 'The project page' @app.route('/about' ) def about (): return 'The about page'
动态路由 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 from markupsafe import escape@app.route('/user/<username>' ) def show_user_profile (username ): return f'User {escape(username)} ' @app.route('/post/<int:post_id>' ) def show_post (post_id ): return f'Post {post_id} ' @app.route('/path/<path:subpath>' ) def show_subpath (subpath ): return f'Subpath {escape(subpath)} '
可变部分的类型有以下几种
类型
解释
string
(default) accepts any text without a /
int
accepts positive integers
float
accepts positive floating point values
path
like string but also accepts /
uuid
accepts UUID strings
路由导航与错误 1 2 3 4 5 6 7 8 9 10 11 from flask import abort, redirect, url_for@app.route('/' ) def index (): return redirect(url_for('login' )) @app.route('/login' ) def login (): abort(401 ) this_is_never_executed()
区分请求方法(get,post等) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 from flask import request@app.route('/login' , methods=['GET' , 'POST' ] ) def login (): if request.method == 'POST' : return do_the_login() else : return show_the_login_form() @app.get('/login' ) def login_get (): return show_the_login_form() @app.post('/login' ) def login_post (): return do_the_login()
处理请求的数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 from flask import request@app.route('/login' , methods=['POST' , 'GET' ] ) def login (): error = None if request.method == 'POST' : if valid_login(request.form['username' ], request.form['password' ]): return log_the_user_in(request.form['username' ]) else : error = 'Invalid username/password' return render_template('login.html' , error=error) searchword = request.args.get('key1' , 'key2' )
上传文件:
注!:前端的表单中需要设置enctype=”multipart/form-data”
1 2 3 4 5 6 7 8 from werkzeug.utils import secure_filename@app.route('/upload' , methods=['GET' , 'POST' ] ) def upload_file (): if request.method == 'POST' : file = request.files['the_file' ] file.save(f"/var/www/uploads/{secure_filename(file.filename)} " ) ...
Cookies 1 2 3 4 5 6 7 8 9 10 11 12 13 from flask import request@app.route('/' ) def index (): username = request.cookies.get('username' ) resp = make_response(render_template(...)) resp.set_cookie('username' , 'the username' ) return resp
JSON的编码与解码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 @app.route("/me" ) def me_api (): user = get_current_user() return { "username" : user.username, "theme" : user.theme, "image" : url_for("user_image" , filename=user.image), } @app.route("/users" ) def users_api (): users = get_all_users() return [user.to_json() for user in users]
Session 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 from flask import sessionapp.secret_key = b'_5#y2L"F4Q8z\n\xec]/' @app.route('/' ) def index (): if 'username' in session: return f'Logged in as {session["username" ]} ' return 'You are not logged in' @app.route('/login' , methods=['GET' , 'POST' ] ) def login (): if request.method == 'POST' : session['username' ] = request.form['username' ] return redirect(url_for('index' )) return ''' <form method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ''' @app.route('/logout' ) def logout (): session.pop('username' , None ) return redirect(url_for('index' ))
未记录的部分 静态资源的传输:Static Files
后端渲染:Rendering Templates
Accessing Request Data
404页面自定义:Handling Application Errors — Flask Documentation (2.3.x) (palletsprojects.com)