python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Flask路由实现

Python的Flask路由实现实例代码

作者:zyanwei2018

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

路由简介

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

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

路由实现

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

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

# 路由映射表
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()

集中管理路由表实现路由

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

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

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

您可能感兴趣的文章:
阅读全文