flask路由實現
處理url和函式之間繫結關係的程式
路由控制訪問的路徑
,路徑能訪問到什麼是由後端來控制的
裝飾器新增路由表實現路由# 路由對映表
path_map =
defroute
(url,
**kwargs)
:def
decorator
(f):
path_map[url]
= f return f
return decorator
@route(
'/')
defhello()
:return
'hello'
@route(
'/index'
)def
index()
:return
'index'
print
(path_map)
>
# 路由裝飾器
class
(object):
def__init__
(self)
:# 定義路由表
self.routes =
defroute
(self, path=
none):
defdecorator
(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()]
)# 檢視函式
'/')
defhello()
:return
'hello'
'/login'
)def
login()
:return
'login'
'/change'
)def
change()
:return
'update pwd'
if __name__ ==
'__main__'
:# 啟動服務
from wsgiref.******_server import make_server
server = make_server(
'127.0.0.1'
,8888
server.serve_forever(
)
集中管理路由表實現路由from wsgiref.******_server import make_server
defhello()
:return
'hello'
deflogin()
:return
'login'
defchange()
:return
'update pwd'
# 路由表
path_dict =
def(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
server.serve_forever(
)
url_map =
defroute
(option)
:def
inner
(func,
*args,
**kwargs)
:# return func(*args, **kwargs)
url_map[option[
'path']]
= func
return inner
@route(
)def
index
(request)
:pass
Flask 路由系統
反向生成url def index print index print url for n1 return index 動態路由 def index nid print url for index nid 777 print url for index nid nid 根據輸入的nid,反向生成ur...
flask框架 路由
1.利用methods限制訪問方式 render template 返回頁面 request 一切瀏覽器請求的內容都封裝到request物件中 request.method 來判斷訪問方式 method 設定請求訪問方式 from flask import flask,render template...
Flask 路由系統
flask中的路由系統其實我們並不陌生了,從一開始到現在都一直在應用 為什麼要這麼用?其中的工作原理我們知道多少?methods 當前 url 位址,允許訪問的請求方式 info methods get post defstudent info stu id int request.args id ...