How Python uses the web framework Flask to develop projects

WBOY
Release: 2023-05-13 17:19:06
forward
1978 people have browsed it

1. Introduction

Flask is a lightweight Python-based web framework.

The code in this document runs using Python 3.
It is recommended to practice command line operations and execute code in this tutorial under Linux.

2. Installation

Just install Flask through pip3:

$ sudo pip3 install Flask
Copy after login

Enter python interactive mode to see the introduction and version of Flask:

$ python3
 
>>> import flask
>>> print(flask.__doc__)
 
    flask
    ~~~~~
 
    A microframework based on Werkzeug.  It's extensively documented
    and follows best practice patterns.
 
    :copyright: © 2010 by the Pallets team.
    :license: BSD, see LICENSE for more details.
 
>>> print(flask.__version__)
1.0.2
Copy after login

3. Start with Hello World

The main content of this section: Use Flask to write a web program that displays "Hello World!", and how to configure and debug Flask.

3.1 Hello World

Follow the following command to create the Flask project HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

static and templates directories are the default configuration. Among them, static is used to store static resources, such as pictures, js, css files, etc. templatesStorage template files.
Our website logic is basically in the server.py file. Of course, this file can also be given other names.

Add the following content to server.py:

from flask import Flask
 
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    return 'Hello World!'
 
if __name__ == '__main__':
    app.run()
Copy after login

Run server.py:

$ python3 server.py 
 * Running on http://127.0.0.1:5000/
Copy after login

Open the browser and visit http://127.0.0.1:5000/, browse Hello World! will appear on the page.
The following information will be displayed in the terminal:

127.0.0.1 - - [16/May/2014 10:29:08] "GET / HTTP/1.1" 200 -
Copy after login

The variable app is a Flask instance, through the following method:

@app.route('/')
def hello_world():
    return 'Hello World!'
Copy after login

When the client accesses /, it will respond to hello_world ()The content returned by the function. Note that this is not as simple as returning Hello World!. Hello World! is just the entity part of the HTTP response message. Information such as status codes can be automatically processed by Flask or formulated through programming.

3.2 Modify the configuration of Flask

app = Flask(__name__)
Copy after login

In the above code, the value of the python built-in variable __name__ is the string __main__. The Flask class takes this parameter as the program name. Of course, this can be customized, such as app = Flask("my-app").

Flask uses the static directory to store static resources by default, and the templates directory to store templates. This can be changed by setting parameters:

app = Flask("my-app", static_folder="path2", template_folder="path3")
Copy after login

More Please refer to __doc__ for parameters:

from flask import Flask
print(Flask.__doc__)
Copy after login

3.3 Debug mode

The above server.py is run in app.run() mode. This In this mode, if an error occurs on the server side, it will not be displayed on the client side. However, in a development environment, it is necessary to display error messages. To display error messages, you should run Flask in the following way:

app.run(debug=True)
Copy after login

Set debug to True# Another benefit of ## is that after the program starts, it will automatically detect whether the source code has changed, and if there are changes, it will automatically restart the program. This can save us a lot of time.

3.4 Binding IP and Port

By default, Flask binds IP to

127.0.0.1 and port to 5000. We can also customize it in the following way:

app.run(host='0.0.0.0', port=80, debug=True)
Copy after login

0.0.0.0 represents all IPs of the computer. 80 is the default port for HTTP website services. What is default? For example, when we visit the website http://www.example.com, we actually visit http://www.example.com:80, but :80 can be omitted.

Since port 80 is bound, server.py needs to be run with root privileges. That is:

$ sudo python3 server.py
Copy after login

4. Get URL parameters

URL parameters are key-value pairs that appear in the url, such as http://127.0.0.1:5000/?disp=3 The url parameter is

{'disp':3}.

4.1 Create the Flask project

Follow the following command to create the Flask project HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

4.2 List all url parameters

Add in server.py The following content:

from flask import Flask, request
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return request.args.__str__()
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

Visit http://127.0.0.1:5000/?user=Flask&time&p=7&p=8 in the browser, it will display:

ImmutableMultiDict([('user', 'Flask'), ('time', ''), ('p', '7'), ('p', '8')])
Copy after login

Newer browsers also Supports inputting Chinese directly into the URL (the latest Firefox browser will help convert Chinese into data that conforms to URL specifications), and access http://127.0.0.1:5000/?info=This is love in the browser. It will be displayed:

ImmutableMultiDict([('info', '这是爱,')])
Copy after login

What does the data sent by the browser to our Flask service look like? You can take a look at

request.full_path and request.path:

from flask import Flask, request
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    print(request.path)
    print(request.full_path)
    return request.args.__str__()
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

Browser access http://127.0.0.1:5000/?info=This is Love, the terminal running server.py will output:

1./
##2./?info=This is love,

4.3 Get a specified parameter

For example, to get the value corresponding to the key

info

, modify server.py as follows: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:py;">from flask import Flask, request app = Flask(__name__) @app.route('/') def hello_world(): return request.args.get('info') if __name__ == '__main__': app.run(port=5000)</pre><div class="contentsignin">Copy after login</div></div>Run server.py and access http://127.0.0.1 in the browser: 5000/?info=hello, the browser will display:

hello
Copy after login

However, when we access http://127.0.0.1:5000/, a 500 error appears

Why is this?

This is because

info

was not found in the URL parameters. So request.args.get('info') returns Python's built-in None, and Flask is not allowed to return None. The solution is very simple. Let’s first determine whether it is None:

from flask import Flask, request
 
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    r = request.args.get('info')
    if r==None:
        # do something
        return ''
    return r
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

Another method is to set a default value, that is, use this value when the data cannot be obtained:

The second parameter of
from flask import Flask, request
 
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    r = request.args.get('info', 'hi')
    return r
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

function

request.args.get

is used to set the default value. At this time, when accessing http://127.0.0.1:5000/ in the browser, it will display: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:plain;">hi</pre><div class="contentsignin">Copy after login</div></div><h4>4.4 如何处理多值</h4><p>还记得上面有一次请求是这样的吗? http://127.0.0.1:5000/?user=Flask&time&p=7&p=8,仔细看下,<code>p有两个值。

如果我们的代码是:

from flask import Flask, request
 
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    r = request.args.get('p')
    return r
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

在浏览器中请求时,我们只会看到7。如果我们需要把p的所有值都获取到,该怎么办?

不用get,用getlist

from flask import Flask, request
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    r = request.args.getlist('p')  # 返回一个list
    return str(r)
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

浏览器输入 http://127.0.0.1:5000/?user=Flask&time&p=7&p=8,我们会看到['7', '8']

五、获取POST方法传送的数据

作为一种HTTP请求方法,POST用于向指定的资源提交要被处理的数据。我们在某网站注册用户、写文章等时候,需要将数据传递到网站服务器中。并不适合将数据放到URL参数中,密码放到URL参数中容易被看到,文章数据又太多,浏览器不一定支持太长长度的URL。这时,一般使用POST方法。

本文使用python的requests库模拟浏览器。

安装方法:

$ sudo pip3 install requests
Copy after login

5.1 建立Flask项目

按照以下命令建立Flask项目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

5.2 查看POST数据内容

以用户注册为例子,我们需要向服务器/register传送用户名name和密码password。如下编写HelloWorld/server.py。

from flask import Flask, request
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/register', methods=['POST'])
def register():
    print(request.headers)
    print(request.stream.read())
    return 'welcome'
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

`@app.route(‘/register’, methods=[‘POST’])是指url/register只接受POST方法。可以根据需要修改methods`参数,例如如果想要让它同时支持GET和POST,这样写:

@app.route('/register', methods=['GET', 'POST'])
Copy after login

浏览器模拟工具client.py内容如下:

import requests
 
user_info = {'name': 'letian', 'password': '123'}
r = requests.post("http://127.0.0.1:5000/register", data=user_info)
 
print(r.text)
Copy after login

运行HelloWorld/server.py,然后运行client.py。client.py将输出:

welcome
Copy after login

而HelloWorld/server.py在终端中输出以下调试信息(通过print输出):

Host: 127.0.0.1:5000
User-Agent: python-requests/2.19.1
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Length: 24
Content-Type: application/x-www-form-urlencoded
 
 
b'name=letian&password=123'
Copy after login

前6行是client.py生成的HTTP请求头,由print(request.headers)输出。

请求体的数据,我们通过print(request.stream.read())输出,结果是:

b'name=letian&password=123'
Copy after login

5.3 解析POST数据

上面,我们看到post的数据内容是:

b'name=letian&password=123'
Copy after login

我们要想办法把我们要的name、password提取出来,怎么做呢?自己写?不用,Flask已经内置了解析器request.form

我们将服务代码改成:

from flask import Flask, request
 
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/register', methods=['POST'])
def register():
    print(request.headers)
    # print(request.stream.read()) # 不要用,否则下面的form取不到数据
    print(request.form)
    print(request.form['name'])
    print(request.form.get('name'))
    print(request.form.getlist('name'))
    print(request.form.get('nickname', default='little apple'))
    return 'welcome'
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

执行client.py请求数据,服务器代码会在终端输出:

Host: 127.0.0.1:5000
User-Agent: python-requests/2.19.1
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Length: 24
Content-Type: application/x-www-form-urlencoded
 
 
ImmutableMultiDict([('name', 'letian'), ('password', '123')])
letian
letian
['letian']
little apple
Copy after login

request.form会自动解析数据。

request.form['name']request.form.get('name')都可以获取name对应的值。对于request.form.get()可以为参数default指定值以作为默认值。所以:

print(request.form.get('nickname', default='little apple'))
Copy after login

输出的是默认值

little apple
Copy after login

如果name有多个值,可以使用request.form.getlist('name'),该方法将返回一个列表。我们将client.py改一下:

import requests
 
user_info = {'name': ['letian', 'letian2'], 'password': '123'}
r = requests.post("http://127.0.0.1:5000/register", data=user_info)
 
print(r.text)
Copy after login

此时运行client.py,print(request.form.getlist('name'))将输出:

[u'letian', u'letian2']
Copy after login

六、处理和响应JSON数据

使用 HTTP POST 方法传到网站服务器的数据格式可以有很多种,比如「5. 获取POST方法传送的数据」讲到的name=letian&password=123这种用过&符号分割的key-value键值对格式。我们也可以用JSON格式、XML格式。相比XML的重量、规范繁琐,JSON显得非常小巧和易用。

6.1 建立Flask项目

按照以下命令建立Flask项目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

6.2 处理JSON格式的请求数据

如果POST的数据是JSON格式,request.json会自动将json数据转换成Python类型(字典或者列表)。

编写server.py:

from flask import Flask, request
 
app = Flask("my-app")
 
 
@app.route('/')
def hello_world():
    return 'Hello World!'
 
 
@app.route('/add', methods=['POST'])
def add():
    print(request.headers)
    print(type(request.json))
    print(request.json)
    result = request.json['a'] + request.json['b']
    return str(result)
 
 
if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000, debug=True)
Copy after login

编写client.py模拟浏览器请求:

import requests
 
json_data = {'a': 1, 'b': 2}
 
r = requests.post("http://127.0.0.1:5000/add", json=json_data)
 
print(r.text)
Copy after login

运行server.py,然后运行client.py,client.py 会在终端输出:

3
Copy after login

server.py 会在终端输出:

Host: 127.0.0.1:5000
User-Agent: python-requests/2.19.1
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Length: 16
Content-Type: application/json
 
 

{'a': 1, 'b': 2}
Copy after login

注意,请求头中Content-Type的值是application/json

6.3 响应JSON-方案1

响应JSON时,除了要把响应体改成JSON格式,响应头的Content-Type也要设置为application/json

编写server2.py:

from flask import Flask, request, Response
import json
 
app = Flask("my-app")
 
 
@app.route('/')
def hello_world():
    return 'Hello World!'
 
 
@app.route('/add', methods=['POST'])
def add():
    result = {'sum': request.json['a'] + request.json['b']}
    return Response(json.dumps(result),  mimetype='application/json')
 
 
if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000, debug=True)
Copy after login

修改后运行。

编写client2.py:

import requests
 
json_data = {'a': 1, 'b': 2}
 
r = requests.post("http://127.0.0.1:5000/add", json=json_data)
 
print(r.headers)
print(r.text)
Copy after login

运行client.py,将显示:

{'Content-Type': 'application/json', 'Content-Length': '10', 'Server': 'Werkzeug/0.14.1 Python/3.6.4', 'Date': 'Sat, 07 Jul 2018 05:23:00 GMT'}

{"sum": 3}
Copy after login

上面第一段内容是服务器的响应头,第二段内容是响应体,也就是服务器返回的JSON格式数据。

另外,如果需要服务器的HTTP响应头具有更好的可定制性,比如自定义Server,可以如下修改add()函数:

@app.route('/add', methods=['POST'])
def add():
    result = {'sum': request.json['a'] + request.json['b']}
    resp = Response(json.dumps(result),  mimetype='application/json')
    resp.headers.add('Server', 'python flask')
    return resp
Copy after login

client2.py运行后会输出:

{'Content-Type': 'application/json', 'Content-Length': '10', 'Server': 'python flask', 'Date': 'Sat, 07 Jul 2018 05:26:40 GMT'}

{"sum": 3}
Copy after login

6.4 响应JSON-方案2

使用 jsonify 工具函数即可。

from flask import Flask, request, jsonify
 
app = Flask("my-app")
 
 
@app.route('/')
def hello_world():
    return 'Hello World!'
 
 
@app.route('/add', methods=['POST'])
def add():
    result = {'sum': request.json['a'] + request.json['b']}
    return jsonify(result)
 
 
if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000, debug=True)
Copy after login

七、上传文件

上传文件,一般也是用POST方法。

7.1 建立Flask项目

按照以下命令建立Flask项目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

7.2 上传文件

这一部分的代码参考自How to upload a file to the server in Flask。

我们以上传图片为例:
假设将上传的图片只允许’png’、’jpg’、’jpeg’、’gif’这四种格式,通过url/upload使用POST上传,上传的图片存放在服务器端的static/uploads目录下。

首先在项目HelloWorld中创建目录static/uploads

mkdir HelloWorld/static/uploads
Copy after login

werkzeug库可以判断文件名是否安全,例如防止文件名是../../../a.png,安装这个库:

$ sudo pip3 install werkzeug
Copy after login

server.py代码:

from flask import Flask, request
 
from werkzeug.utils import secure_filename
import os
 
app = Flask(__name__)
 
# 文件上传目录
app.config['UPLOAD_FOLDER'] = 'static/uploads/'
# 支持的文件格式
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'}  # 集合类型
 
 
# 判断文件名是否是我们支持的格式
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/upload', methods=['POST'])
def upload():
    upload_file = request.files['image']
    if upload_file and allowed_file(upload_file.filename):
        filename = secure_filename(upload_file.filename)
        # 将文件保存到 static/uploads 目录,文件名同上传时使用的文件名
        upload_file.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename))
        return 'info is '+request.form.get('info', '')+'. success'
    else:
        return 'failed'
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

app.config中的config是字典的子类,可以用来设置自有的配置信息,也可以设置自己的配置信息。函数allowed_file(filename)用来判断filename是否有后缀以及后缀是否在app.config['ALLOWED_EXTENSIONS']中。

客户端上传的图片必须以image01标识。upload_file是上传文件对应的对象。app.root_path获取server.py所在目录在文件系统中的绝对路径。upload_file.save(path)用来将upload_file保存在服务器的文件系统中,参数最好是绝对路径,否则会报错(网上很多代码都是使用相对路径,但是笔者在使用相对路径时总是报错,说找不到路径)。函数os.path.join()用来将使用合适的路径分隔符将路径组合起来。

好了,定制客户端client.py:

import requests
file_data = {'image': open('Lenna.jpg', 'rb')}
user_info = {'info': 'Lenna'}
r = requests.post("http://127.0.0.1:5000/upload", data=user_info, files=file_data)
print(r.text)
Copy after login

运行client.py,当前目录下的Lenna.jpg将上传到服务器。

然后,我们可以在static/uploads中看到文件Lenna.jpg。

要控制上产文件的大小,可以设置请求实体的大小,例如:

app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 #16MB
Copy after login

不过,在处理上传文件时候,需要使用try:...except:...

如果要获取上传文件的内容可以:

file_content = request.files['image'].stream.read()
Copy after login

八、Restful URL

简单来说,Restful URL可以看做是对 URL 参数的替代。

8.1 建立Flask项目

按照以下命令建立Flask项目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

8.2 编写代码

编辑server.py:

from flask import Flask
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/user/')
def user(username):
    print(username)
    print(type(username))
    return 'hello ' + username
 
 
@app.route('/user//friends')
def user_friends(username):
    print(username)
    print(type(username))

    return 'hello ' + username
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

运行HelloWorld/server.py。使用浏览器访问http://127.0.0.1:5000/user/letian,HelloWorld/server.py将输出:

letian
Copy after login
Copy after login

而访问http://127.0.0.1:5000/user/letian/,响应为404 Not Found。

浏览器访问http://127.0.0.1:5000/user/letian/friends,可以看到:

Hello letian. They are your friends.
Copy after login

HelloWorld/server.py输出:

letian
Copy after login
Copy after login

8.3 转换类型

由上面的示例可以看出,使用 Restful URL 得到的变量默认为str对象。如果我们需要通过分页显示查询结果,那么需要在url中有数字来指定页数。按照上面方法,可以在获取str类型页数变量后,将其转换为int类型。不过,还有更方便的方法,就是用flask内置的转换机制,即在route中指定该如何转换。

新的服务器代码:

from flask import Flask
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/page/')
def page(num):
    print(num)
    print(type(num))
    return 'hello world'
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

`@app.route(‘/page/int:num‘)`会将num变量自动转换成int类型。

运行上面的程序,在浏览器中访问http://127.0.0.1:5000/page/1,HelloWorld/server.py将输出如下内容:

1
Copy after login

如果访问的是http://127.0.0.1:5000/page/asd,我们会得到404响应。

在官方资料中,说是有3个默认的转换器:

int     accepts integers

float     like int but for floating point values

path     like the default but also accepts slashes
Copy after login

看起来够用了。

8.4 一个有趣的用法

如下编写服务器代码:

from flask import Flask
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/page/-')
def page(num1, num2):
    print(num1)
    print(num2)
    return 'hello world'
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

在浏览器中访问http://127.0.0.1:5000/page/11-22,HelloWorld/server.py会输出:

11

22
Copy after login

8.5 编写转换器

自定义的转换器是一个继承werkzeug.routing.BaseConverter的类,修改to_pythonto_url方法即可。to_python方法用于将url中的变量转换后供被`@app.route包装的函数使用,to_url方法用于flask.url_for`中的参数转换。

下面是一个示例,将HelloWorld/server.py修改如下:

from flask import Flask, url_for
 
from werkzeug.routing import BaseConverter
 
 
class MyIntConverter(BaseConverter):
 
    def __init__(self, url_map):
        super(MyIntConverter, self).__init__(url_map)
 
    def to_python(self, value):
        return int(value)
 
    def to_url(self, value):
        return value * 2
 
 
app = Flask(__name__)
app.url_map.converters['my_int'] = MyIntConverter
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/page/')
def page(num):
    print(num)
    print(url_for('page', num=123))   # page 对应的是 page函数 ,num 对应对应`/page/`中的num,必须是str
    return 'hello world'
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

浏览器访问http://127.0.0.1:5000/page/123后,HelloWorld/server.py的输出信息是:

123

/page/123123
Copy after login

九、使用url_for生成链接

工具函数url_for可以让你以软编码的形式生成url,提供开发效率。

9.1 建立Flask项目

按照以下命令建立Flask项目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

9.2 编写代码

编辑HelloWorld/server.py:

from flask import Flask, url_for
 
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    pass
 
@app.route('/user/')
def user(name):
    pass
 
@app.route('/page/')
def page(num):
    pass
 
@app.route('/test')
def test():
    print(url_for('hello_world'))
    print(url_for('user', name='letian'))
    print(url_for('page', num=1, q='hadoop mapreduce 10%3'))
    print(url_for('static', filename='uploads/01.jpg'))
    return 'Hello'
 
if __name__ == '__main__':
    app.run(debug=True)
Copy after login

运行HelloWorld/server.py。然后在浏览器中访问http://127.0.0.1:5000/test,HelloWorld/server.py将输出以下信息:

/
/user/letian
/page/1?q=hadoop+mapreduce+10%253
/static/uploads/01.jpg
Copy after login

十、使用redirect重定向网址

redirect函数用于重定向,实现机制很简单,就是向客户端(浏览器)发送一个重定向的HTTP报文,浏览器会去访问报文中指定的url。

10.1 建立Flask项目

按照以下命令建立Flask项目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

10.2 编写代码

使用redirect时,给它一个字符串类型的参数就行了。

编辑HelloWorld/server.py:

from flask import Flask, url_for, redirect
 
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    return 'hello world'
 
@app.route('/test1')
def test1():
    print('this is test1')
    return redirect(url_for('test2'))
 
@app.route('/test2')
def test2():
    print('this is test2')
    return 'this is test2'
 
if __name__ == '__main__':
    app.run(debug=True)
Copy after login

运行HelloWorld/server.py,在浏览器中访问http://127.0.0.1:5000/test1,浏览器的url会变成http://127.0.0.1:5000/test2,并显示:

this is test2
Copy after login

十一、使用Jinja2模板引擎

模板引擎负责MVC中的V(view,视图)这一部分。Flask默认使用Jinja2模板引擎。

Flask与模板相关的函数有:

  • flask.render_template(template_name_or_list, **context)
    Renders a template from the template folder with the given context.

  • flask.render_template_string(source, **context)
    Renders a template from the given template source string with the given context.

  • flask.get_template_attribute(template_name, attribute)
    Loads a macro (or variable) a template exports. This can be used to invoke a macro from within Python code.

这其中常用的就是前两个函数。

这个实例中使用了模板继承、if判断、for循环。

11.1 建立Flask项目

按照以下命令建立Flask项目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

11.2 创建并编辑HelloWorld/templates/default.html

内容如下:

<html>
<head>
    <title>
        {% if page_title %}
            {{ page_title }}
        {% endif %}
    </title>
</head>
 
<body>
    {% block body %}{% endblock %}
 
 
```
可以看到,在``标签中使用了if判断,如果给模板传递了`page_title`变量,显示之,否则,不显示。
``标签中定义了一个名为`body`的block,用来被其他模板文件继承。
### 11.3 创建并编辑HelloWorld/templates/user_info.html
内容如下:
```
{% extends "default.html" %}
 
{% block body %}
    {% for key in user_info %}
 
        {{ key }}: {{ user_info[key] }} 
 
 
    {% endfor %}
{% endblock %}
Copy after login

变量user_info应该是一个字典,for循环用来循环输出键值对。

11.4 编辑HelloWorld/server.py

内容如下:

from flask import Flask, render_template
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/user')
def user():
    user_info = {
        'name': 'letian',
        'email': '123@aa.com',
        'age':0,
        'github': 'https://github.com/letiantian'
    }
    return render_template('user_info.html', page_title='letian\'s info', user_info=user_info)
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

render_template()函数的第一个参数指定模板文件,后面的参数是要传递的数据。

11.5 运行与测试

运行HelloWorld/server.py:

$ python3 HelloWorld/server.py
Copy after login

在浏览器中访问http://127.0.0.1:5000/user

查看网页源码:

<html>
<head>
    <title>
            letian&&9;s info
    </title>
</head>
<body>
        name: letian <br/>
        email: 123@aa.com <br/>
        age: 0 <br/>
        github: https://github.com/letiantian <br/>
</body>
</html>
Copy after login

十二、自定义404等错误的响应

要处理HTTP错误,可以使用flask.abort函数。

12.1 示例1:简单入门

建立Flask项目

按照以下命令建立Flask项目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

代码

编辑HelloWorld/server.py:

from flask import Flask, render_template_string, abort
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/user')
def user():
    abort(401)  # Unauthorized 未授权
    print('Unauthorized, 请先登录')
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

效果

运行HelloWorld/server.py,浏览器访问http://127.0.0.1:5000/user

要注意的是,HelloWorld/server.py中abort(401)后的print并没有执行。

12.2 示例2:自定义错误页面

代码

将服务器代码改为:

from flask import Flask, render_template_string, abort
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/user')
def user():
    abort(401)  # Unauthorized
 
 
@app.errorhandler(401)
def page_unauthorized(error):
    return render_template_string('
 Unauthorized 
{{ error_info }}', error_info=error), 401
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

page_unauthorized函数返回的是一个元组,401 代表HTTP 响应状态码。如果省略401,则响应状态码会变成默认的 200。

效果

运行HelloWorld/server.py,浏览器访问http://127.0.0.1:5000/user

十三、用户会话

session用来记录用户的登录状态,一般基于cookie实现。

下面是一个简单的示例。

13.1 建立Flask项目

按照以下命令建立Flask项目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

13.2 编辑HelloWorld/server.py

内容如下:

from flask import Flask, render_template_string, \
    session, request, redirect, url_for
 
app = Flask(__name__)
 
app.secret_key = 'F12Zr47j\3yX R~X@H!jLwf/T'
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/login')
def login():
     return render_template_string(page)
@app.route('/do_login', methods=['POST'])
def do_login():
    name = request.form.get('user_name')
    session['user_name'] = name
    return 'success'
 
 
@app.route('/show')
def show():
    return session['user_name']
 
 
@app.route('/logout')
def logout():
    session.pop('user_name', None)
    return redirect(url_for('login'))
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

13.3 代码的含义

app.secret_key用于给session加密。

/login中将向用户展示一个表单,要求输入一个名字,submit后将数据以post的方式传递给/do_login/do_login将名字存放在session中。

如果用户成功登录,访问/show时会显示用户的名字。此时,打开firebug等调试工具,选择session面板,会看到有一个cookie的名称为session

/logout用于登出,通过将session中的user_name字段pop即可。Flask中的session基于字典类型实现,调用pop方法时会返回pop的键对应的值;如果要pop的键并不存在,那么返回值是pop()的第二个参数。

另外,使用redirect()重定向时,一定要在前面加上return

13.4 效果

进入http://127.0.0.1:5000/login,输入name,点击submit

进入http://127.0.0.1:5000/show查看session中存储的name:

How Python uses the web framework Flask to develop projects

13.5 设置sessin的有效时间

下面这段代码来自Is there an easy way to make sessions timeout in flask?:

from datetime import timedelta
from flask import session, app
 
session.permanent = True
app.permanent_session_lifetime = timedelta(minutes=5)
Copy after login

这段代码将session的有效时间设置为5分钟。

十四、使用Cookie

Cookie是存储在客户端的记录访问者状态的数据。 常用的用于记录用户登录状态的session大多是基于cookie实现的。

cookie可以借助flask.Response来实现。下面是一个示例。

14.1 建立Flask项目

按照以下命令建立Flask项目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

14.2 代码

修改HelloWorld/server.py:

from flask import Flask, request, Response, make_response
import time
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/add')
def login():
    res = Response('add cookies')
    res.set_cookie(key='name', value='letian', expires=time.time()+6*60)
    return res
 
 
@app.route('/show')
def show():
    return request.cookies.__str__()
 
 
@app.route('/del')
def del_cookie():
    res = Response('delete cookies')
    res.set_cookie('name', '', expires=0)
    return res
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)
Copy after login

由上可以看到,可以使用Response.set_cookie添加和删除cookie。expires参数用来设置cookie有效时间,它的值可以是datetime对象或者unix时间戳,笔者使用的是unix时间戳。

res.set_cookie(key='name', value='letian', expires=time.time()+6*60)
Copy after login

上面的expire参数的值表示cookie在从现在开始的6分钟内都是有效的。

要删除cookie,将expire参数的值设为0即可:

res.set_cookie('name', '', expires=0)
Copy after login

set_cookie()函数的原型如下:

set_cookie(key, value=’’, max_age=None, expires=None, path=’/‘, domain=None, secure=None, httponly=False)

Sets a cookie. The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data, too.
Parameters:

key – the key (name) of the cookie to be set.
value – the value of the cookie.
max_age – should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session.

expires – should be a datetime object or UNIX timestamp.

domain – if you want to set a cross-domain cookie. For example, domain=”.example.com” will set a cookie that is readable by the domain www.example.com, foo.example.com etc. Otherwise, a cookie will only be readable by the domain that set it.

path – limits the cookie to a given path, per default it will span the whole domain.

14.3 运行与测试

运行HelloWorld/server.py:

$ python3 HelloWorld/server.py
Copy after login
Copy after login

使用浏览器打开http://127.0.0.1:5000/add,浏览器界面会显示

add cookies
Copy after login

下面查看一下cookie,如果使用firefox浏览器,可以用firebug插件查看。打开firebug,选择Cookies选项,刷新页面,可以看到名为name的cookie,其值为letian

在“网络”选项中,可以查看响应头中类似下面内容的设置cookie的HTTP「指令」:

Set-Cookie: name=letian; Expires=Sun, 29-Jun-2014 05:16:27 GMT; Path=/
Copy after login

在cookie有效期间,使用浏览器访问http://127.0.0.1:5000/show,可以看到:

{'name': 'letian'}
Copy after login

十五、闪存系统 flashing system

Flask的闪存系统(flashing system)用于向用户提供反馈信息,这些反馈信息一般是对用户上一次操作的反馈。反馈信息是存储在服务器端的,当服务器向客户端返回反馈信息后,这些反馈信息会被服务器端删除。

下面是一个示例。

15.1 建立Flask项目

按照以下命令建立Flask项目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

15.2 编写HelloWorld/server.py

内容如下:

from flask import Flask, flash, get_flashed_messages
import time
 
app = Flask(__name__)
app.secret_key = 'some_secret'
 
 
@app.route('/')
def index():
    return 'hi'
 
 
@app.route('/gen')
def gen():
    info = 'access at '+ time.time().__str__()
    flash(info)
    return info
 
 
@app.route('/show1')
def show1():
    return get_flashed_messages().__str__()
 
 
@app.route('/show2')
def show2():
    return get_flashed_messages().__str__()
 
 
if __name__ == "__main__":
    app.run(port=5000, debug=True)
Copy after login

15.3 效果

运行服务器:

$ python3 HelloWorld/server.py
Copy after login
Copy after login

打开浏览器,访问http://127.0.0.1:5000/gen,浏览器界面显示(注意,时间戳是动态生成的,每次都会不一样,除非并行访问):

access at 1404020982.83
Copy after login

查看浏览器的cookie,可以看到session,其对应的内容是:

.eJyrVopPy0kszkgtVrKKrlZSKIFQSUpWSknhYVXJRm55UYG2tkq1OlDRyHC_rKgIvypPdzcDTxdXA1-XwHLfLEdTfxfPUn8XX6DKWCAEAJKBGq8.BpE6dg.F1VURZa7VqU9bvbC4XIBO9-3Y4Y
Copy after login

再一次访问http://127.0.0.1:5000/gen,浏览器界面显示:

access at 1404021130.32
Copy after login

cookie中session发生了变化,新的内容是:

.eJyrVopPy0kszkgtVrKKrlZSKIFQSUpWSknhYVXJRm55UYG2tkq1OlDRyHC_rKgIvypPdzcDTxdXA1-XwHLfLEdTfxfPUn8XX6DKWLBaMg1yrfCtciz1rfIEGxRbCwAhGjC5.BpE7Cg.Cb_B_k2otqczhknGnpNjQ5u4dqw
Copy after login

然后使用浏览器访问http://127.0.0.1:5000/show1,浏览器界面显示:

['access at 1404020982.83', 'access at 1404021130.32']
Copy after login

这个列表中的内容也就是上面的两次访问http://127.0.0.1:5000/gen得到的内容。此时,cookie中已经没有session了。

如果使用浏览器访问http://127.0.0.1:5000/show1或者http://127.0.0.1:5000/show2,只会得到:

[]
Copy after login

15.4 高级用法

flash系统也支持对flash的内容进行分类。修改HelloWorld/server.py内容:

from flask import Flask, flash, get_flashed_messages
import time
 
app = Flask(__name__)
app.secret_key = 'some_secret'
 
 
@app.route('/')
def index():
    return 'hi'
 
 
@app.route('/gen')
def gen():
    info = 'access at '+ time.time().__str__()
    flash('show1 '+info, category='show1')
    flash('show2 '+info, category='show2')
    return info
 
 
@app.route('/show1')
def show1():
    return get_flashed_messages(category_filter='show1').__str__()
 
@app.route('/show2')
def show2():
    return get_flashed_messages(category_filter='show2').__str__()
 
 
if __name__ == "__main__":
    app.run(port=5000, debug=True)
Copy after login

某一时刻,浏览器访问http://127.0.0.1:5000/gen,浏览器界面显示:

access at 1404022326.39
Copy after login

不过,由上面的代码可以知道,此时生成了两个flash信息,但分类(category)不同。

使用浏览器访问http://127.0.0.1:5000/show1,得到如下内容:

['1 access at 1404022326.39']
Copy after login

而继续访问http://127.0.0.1:5000/show2,得到的内容为空:

[]
Copy after login

15.5 在模板文件中获取flash的内容

在Flask中,get_flashed_messages()默认已经集成到Jinja2模板引擎中,易用性很强。

The above is the detailed content of How Python uses the web framework Flask to develop projects. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template