💡 出于大创的需要,跑去看了一下flask的官方文档,并且简单记录了一下。不过现在回过头看发现好像只是把标题翻译了一下。这种记录似乎没啥意义,可能还是先跟着实战教程跑,跑的过程中记录自己遇到的问题以及解决问题的文档好一点

简单使用

1
pip install flask

基本示例:

1
2
3
4
5
6
7
8
9
10
from flask import Flask

app = 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
#访问/projects/ 或者 /projects 都行
@app.route('/projects/')
def projects():
return 'The project page'

#只能访问/about, 访问/about/报错
#据说有助于保持这些资源的URL唯一
@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):
# show the user profile for that user
return f'User {escape(username)}'

#规定可变部分的类型
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return f'Post {post_id}'

@app.route('/path/<path:subpath>')
def show_subpath(subpath):
# show the subpath after /path/
return f'Subpath {escape(subpath)}'

#escape是一个用来防止前端注入的函数
#以下是new bing对escape函数的解释
#escape()函数是用来对HTML文本进行转义的
#也就是把一些特殊字符替换成它们的HTML实体表示
#这样可以避免在网页中出现不安全或者不正确的内容。
#例如,如果你想在网页中显示一个用户的名字,但是用户的名字可能包含一些HTML标签
#那么你就需要用escape()函数来处理一下
#否则可能会影响网页的布局或者执行一些恶意的代码。

可变部分的类型有以下几种

类型 解释
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():
#url_for(函数名)返回函数所在的路径
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()

#也可把get与post直接分开配置
@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':
#valid_login是需要自定义的函数
if valid_login(request.form['username'],
request.form['password']):
return log_the_user_in(request.form['username'])
else:
error = 'Invalid username/password'
# the code below is executed if the request method
# was GET or the credentials were invalid
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():
#读cookies
username = request.cookies.get('username')
# use cookies.get(key) instead of cookies[key] to not get a
# KeyError if the cookie is missing.

#存cookies
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
#dict与list结构的返回值再返回头中会自动转化为JSON格式
@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 session

# Set the secret key to some random bytes. Keep this really secret!
app.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():
# remove the username from the session if it's there
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)