Python的Flask路由实现实例代码

 更新时间:2023年08月09日 10:24:34   作者:zyanwei2018  
这篇文章主要介绍了Python的Flask路由实现实例代码,在启动程序时,python解释器会从上到下对代码进行解释,当遇到装饰器时,会执行,并把函数对应的路由以字典的形式进行存储,当请求到来时,即可根据路由查找对应要执行的函数方法,需要的朋友可以参考下

路由简介

  • 路由定义

处理url和函数之间绑定关系的程序

  • 路由作用

路由控制访问的路径 ,路径能访问到什么是由后端来控制的

路由实现

装饰器添加路由表实现路由

  • 采用装饰器添加路由功能在程序运行时,自动添加路由表
  • Flask即采用这种模式

函数装饰器方式添加路由映射表

# 路由映射表
path_map = {}
def route(url, **kwargs):
    def decorator(f):
        path_map[url] = f
        return f
    return decorator
@route('/')
def hello():
    return 'hello'
@route('/index')
def index():
    return 'index'
print(path_map)
>{'/': <function hello at 0x7fa103cfee50>, '/index': <function index at 0x7fa103cfedc0>}

类装饰器方式添加路由映射表

# 路由装饰器
class WsgiApp(object):
    def __init__(self):
        # 定义路由表
        self.routes = {}
    def route(self, path=None):
        def decorator(func):
            self.routes[path] = func
            return func
        return decorator
    def __call__(self, environ, start_response):
        path = environ.get('PATH_INFO')
        if path is None or path not in self.routes.keys():
            status = "400 Not Found"
            header = [('Content-Type', 'text/plain; charset=utf-8')]
            start_response(status, header)
            return [b'Page Not Found']
        else:
            status = "200 OK"
            header = [('Content-Type', 'text/plain; charset=utf-8')]
            start_response(status, header)
            resp = self.routes.get(path)
            if resp is None:
                status = "400 Not Found"
                header = [('Content-Type', 'text/plain; charset=utf-8')]
                start_response(status, header)
                return [b'Page Not Found']
            else:
                return [resp().encode()]
app = WsgiApp()
# 视图函数
@app.route('/')
def hello():
    return 'hello'
@app.route('/login')
def login():
    return 'login'
@app.route('/change')
def change():
    return 'update pwd'
if __name__ == '__main__':
    # 启动服务
    from wsgiref.simple_server import make_server
    server = make_server('127.0.0.1', 8888, app)
    server.serve_forever()

集中管理路由表实现路由

手动添加路由映射表来 集中管理 路由。

  • Django等大型项目一般采用这种方式。
  • 使用时自己去添加路由映射表和对应的视图函数
from wsgiref.simple_server import make_server
def hello():
    return 'hello'
def login():
    return 'login'
def change():
    return 'update pwd'
# 路由表
path_dict = {'/': hello,
             '/login': login,
             '/change': change
             }
def app(environ, start_response):
    path = environ.get('PATH_INFO')
    if path is None or path not in path_dict.keys():
        status = "400 Not Found"
        header = [('Content-Type', 'text/plain; charset=utf-8')]
        start_response(status, header)
        return [b'Page Not Found']
    else:
        status = "200 OK"
        header = [('Content-Type', 'text/plain; charset=utf-8')]
        start_response(status, header)
        resp = path_dict.get(path)
        if resp is None:
            status = "400 Not Found"
            header = [('Content-Type', 'text/plain; charset=utf-8')]
            start_response(status, header)
            return [b'Page Not Found']
        else:
            return [resp().encode()]
if __name__ == '__main__':
    server = make_server('127.0.0.1', 8888, app)
    server.serve_forever()

flask路由实现

在启动程序时,python解释器会从上到下对代码进行解释,当遇到装饰器时,会执行,并把函数对应的路由以字典的形式进行存储,当请求到来时,即可根据路由查找对应要执行的函数方法
url_map = {
    # '/index': index
}
def route(option):
    def inner(func,*args, **kwargs):
        # return func(*args, **kwargs)
        url_map[option['path']] = func
    return inner
@route({'path': '/index'})
def index(request):
    pass
  •  这里的url_map作为存储维护路由函数对应关系的映射空间
  • 当python解释器从上到下解释到@route这一行时,会自动执行route({‘path’: ‘/index’}),将inner作为返回值,此时@route({‘path’: ‘/index’})等同于@inner并装饰index函数
  • 继续执行index=inner(index),url_map即存储’/index’路由对应的index函数

到此这篇关于Python的Flask路由实现实例代码的文章就介绍到这了,更多相关Flask路由实现内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • opencv-python图像配准(匹配和叠加)的实现

    opencv-python图像配准(匹配和叠加)的实现

    图像配准需是指对不同条件下得到的两幅或多幅图像进行匹配、叠加的过程。本文详细的介绍了如何使用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-06-06
  • Python中文件的写入读取以及附加文字方法

    Python中文件的写入读取以及附加文字方法

    今天小编就为大家分享一篇Python中文件的写入读取以及附加文字方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-01-01
  • 为什么入门大数据选择Python而不是Java?

    为什么入门大数据选择Python而不是Java?

    为什么入门大数据选择Python而不是Java?这篇文章就来谈谈学习大数据入门语言的选择,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-03-03
  • 详解Python利用random生成一个列表内的随机数

    详解Python利用random生成一个列表内的随机数

    这篇文章主要介绍了详解Python利用random生成一个列表内的随机数,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-08-08
  • Python unittest单元测试框架实现参数化

    Python unittest单元测试框架实现参数化

    这篇文章主要介绍了Python unittest单元测试框架实现参数化,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • Python字符编码判断方法分析

    Python字符编码判断方法分析

    这篇文章主要介绍了Python字符编码判断方法,结合实例形式分析了Python字符编码的判断技巧,并给出了chardet的安装与使用方法,需要的朋友可以参考下
    2016-07-07
  • vim自动补全插件YouCompleteMe(YCM)安装过程解析

    vim自动补全插件YouCompleteMe(YCM)安装过程解析

    这篇文章主要介绍了vim自动补全插件YouCompleteMe(YCM)安装过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • Python编程实现删除VC临时文件及Debug目录的方法

    Python编程实现删除VC临时文件及Debug目录的方法

    这篇文章主要介绍了Python编程实现删除VC临时文件及Debug目录的方法,涉及Python针对文件与目录的遍历、删除等相关操作技巧,需要的朋友可以参考下
    2017-03-03
  • Python中的pandas表格模块、文件模块和数据库模块

    Python中的pandas表格模块、文件模块和数据库模块

    这篇文章介绍了Python中的pandas表格模块、文件模块和数据库模块,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-05-05
  • pytorch加载自定义网络权重的实现

    pytorch加载自定义网络权重的实现

    今天小编就为大家分享一篇pytorch加载自定义网络权重的实现,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01

最新评论