API接口开发其实特简单,Python Flask Web 框架教程来了

news2025/2/24 23:02:47

大家好,日常工作中,无论你是数据工程师、数据挖掘工程师,甚至数据分析人员,都不可避免的与他人进行数据交互,API接口提供数据是最常见的形式。

今天我给大家分享 Python Flask Web 框架教程,共计10个部分,后续内容会更新,内容较长,喜欢记得收藏、点赞、关注。

目录

    • 源码分享
    • 1、Python Flask: 安装 Flask
      • 安装 Python 3
      • 安装 Falsk
    • 2、Python Flask: 从 Hello Wolrd 开始
      • Hello World
      • 修改Flask的配置
      • 调试模式
      • 绑定IP和端口
    • 3、Python Flask: 获取 URL 参数
      • 建立Flask项目
      • 列出所有的url参数
      • 获取某个指定的参数
      • 如何处理多值
    • 4、Python Flask: 获取 POST 方法传送的数据
      • 建立Flask项目
      • 查看POST数据内容
      • 解析POST数据
    • 5、Python Flask: 处理和响应 JSON 数据
      • 建立Flask项目
      • 处理JSON格式的请求数据
      • 响应JSON-方案1
      • 响应JSON-方案2
    • 6、Python Flask: 上传文件
      • 建立Flask项目
      • 上传文件
    • 7、Python Flask: Restful URL
      • 建立Flask项目
      • 编写代码
      • 转换类型
      • 一个有趣的用法
      • 编写转换器
    • 8、Python Flask: 使用 url_for 生成链接
      • 建立Flask项目
      • 编写代码
    • 9、Python Flask: 使用 redirect 重定向网址
      • 建立Flask项目
      • 编写代码
    • 10、Python Flask: 使用 Jinja2 模板引擎
      • 建立Flask项目
      • 创建并编辑HelloWorld/templates/default.html
      • 创建并编辑HelloWorld/templates/user\_info.html
      • 编辑HelloWorld/server.py
      • 运行与测试

源码分享

按照如下方式

目前群友已超过3000人,添加时最好的备注方式为:来源+兴趣方向,方便找到志同道合的朋友
方式①、添加微信号:dkl88191,备注:来自CSDN+flask
方式②、微信搜索公众号:Python学习与数据挖掘,后台回复:flask

1、Python Flask: 安装 Flask

本文讲述学习 Python Flask Web 框架之前需要安装什么。

安装 Python 3

自行百度/谷歌即可。

在Linux/MacOS安装后,可以使用python3命令执行Python程序,使用pip3安装Python库。 在Windows系统,仍然是pythonpip

安装 Falsk

通过pip3安装Flask即可:

方式1 - 全局安装:

$ sudo pip3 install Flask

方式2 - 针对当前用户安装:

$ pip3 install --user Flask

确认安装成功:

进入python交互模式看下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

2、Python Flask: 从 Hello Wolrd 开始

本文讲述如何使用 Python Flask Web 框架构建一个显示"Hello World!"的web程序,以及如何配置、调试 Flask。

Hello World

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

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

statictemplates目录是默认配置,其中static用来存放静态资源,例如图片、js、css文件等。templates存放模板文件。 我们的网站逻辑基本在server.py文件中,当然,也可以给这个文件起其他的名字。

server.py中加入以下内容:

from flask import Flask

app = Flask(__name__)

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

if __name__ == '__main__':
    app.run()

运行server.py

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

打开浏览器访问http://127.0.0.1:5000/,浏览页面上将出现Hello World!。 终端里会显示下面的信息:

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

变量app是一个Flask实例,通过下面的方式:

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

当客户端访问/时,将响应hello_world()函数返回的内容。注意,这不是返回Hello World!这么简单,Hello World!只是HTTP响应报文的实体部分,状态码等信息既可以由Flask自动处理,也可以通过编程来制定。

修改Flask的配置

app = Flask(__name__)

上面的代码中,python内置变量__name__的值是字符串__main__ 。Flask类将这个参数作为程序名称。当然这个是可以自定义的,比如app = Flask("my-app")

Flask默认使用static目录存放静态资源,templates目录存放模板,这是可以通过设置参数更改的:

app = Flask("my-app", static_folder="path1", template_folder="path2")

更多参数请参考__doc__

from flask import Flask
print(Flask.__doc__)

调试模式

上面的server.py中以app.run()方式运行,这种方式下,如果服务器端出现错误是不会在客户端显示的。但是在开发环境中,显示错误信息是很有必要的,要显示错误信息,应该以下面的方式运行Flask:

app.run(debug=True)

debug设置为True的另一个好处是,程序启动后,会自动检测源码是否发生变化,若有变化则自动重启程序。这可以帮我们省下很多时间。

绑定IP和端口

默认情况下,Flask绑定IP为127.0.0.1,端口为5000。我们也可以通过下面的方式自定义:

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

0.0.0.0代表电脑所有的IP。80是HTTP网站服务的默认端口。什么是默认?比如,我们访问网站http://www.example.com,其实是访问的http://www.example.com:80,只不过:80可以省略不写。

由于绑定了80端口,需要使用root权限运行server.py。也就是:

$ sudo python3 server.py

3、Python Flask: 获取 URL 参数

本文讲述在 Python Flask Web 框架中如何获取 URL 参数。

URL参数是出现在url中的键值对,例如http://127.0.0.1:5000/?disp=3中的url参数是{'disp':3}

建立Flask项目

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

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

列出所有的url参数

在server.py中添加以下内容:

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)

在浏览器中访问http://127.0.0.1:5000/?user=Flask&time&p=7&p=8,将显示:

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

较新的浏览器也支持直接在url中输入中文(最新的火狐浏览器内部会帮忙将中文转换成符合URL规范的数据),在浏览器中访问http://127.0.0.1:5000/?info=这是爱,,将显示:

ImmutableMultiDict([('info', '这是爱,')])

浏览器传给我们的Flask服务的数据长什么样子呢?可以通过request.full_pathrequest.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)

浏览器访问http://127.0.0.1:5000/?info=这是爱,,运行server.py的终端会输出:

/
/?info=%E8%BF%99%E6%98%AF%E7%88%B1%EF%BC%8C

获取某个指定的参数

例如,要获取键info对应的值,如下修改server.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)

运行server.py,在浏览器中访问http://127.0.0.1:5000/?info=hello,浏览器将显示:

hello

不过,当我们访问http://127.0.0.1:5000/时候却出现了500错误,浏览器显示:

如果开启了Debug模式,会显示:

为什么为这样?

这是因为没有在URL参数中找到info。所以request.args.get('info')返回Python内置的None,而Flask不允许返回None。

解决方法很简单,我们先判断下它是不是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)

另外一个方法是,设置默认值,也就是取不到数据时用这个值:

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)

函数request.args.get的第二个参数用来设置默认值。此时在浏览器访问http://127.0.0.1:5000/,将显示:

hi

如何处理多值

还记得上面有一次请求是这样的吗? http://127.0.0.1:5000/?user=Flask&time&p=7&p=8,仔细看下,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)

在浏览器中请求时,我们只会看到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)

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

4、Python Flask: 获取 POST 方法传送的数据

本文讲述在 Python Flask Web 框架中如何获取 POST 方法传送的数据。

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

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

安装方法:

$ sudo pip3 install requests

建立Flask项目

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

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

查看POST数据内容

以用户注册为例子,我们需要向服务器/register传送用户名name和密码xxpassword。如下编写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)

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

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

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

import requests

user_info = {'name': 'letian', 'xxpassword': '123'}
r = requests.post("http://127.0.0.1:5000/register", data=user_info)

print(r.text)

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

welcome

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&xxpassword=123'

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

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

b'name=letian&xxpassword=123'

解析POST数据

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

b'name=letian&xxpassword=123'

我们要想办法把我们要的name、xxpassword提取出来,怎么做呢?自己写?不用,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)

执行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'), ('xxpassword', '123')])
letian
letian
['letian']
little apple

request.form会自动解析数据。

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

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

输出的是默认值

little apple

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

import requests

user_info = {'name': ['letian', 'letian2'], 'xxpassword': '123'}
r = requests.post("http://127.0.0.1:5000/register", data=user_info)

print(r.text)

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

[u'letian', u'letian2']

5、Python Flask: 处理和响应 JSON 数据

本文讲述在 Python Flask Web 框架中如何处理和响应 JSON 数据。

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

建立Flask项目

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

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

处理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)

编写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)

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

3

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


<class 'dict'>
{'a': 1, 'b': 2}

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

响应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)

修改后运行。

编写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)

运行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}

上面第一段内容是服务器的响应头,第二段内容是响应体,也就是服务器返回的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

client2.py运行后会输出:

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

响应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)

6、Python Flask: 上传文件

本文讲述在 Python Flask Web 框架中如何上传文件。

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

建立Flask项目

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

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

上传文件

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

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

mkdir HelloWorld/static/uploads

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

$ sudo pip3 install werkzeug

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)

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)

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

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

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

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

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

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

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

7、Python Flask: Restful URL

本文讲述如何使用 Python Flask Web 框架构建支持 Restful URL 的 Web 应用。

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

建立Flask项目

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

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

编写代码

编辑server.py:

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'hello world'


@app.route('/user/<username>')
def user(username):
    print(username)
    print(type(username))
    return 'hello ' + username


@app.route('/user/<username>/friends')
def user_friends(username):
    print(username)
    print(type(username))
    return 'hello ' + username


if __name__ == '__main__':
    app.run(port=5000, debug=True)

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

letian
<class 'str'>

而访问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.

HelloWorld/server.py输出:

letian
<class 'str'>

转换类型

由上面的示例可以看出,使用 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/<int:num>')
def page(num):
    print(num)
    print(type(num))
    return 'hello world'


if __name__ == '__main__':
    app.run(port=5000, debug=True)

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

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

1
<class 'int'>

如果访问的是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

看起来够用了。

一个有趣的用法

如下编写服务器代码:

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'hello world'


@app.route('/page/<int:num1>-<int:num2>')
def page(num1, num2):
    print(num1)
    print(num2)
    return 'hello world'


if __name__ == '__main__':
    app.run(port=5000, debug=True)

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

11
22

编写转换器

自定义的转换器是一个继承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/<my_int:num>')
def page(num):
    print(num)
    print(url_for('page', num=123))   # page 对应的是 page函数 ,num 对应对应`/page/<my_int:num>`中的num,必须是str
    return 'hello world'


if __name__ == '__main__':
    app.run(port=5000, debug=True)

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

123
/page/123123

8、Python Flask: 使用 url_for 生成链接

本文讲述在 Python Flask Web 框架中如何使用 url_for 函数生成链接。

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

建立Flask项目

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

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

编写代码

编辑HelloWorld/server.py

from flask import Flask, url_for

app = Flask(__name__)

@app.route('/')
def hello_world():
    pass

@app.route('/user/<name>')
def user(name):
    pass

@app.route('/page/<int:num>')
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)

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

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

9、Python Flask: 使用 redirect 重定向网址

本文讲述在 Python Flask Web 框架中如何重定向网址。

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

建立Flask项目

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

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

编写代码

使用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)

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

this is test2

10、Python Flask: 使用 Jinja2 模板引擎

本文讲述在 Python Flask Web 框架中如何使用 Jinja2 模板引擎渲染html。

模板引擎负责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循环。

建立Flask项目

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

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

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

内容如下:

<html>
<head>
    <title>
        {% if page_title %}
            {{ page_title }}
        {% endif %}
    </title>
</head>

<body>
    {% block body %}{% endblock %}
</body>
</html>

可以看到,在<head>标签中使用了if判断,如果给模板传递了page_title变量,显示之,否则,不显示。

<body>标签中定义了一个名为body的block,用来被其他模板文件继承。

创建并编辑HelloWorld/templates/user_info.html

内容如下:

{% extends "default.html" %}

{% block body %}
    {% for key in user_info %}

        {{ key }}: {{ user_info[key] }} <br/>

    {% endfor %}
{% endblock %}

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

编辑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)

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

运行与测试

运行HelloWorld/server.py:

$ python3 HelloWorld/server.py

在浏览器中访问http://127.0.0.1:5000/user,效果图如下:

查看网页源码:

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/408362.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Vue面试题你知道多少

✅作者简介&#xff1a;大家好我是hacker707,大家可以叫我hacker&#xff0c;新星计划第三季python赛道Top1&#x1f3c6; &#x1f4c3;个人主页&#xff1a;hacker707的csdn博客 &#x1f525;系列专栏&#xff1a;带你玩转Vue &#x1f4ac;推荐一款模拟面试、刷题神器&…

前端401错误 解决方法:响应拦截器

目录 1.该问题出现的原因 2.处理401问题的解决方案原理 3.使用响应拦截器解决问题 1.该问题出现的原因 在前后端分离项目中&#xff0c;最常见的是前端点击登录后&#xff0c;后端返回token字符串&#xff0c;这个token可以看作是一个“令牌”&#xff0c;就比如你去酒店办理…

Vue实战【调整Vue-element-admin中的菜单栏,并添加顶部模块菜单栏】

目录&#x1f31f;前言&#x1f31f;小伙伴们先看&#x1f31f;实现思路&#x1f31f;具体代码&#x1f31f;最后&#x1f31f;前言 因为最近在整合公司的项目&#xff0c;需要把所有系统里的功能集成到一个项目里&#xff0c;这样就导致菜单栏目录会特别的多&#xff0c;不便…

【JavaScript】手撕前端面试题:事件委托 | 判断URL是否合法 | 全排列

&#x1f5a5;️ NodeJS专栏&#xff1a;Node.js从入门到精通 &#x1f5a5;️ 博主的前端之路&#xff08;源创征文一等奖作品&#xff09;&#xff1a;前端之行&#xff0c;任重道远&#xff08;来自大三学长的万字自述&#xff09; &#x1f5a5;️ TypeScript知识总结&…

【Axure】Axure RP 9下载、安装、授权、汉化

目录一、Axure RP 9 下载二、Axure RP 9 安装三、Axure RP 9 授权四、Axure RP 9 汉化一、Axure RP 9 下载 1、Axure RP 9 下载地址&#xff1a;https://www.axure.com/release-history/rp9 2、其他版本下载地址 ①登录axure官网:https://www.axure.com/ ②拉到最下面找到相关…

很好看的爱心表白代码(动态)

分享几个好看的爱心表白代码❤️爱心代码❤️&#xff08;C语言&#xff09;❤️流动爱心❤️&#xff08;htmlcssjs&#xff09;❤️线条爱心❤️&#xff08;htmlcssjs&#xff09;❤️biu表白爱心❤️&#xff08;htmlcssjs&#xff09;❤️matlab爱心函数❤️&#xff08;需…

Vue3+TS+Vite 入门指南

最近尝试上手 Vue3TSVite&#xff0c;对比起 Vue2 有些不适应&#xff0c;但还是真香~ 上手前先说下 Vue3 的一些变化吧~ Vue3 的变化 Vue3 带来的变化主要有以下几个方面&#xff1a; 使用层面 对比起 Vue2 启动速度快很多&#xff0c;新项目从 1s 升级到不到 500msvite.co…

Element-UI新手学习记录(一)

Layout 布局 通过基础的 24 分栏&#xff0c;迅速简便地创建布局。 span的作用 一行默认24个span&#xff0c;属性放在el-col中决定此元素占据多少span gutter属性 放在el-row中&#xff0c;给各个块之前设置间隔&#xff0c;但是是割的代码块的宽度。 offset属性 放在el…

小程序页面之间数据传递的四种方法

近期再使用小程序开发的时候遇到小程序页面和页面之间的数据传递问题。总结一下大致有以下几种方式实现页面数据传递。 最常见的就是路由传参&#xff0c;使用场景主要是页面汇总的少量数据的传递。以下都以Tarovue示例&#xff0c;原生、react或者uniapp同理&#xff0c;替换…

Pinia(二)了解和使用Store

Store Store 是保存状态(state)和业务逻辑的实体, store 不应该与我们的组件绑定. 换句话说, store 就是全局状态.store 有三个关键概念, 分别是 state, getters 和 actions, 这与 Vue 组件中的 data, computed 和 methods 是相对应的概念. 定义 store 通过 defineStore 函数…

Vue页面路由参数的传递和获取

文章目录1. 通过动态路由参数传递2. 通过query字符串传递3. props 隐式传递vue 页面路由切换时传参的方式有如下几种&#xff1a; 动态路由参数 它隐藏字段信息&#xff0c;相对于来说较安全&#xff0c;同时地址栏中的地址也相对较短 它必须是先定义后使用&#xff0c;一般用…

关于嵌套使用 iFrame 出现 Refused to display in aframe 拒绝连接访问 和 ‘X-Frame-Options‘ to ‘SAMEORIGIN‘ 的解决方案【已解决】

目录问题描述原因分析问题解决总结今天在迁移旧项目时&#xff0c;出现了如下错误提示&#xff1a; Refused to display in a frame because it set X-Frame-Options to SAMEORIGIN问题描述 当前项目是一个生产环境正常运行的项目&#xff0c;由于我们要迁移服务器并且部署 k…

Pro2:修改div块的颜色

什么是JavaScript&#xff1f;实现目标实现代码实现效果实现方法&#x1f49b;作者主页&#xff1a;静Yu &#x1f9e1;简介&#xff1a;CSDN全栈优质创作者、华为云享专家、阿里云社区博客专家&#xff0c;前端知识交流社区创建者 &#x1f49b;社区地址&#xff1a;前端知识交…

html里面使用axios发送请求

html里面使用axios 效果展示&#xff1a; 代码展示&#xff1a; <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta http-equiv"X-UA-Compatible" content"IEedge"><meta name…

Vue项目实战 —— 后台管理系统( pc端 ) —— Pro最终版本

前期回顾 开源项目 —— 原生JS实现斗地主游戏 ——代码极少、功能都有、直接粘贴即用_js斗地主_0.活在风浪里的博客-CSDN博客JS 实现 斗地主网页游戏https://blog.csdn.net/m0_57904695/article/details/128982118?spm1001.2014.3001.5501 通用版后台管理系统&#xff0c;如果…

前端vben框架中表格table问题汇总

1.template中的代码 <BasicTable register"registerTable" :canResize"false"><!-- 表格左边的插槽 --><template #tableTitle><div class"btn-group"><a-buttonghosttype"primary"preIcon"ant-desi…

【vue】vue脚手架以及vite介绍

内容一、VUECLI二、关于cli的原理三、vite四、使用vite五、vite处理css、less、postcss、ts六、vite对vue的支持&#xff1a;七、预打包&#xff1a;八、关于vite打包九、真实项目中不会一直使用npx的十、ESBuild十一、vite脚手架&#xff0c;一、VUECLI 先安装这个工具&#…

基于AI分词模型,构建一个简陋的Web应用

文章目录前言1. 效果展示2. 应用设计3. 实现3.1. lac分词模型的服务化部署3.2 使用Flask构建app4. 小结前言 内容纯属个人经验&#xff0c;若有不当或错误之处&#xff0c;还请见谅&#xff0c;欢迎指出。 文中大致介绍了&#xff0c;如何快捷地使用PaddleHub服务化部署一个简…

vue 时间格式总结及转换

vue框架中我们常常用el-date-picker标签来显示和选择时间&#xff0c;那么&#xff0c;常见的时间的格式包含年-月-日&#xff08;yyyy-MM-dd&#xff09;、年-月-日 时-分-秒&#xff08;yyyy-MM-dd HH-mm-ss&#xff09;、标准时间格式以及时间戳。那么今天我们就来总结一下常…

Vue的开发常用的工具有哪些?

相比其他大型框架&#xff0c;Vue更加灵活&#xff0c;开发者既可以选择使用Vue来开发一个全新项目&#xff0c;也可以将Vue引入到一个现有的项目中。代码简洁、上手容易&#xff0c;深受开发者青睐。本节我们将对Vue的开发环境以及常用工具的使用进行讲解。 1.Visual Studio …