Flask配置文件

 一、配置文件

settings.py:

复制代码
class BaseConfig(object):
    DEBUG = False
    TESTING = False
    DATABASE_URI = 'sqlite://:memory:'


class ProductionConfig(BaseConfig):
    DATABASE_URI = 'mysql://user@pro/foo'


class DevelopmentConfig(BaseConfig):
    DATABASE_URI = 'mysql://user@dev/foo'


class TestingConfig(BaseConfig):
    DATABASE_URI = 'mysql://user@test/foo'
复制代码

主文件引入配置文件:

复制代码
from flask import Flask
app = Flask(__name__)
# 配置文件
app.config.from_object('settings.DevelopmentConfig')


@app.route('/index', methods=['GET', 'POST'])
def index():
    return '123'


if __name__ == '__main__':
    app.run()
复制代码

 

二、路由

1、添加路由的两种方式,通常使用方式一

复制代码
from flask import Flask
app = Flask(__name__)


# 路由方式一
@app.route('/index', methods=['GET', 'POST'])
def index():
    return 'index'


# 路由方式二
def order():
    return 'order'
app.add_url_rule('/order', view_func=order)


if __name__ == '__main__':
    app.run()
复制代码

2、反向解析:

3、路由系统

@app.route('/user/<username>')

@app.route('/post/<int:post_id>')

@app.route('/post/<float:post_id>')

@app.route('/post/<path:path>')

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

常用路由系统有以上五种,所有的路由系统都是基于一下对应关系来处理:

复制代码
DEFAULT_CONVERTERS = {
    'default':          UnicodeConverter,
    'string':           UnicodeConverter,
    'any':              AnyConverter,
    'path':             PathConverter,
    'int':              IntegerConverter,
    'float':            FloatConverter,
    'uuid':             UUIDConverter,
}
复制代码

 

自定义转换器支持正则:

复制代码
from flask import Flask, url_for
from werkzeug.routing import BaseConverter

app = Flask(import_name=__name__)


class RegexConverter(BaseConverter):
    """
    自定义URL匹配正则表达式
    """
    def __init__(self, map, regex):
        super(RegexConverter, self).__init__(map)
        self.regex = regex

    def to_python(self, value):
        """
        路由匹配时,匹配成功后传递给视图函数中参数的值
        """
        return int(value)

    def to_url(self, value):
        """
        使用url_for反向生成URL时,传递的参数经过该方法处理,返回的值用于生成URL中的参数
        """
        val = super(RegexConverter, self).to_url(value)
        return val


# 添加到flask中
app.url_map.converters['regex'] = RegexConverter


@app.route('/index/<regex("\d+"):nid>')
def index(nid):
    print(nid)
    print(url_for('index', nid='888'))
    return 'Index'


if __name__ == '__main__':
    app.run()
View Code
复制代码

 

posted @   困了就睡觉觉  Views(64)  Comments(0Edit  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示