欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python的Flask路由實現(xiàn)實例代碼

 更新時間:2023年08月09日 10:24:34   作者:zyanwei2018  
這篇文章主要介紹了Python的Flask路由實現(xiàn)實例代碼,在啟動程序時,python解釋器會從上到下對代碼進行解釋,當遇到裝飾器時,會執(zhí)行,并把函數(shù)對應的路由以字典的形式進行存儲,當請求到來時,即可根據(jù)路由查找對應要執(zhí)行的函數(shù)方法,需要的朋友可以參考下

路由簡介

  • 路由定義

處理url和函數(shù)之間綁定關系的程序

  • 路由作用

路由控制訪問的路徑 ,路徑能訪問到什么是由后端來控制的

路由實現(xiàn)

裝飾器添加路由表實現(xiàn)路由

  • 采用裝飾器添加路由功能在程序運行時,自動添加路由表
  • Flask即采用這種模式

函數(shù)裝飾器方式添加路由映射表

# 路由映射表
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()
# 視圖函數(shù)
@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()

集中管理路由表實現(xiàn)路由

手動添加路由映射表來 集中管理 路由。

  • Django等大型項目一般采用這種方式。
  • 使用時自己去添加路由映射表和對應的視圖函數(shù)
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路由實現(xiàn)

在啟動程序時,python解釋器會從上到下對代碼進行解釋,當遇到裝飾器時,會執(zhí)行,并把函數(shù)對應的路由以字典的形式進行存儲,當請求到來時,即可根據(jù)路由查找對應要執(zhí)行的函數(shù)方法
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作為存儲維護路由函數(shù)對應關系的映射空間
  • 當python解釋器從上到下解釋到@route這一行時,會自動執(zhí)行route({‘path’: ‘/index’}),將inner作為返回值,此時@route({‘path’: ‘/index’})等同于@inner并裝飾index函數(shù)
  • 繼續(xù)執(zhí)行index=inner(index),url_map即存儲’/index’路由對應的index函數(shù)

到此這篇關于Python的Flask路由實現(xiàn)實例代碼的文章就介紹到這了,更多相關Flask路由實現(xiàn)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論