1. 前言
Flask 在处理请求与响应的过程:
首先我们从浏览器发送一个请求到服务端,由 Flask 接收了这个请求以后,这个请求将会由路由系统接收。然后在路由系统中,还可以挂入一些 "勾子",在进入我们的 viewFunction
以前做一些预处理。即产生一个 request 对象,可以获取一些变量、cookie等参数,再传入 viewFunction
里面做一个进一步的处理。处理完了以后,一般上不需要直接去产生一个 response,而是通过 render_template
传给 Flask。
2. login
login.html:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>方法:{{ method }}</h1>
<form method="post">
<div>
<input type="text"
name="username"
placeholder="User name" />
</div>
<div>
<input type="text"
name="password"
placeholder="Password" />
</div>
<input type="submit">
</form>
</body>
</html>
python
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
else:
username = request.args['username']
return render_template('login.html',method=request.method)
可直接使用浏览器传值:
3. 上传文件
python
@app.route('/upload', methods=['GET', 'POST'])
def uploads():
if request.method == 'POST':
f = request.files['file']
basepath = path.abspath(path.dirname(__file__)) # 获取当前绝对路径
upload_path = path.join(basepath, 'static/uploads')
f.save(upload_path, secure_filename(f.filename))
return redirect(url_for('uploads'))
return render_template('upload.html')
upload.html:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload new File</title>
</head>
<body>
<h1>文件上传示例</h1>
<form action=""
method="post"
enctype="multipart/form-data">
<p>
<input type="file"
name="file">
<input type="submit"
value="Upload">
</p>
</form>
</body>
</html>
4. errorhandler
对错误进行监控:
python
@app.errorhandler(404)
def page_not_found(error):
return render_template('404.html'), 404
@app.errorhandler(400)
def bad_request(error):
return render_template('400.html'), 400
404.html:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>404</h1>
<h2>很抱歉!</h2>
<p>您访问的页面并不存在</p>
</body>
</html>
400.html:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>400</h1>
<h2>很抱歉!</h2>
<p>您发送了一个错误的请求</p>
</body>
</html>