参考:https://dormousehole.readthedocs.io/en/latest/quickstart.html
这里笔者采用的是PyCharm开发Flask,所以创建项目之后就可以看到这个最简单的应用。
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world(): # put application's code here
return 'Hello World!'
代码含义:
运行之后如下所示:
FLASK_APP = app.py
FLASK_ENV = development
FLASK_DEBUG = 0
In folder E:/PythonWeb_new/flaskFasttry
C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\python.exe -m flask run
- Serving Flask app ‘app.py’
- Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.- Running on http://127.0.0.1:5000
Press CTRL+C to quit
可以点击该网址,就可看到该程序。
编辑配置中勾选FLASK_DEBUG就可以实时修改程序实时更新内容。
为了防止注入攻击,所有用户提供的值在输出渲染前必须被转义。使用Jinja渲染的HTML会自动执行此操作。
也可以使用escape手动转义。
from markupsafe import escape
@app.route('/' )
def hello_world(name): # put application's code here
return f'Hello {escape(name)}!'
现代Web应用的URL是有意义的,有利于记忆。
使用route()装饰器来把函数绑定到URL:
@app.route('/' )
def hello_world(name): # put application's code here
return f'Hello {escape(name)}!'
@app.route('/hello')
def hello(): # put application's code here
return f'Hello!'
通过把URL的一部分标记为
@app.route('/post/' )
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/' )
def show_subpath(subpath):
# show the subpath after /path/
return f'Subpath {escape(subpath)}'
转换器类型:
| string | 接受任何不包含斜杠的文本 |
|---|---|
| int | 正整数 |
| float | 正浮点数 |
| path | 类似string,允许包含/ |
| uuid | 接受UUID字符串 |
以下两条规则的不同之处在于是否使用尾部的斜杠。:
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'
projects 的 URL 是中规中矩的,尾部有一个斜杠,看起来就如同一个文件 夹。访问一个没有斜杠结尾的 URL ( /projects )时 Flask 会自动进行重 定向,帮您在尾部加上一个斜杠( /projects/ )。
about 的 URL 没有尾部斜杠,因此其行为表现与一个文件类似。如果访问这 个 URL 时添加了尾部斜杠(/about/ )就会得到一个 404 “未找到” 错 误。这样可以保持 URL 唯一,并有助于搜索引擎重复索引同一页面。
url_for()函数用于构建指定函数的URL。第一个参数是函数名称。接受任意个关键字参数,每个关键字参数对应URL中的变量。
Web应用使用不同的HTTP方法处理URL。默认使用GET请求。考科一使用route()装饰器methods参数来处理不同的HTTP方法。
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()
动态的web应用也需要静态文件,一般是CSS和JavaScript文件。静态文件位于应用的/static中。
使用特定的‘static’端点就可以生成响应的URL。
url_for('static', filename='style.css')
Flask自动配置Jinjia2模板引擎。
使用render_template()方法可以渲染模板,
render_template()
参数:
首先,需要导入请求对象。
from flask import request
通过使用 method 属性可以操作当前请求方法,通过使用 form 属性处理表单数据(在 POST 或者 PUT 请求 中传输的数据)。以下是使用上述两个属性的例子:
@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'
# the code below is executed if the request method
# was GET or the credentials were invalid
return render_template('login.html', error=error)
不要忘记在HTML表单中设置enctype=“multipart/form-data”,否则浏览器将不会传送您的文件。
已上传的文件被储存在内存或文件系统的临时位置。您可以通过请求对象 files 属性来访问上传的文件。每个上传的文件都储存在这个 字典型属性中。这个属性基本和标准 Python file 对象一样,另外多出一个 用于把上传文件保存到服务器的文件系统中的 save() 方法。下例展示其如何运作:
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')
...
如果想要知道文件上传之前其在客户端系统中的名称,可以使用 filename 属性。但是请牢记这个值是 可以伪造的,永远不要信任这个值。如果想要把客户端的文件名作为服务器上的文件名, 可以通过 Werkzeug 提供的 secure_filename() 函数:
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 ,可以使用 cookies 属性。可以使用响应 对象 的 set_cookie 方法来设置 cookies 。请求对象的 cookies 属性是一个包含了客户端传输的所有 cookies 的字典。在 Flask 中,如果使用 会话 ,那么就不要直接使用 cookies ,因为 会话 比较安全一些。
读取cookies:
from flask import request
@app.route('/')
def index():
username = request.cookies.get('username')
# use cookies.get(key) instead of cookies[key] to not get a
# KeyError if the cookie is missing.
储存cookies:
from flask import make_response
@app.route('/')
def index():
resp = make_response(render_template(...))
resp.set_cookie('username', 'the username')
return resp
使用redirect()函数可以重定向。使用abort()可以更早退出请求,并返回错误代码:
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()
使用 errorhandler() 装饰器可以定制出错页面:
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
用 Flask 写这样的 API 是很容易上手的。如果从视图 返回一个 dict ,那么它会被转换为一个 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),
}
还可以使用jsonify()。
@app.route("/users")
def users_api():
users = get_all_users()
return jsonify([user.to_json() for user in users])
除了请求对象之外,还有一种称为session的对象,可以使用它在不同请求之间储存信息。这个对象相当于用密钥加密的cookie,即用户可以查看您的cookie,但是如果没有密钥就无法修改它。
使用会话之前您必须设置一个密钥。举例说明:
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 '''
'''
@app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('index'))