
运行1
如果是.py文件,使用下面的语句:
$ set FLASK_APP=hello.py
$ flask run
如果是文件夹,则为:
$ set FLASK_APP=hello
$ flask run
如果使用调试模式,在flask run前添加:
$ set FLASK_ENV=development
使服务器对外可见
Externally Visible Server If you run the server you will notice that
the server is only accessible from your own computer, not from any
other in the network. This is the default because in debugging mode a
user of the application can execute arbitrary Python code on your
computer.If you have the debugger disabled or trust the users on your network,
you can make the server publicly available simply by adding
–host=0.0.0.0 to the command line:$ flask run --host=0.0.0.0 This tells your operating system to listen
on all public IPs.
更多信息
关于部署,可以参考Deployment Options。
开发服务器的更多参数在Development Server。
关于调试器,可以参考Werkzeug documentation。
路由
使用route()装饰器来将函数绑定到URL上。
@app.route('/xxx/<var>')
def func():
return 'hello'
URL可以是动态的。<var>中的内容可以被用作参数,对其类型转换的操作如下。
类型转换
使用<converter:variable_name>来指定参数的类型。可指定的类型如下表:
| type | description |
|---|---|
string | (default) accepts any text without a slash |
int | accepts positive integers |
float | accepts positives floating point values |
path | like string but also accepts slashes |
uuid | accepts UUID strings |
url_for()
使用url_for()来将一个指向一个函数的URL。
也可以通过下面的方式指向一个静态文件。静态文件存放在static文件夹中,并作为url_for的endpoint参数。
url_for('static', filename='style.css')
HTTP方法
通常情况下,路由回应GET request。在app.route()中添加methods参数来处理不同的HTTP方法。例如:
from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return do_the_login()
return show_the_login_form()
Render Templates
使用render_template()方法来渲染一个template。可以将参数传递给template;template之间的继承在保持风格的同时也减少了代码量。
from flask import render_template
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
关于template的更多信息可参考Jinja2。
参数可以通过下面的方式从函数传递给template:
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}
在template可以获取request,session和g的对象信息,以及get_flashed_messages()函数。
Accessing Request Data
在flask中,客户端向服务器端发送的数据由全局对象request2回应。flask中使用Context Locals3来实现“全局对象” (测试或单元测试时需查阅)。
通过request对象的method4 属性来获取当前request的method。通过form5 属性来从POST或PUT请求访问数据。
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'
# the code below is executed if the request method
# was GET or the credentials were invalid
return render_template('login.html', error=error)
File Uploads
在HTML中设置:
enctype="multipart/form-data"
少量的信息在Quickstart中,更多信息在Uploading Files Pattern中。
Cookies
待更新
https://flask.palletsprojects.com/en/1.1.x/quickstart/#cookies
Redirects and Errors
from flask import abort, redirect, url_for
@app.route('/')
def index():
# to redirect a user to another endpoint, use the redirect() function
return redirect(url_for('login'))
@app.route('/login')
def login():
# to abort a request early with an error code, use the abort() function
abort(401)
this_is_never_executed()
如果想要修改错误页,使用errorhandle()装饰器。
from flask import render_template
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
Sessions
session在多个request的处理过程中存储当前的用户信息。
This is implemented on top of cookies for you and signs the cookies cryptographically. What this means is that the user could look at the contents of your cookie but not modify it, unless they know the secret key used for signing.
使用session需要设置一个secret key。
from flask import Flask, session, redirect, url_for, request
from markupsafe import escape
app = Flask(__name__)
# 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 'Logged in as %s' % escape(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'))
The escape() mentioned here does escaping for you if you are not using the template engine (as in this example).
使用下面的方法生成一个好的secret key。
$ python -c 'import os; print(os.urandom(16))'
b'_5#y2L"F4Q8z\n\xec]/'
Message Flashing
The flashing system basically makes it possible to record a message at the end of a request and access it on the next (and only the next) request. This is usually combined with a layout template to expose the message.
To flash a message use the flash() method, to get hold of the messages you can use get_flashed_messages() which is also available in the templates. Check out the Message Flashing for a full example.
Logging
The attached logger is a standard logging Logger, so head over to the official logging docs for more information.
Read more on Application Errors.
Using Flask Extensions
Extensions are packages that help you accomplish common tasks. For example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple and easy to use with Flask.
For more on Flask extensions, have a look at Extensions.
Deploying to a Web Server
未包含部分
- About Responses
- Hooking in WSGI Middleware
本文档介绍了Flask开发的基本操作,包括启动对外可见的服务器、路由设定、URL参数类型转换、url_for()的使用、HTTP方法处理、模板渲染、请求数据访问、文件上传、错误处理、会话管理、消息闪现、日志记录以及使用Flask扩展。提供了一个快速开始Flask应用的指南。
2121

被折叠的 条评论
为什么被折叠?



