Technology Sharing

[Flask from entry to mastery: Lesson 2: Two ways to load project configuration with flask, basic definition of routing and terminal operation]

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Two ways to load project configuration in flask

# 1. 导入flask核心类
from flask import Flask

# 2. 初始化web应用程序的实例对象
app = Flask(__name__)

"""第一种:flask项目加载站点配置的方式"""
# app.config["配置项"] = 配置项值
# app.config["DEBUG"] = False

"""第二种:flask项目加载站点配置的方式"""
# app.config是整个flask项目默认的配置属性,里面包含了所有的可用配置项,配置项的属性名都是大写字母或大小字母+下划线组成
config = {
    "DEBUG": True
}
app.config.update(config)

# 4. 可以通过实例对象app提供的route路由装饰器,绑定视图与uri地址的关系
@app.route("/")
def index():
    # 5. 默认flask支持函数式视图,视图的函数名不能重复,否则报错!!!
    # 视图的返回值将被flask包装成响应对象的HTML文档内容,返回给客户端。
    return "<h1>hello flask</h1>"


if __name__ == '__main__':
    # 3. 运行flask提供的测试web服务器程序
    app.run(host="0.0.0.0", port=5000)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

Basic definition of routing

The names of routes and views must be globally unique and cannot be repeated, otherwise an error will be reported.

# 1. 导入flask核心类
from flask import Flask

# 2. 初始化web应用程序的实例对象
app = Flask(__name__)

# 开启debug模式
app.config["DEBUG"] = True

# 参数1:rule设置当前视图的路由地址
# 惨呼2:methods,设置当前视图的HTTP请求方法,允许一个或多个方法,不区分大小写
@app.route(rule="/", methods=["get", "post"])
def index():
    return "<h1>hello flask1</h1>"

if __name__ == '__main__':
    # 3. 运行flask提供的测试web服务器程序
    app.run(host="0.0.0.0", port=5000)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

What is routing?

Routing is aMapping relations. It is a one-to-one mapping relationship between binding application (view) and URL address! In the development process, the routing used when writing projects often refers to the class used to complete the routing function in the framework/project. This class is generally the routing class, referred to as routing.

In flask, the url can pass routing parameters in two ways:

Route parameters are part of the URL path.

Accepts arbitrary route parameters

# 1. 导入flask核心类
from flask import Flask

# 2. 初始化web应用程序的实例对象
app = Flask(__name__)

# 开启debug模式
app.config["DEBUG"] = True

@app.route(rule="/", methods=["get", "post"])
def index():
    return "<h1>hello flask1</h1>"

"""
路由参数的传递
小括号圈住,里面写上参数变量名
在视图中即可通过参数列表按命名来接收
接收参数时,如果没有在设置路由中设置参数的类型,则默认参数类型为字符串类型
"""
@app.route("/goods/<cid>/<gid>")
def goods(gid, cid):
    print(gid, type(gid))
    print(cid, type(cid))
    return f"显示cid={cid},gid={gid}的商品信息"

if __name__ == '__main__':
    # 3. 运行flask提供的测试web服务器程序
    app.run(host="0.0.0.0", port=5000)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

Accepts a restricted type parameter

To limit the type of routing parameters, the flask system's built-in converter is written in the werkzeug/routing/converters.py file. The following dictionary can be seen at the bottom:

# converters用于对路由中的参数进行格式转换与类型限定的
DEFAULT_CONVERTERS: t.Mapping[str, t.Type[BaseConverter]] = {
    "default": UnicodeConverter, # 默认类型,也就是string
    "string": UnicodeConverter, # 字符串,不包含 /
    "any": AnyConverter,    # 任意类型
    "path": PathConverter,  # 也是字符串,但是包含了 /
    "int": IntegerConverter,
    "float": FloatConverter,
    "uuid": UUIDConverter,
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

The specific usage of the system's built-in converters is written in the comment code of each converter. Please pay attention to the initialization parameters of each converter.

Converter Namedescribe
stringDefault type, accepts any text without slashes
intAccepts positive integers
floatAccepts positive floating point values
pathtake overstringBut also accepts slashes
uuidAccepts UUID (Universally Unique Identifier) ​​string xxxx-xxxx-xxxxx-xxxxx

Code:

# 1. 导入flask核心类
from flask import Flask

# 2. 初始化web应用程序的实例对象
app = Flask(__name__)

# 开启debug模式
app.config["DEBUG"] = True

@app.route(rule="/", methods=["get", "post"])
def index():
    return "<h1>hello flask1</h1>"

"""
通过路由转换器来对路由参数显示格式转换和限制类型
"""
@app.route("/goods/<float:cid>/<uuid:gid>")
def goods(gid, cid):
    print(gid, type(gid))
    print(cid, type(cid))
    return f"显示cid={cid},gid={gid}的商品信息"

if __name__ == '__main__':
    # 3. 运行flask提供的测试web服务器程序
    app.run(host="0.0.0.0", port=5000)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

Custom route parameter converter

Also called regular matching routing parameters.

In web development, there may be scenarios where user access rules are restricted. In this case, regular matching is needed to limit request parameters according to your own rules before access.

The specific implementation steps are:

  • Import the converter base class BaseConverter: In Flask, all routing matching rules are recorded using converter objects
  • Custom converter: The custom class inherits from the converter base class BaseConverter
  • Add the converter to the default converter dictionary DEFAULT_CONVERTERS
  • Implementing custom matching rules using custom converters

Code

  • Import the converter base class
from werkzeug.routing.converters import BaseConverter
  • 1
  • Custom Converters
class RegexConverter(BaseConverter):
    def __init__(self, map, *args, **kwargs):
        super().__init__(map, *args, **kwargs)
        self.regex = args[0]

  • 1
  • 2
  • 3
  • 4
  • 5
  • Add the converter to the default converter dictionary and specify the name of the converter to use:
app.url_map.converters["re"] = RegexConverter
  • 1
  • Use the converter to implement custom matching rules. The current rules defined here are: mobile phone number
"""
自定义路由转换[在实际项目开发中,我们会单独准备一个python文件来保存转换器的定义代码]
"""
from werkzeug.routing.converters import BaseConverter

class RegexConverter(BaseConverter):
    def __init__(self, map, *args, **kwargs):
        super().__init__(map, *args, **kwargs)
        self.regex = args[0]

app.url_map.converters["re"] = RegexConverter

@app.route("/sms/<re('1[3-9]d{9}'):mobile>")
def sms(mobile):
    return f"发送短信给手机号:{mobile}的用户"

@app.route("/goods/<re('d+'):id>")
def goods(id):
    return f"显示商品id={id}的信息"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

Run the test: http://127.0.0.1:5000/sms/13012345671. If the URL you access does not meet the rules, you will be prompted that the page cannot be found.

manage.py, classroom code:

# 1. 导入flask核心类
from flask import Flask

# 2. 初始化web应用程序的实例对象
app = Flask(__name__)

# 开启debug模式
app.config["DEBUG"] = True

"""
自定义路由转换[在实际项目开发中,我们会单独准备一个python文件来保存转换器的定义代码]
"""
from werkzeug.routing.converters import BaseConverter

class RegexConverter(BaseConverter):
    def __init__(self, map, *args, **kwargs):
        super().__init__(map, *args, **kwargs)
        self.regex = args[0]

app.url_map.converters["re"] = RegexConverter

@app.route("/sms/<re('1[3-9]d{9}'):mobile>")
def sms(mobile):
    return f"发送短信给手机号:{mobile}的用户"

@app.route("/goods/<re('d+'):id>")
def goods(id):
    return f"显示商品id={id}的信息"

if __name__ == '__main__':
    # 3. 运行flask提供的测试web服务器程序
    app.run(host="0.0.0.0", port=5000)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

Run the Flask project in the terminal

#  如果要基于开发环境在终端启动项目,设置环境变量如下:
export FLASK_DEBUG=True
# 如果要基于生产环境在终端启动项目,设置环境变量如下:
# export FLASK_DEBUG=Flase

# 找到创建flask应用的模块路径,例如:manage.py
# 则ubuntu等Linux下的终端:
export FLASK_APP=manage.py  # 这是临时设置,如果有永久设置,可以通过/etc/profile保存
# 2. 在当前虚拟环境中,如果安装了flask模块,则可以使用全局命令flask run,即可运行flask项目
flask run # 采用默认的127.0.0.1 和 5000端口运行项目 
flask run --host=0.0.0.0 --port=8088 # 可以改绑定域名IP和端口
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11