Flask--路由实现

路由简介

  • 路由定义

处理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函数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值