Python Web開發 教你如何解放路由管理

2021-09-12 15:49:35 字數 4423 閱讀 6974

隨著業務的飛速發展,api介面越來越多,路由管理檔案從幾十號變成幾百上千行,且每次上新服務,需要在修改路由檔案**,帶來一定的風險。

下面這套規則只是其中一種方案,可以針對專案情況制定對應的規則,然後實現相關**,但是整體思路基本一樣。

**目錄結構,列一下簡單的專案檔案目錄,下面以flask框架為例:

專案的api介面**均放在resources資料夾下,且此資料夾只能寫介面api服務**。

介面名稱命名以_連線單詞,而對應檔案裡的類名檔名稱的單詞,不過換成是駝峰寫法。

類的匯入則通過檔名對應到類名,實現自動對映註冊到web框架中。

規則舉例如下: 如上圖,resources下有乙個hello_world介面,還有乙個ab專案資料夾,ab下面還有乙個hello_world_python介面以及子專案資料夾testab,testab下面也有乙個hello_world_python.

路由入口檔案會自動對映,對映規則為:字首 / 專案資料夾[…] / 檔名

其中 字首為整個專案的路由字首,可以定義,也可以不定義,比如api-ab專案,可以定義整個專案的路由字首為 ab/ resource下面專案資料夾如果有,則會自動拼接,如果沒有,則不會讀取。舉例: 字首為空,上圖resources中的三個介面對應的路由為:

hello_world.py ==>  /hello_world

ab/hello_world_python.py ==> /ab/hello_world_python

ab/testab/hello_world_python.py ==> /ab/testab/hello_world_python

字首為ab/,上圖resources中的三個介面對應的路由為:

hello_world.py ==> ab/hello_world

ab/hello_world_python.py ==> ab/ab/hello_world_python

ab/testab/hello_world_python.py ==> ab/ab/testab/hello_world_python

複製**

關於resources裡目錄結構,**裡是可以允許n層,但建議不要超過3層, 不易管理。

python很多框架的啟動和路由管理都很類似,所以這套規則適合很多框架,測試過程中有包括flask, tornado, sanic, japronto。 以前年代久遠的web.py也是支援的。

實現下劃線命名 轉 駝峰命名 函式,**演示:

def underline_to_hump(underline_str):

'''下劃線形式字串轉成駝峰形式,首字母大寫

'''sub = re.sub(r'(_\w)', lambda x: x.group(1)[1].upper(), underline_str)

if len(sub) > 1:

return sub[0].upper() + sub[1:]

return sub

實現根據字串匯入模組函式, **演示:

importlib.import_module(name)

複製**

上面2種方法都可以,github上**裡2種方法都有測試。

檢索resources資料夾,生成路由對映,並匯入對應實現類, **演示如下:

def route(route_file_path,

resources_name="resources",

route_prefix="",

existing_route=none):

route_list =

def get_route_tuple(file_name, route_pre, resource_module_name):

""":param file_name: api file name

:param route_pre: route prefix

:param resource_module_name: resource module

"""nonlocal route_list

nonlocal existing_route

route_endpoint = file_name.split(".py")[0]

#module = importlib.import_module('{}.{}'.format(

# resource_module_name, route_endpoint))

module = import_object('{}.{}'.format(

resource_module_name, route_endpoint))

route_class = underline_to_hump(route_endpoint)

real_route_endpoint = r'/{}{}'.format(route_pre, route_endpoint)

if existing_route and isinstance(existing_route, dict):

if real_route_endpoint in existing_route:

real_route_endpoint = existing_route[real_route_endpoint]

def check_file_right(file_name):

if file_name.startswith("_"):

return false

if not file_name.endswith(".py"):

return false

if file_name.startswith("."):

return false

return true

def recursive_find_route(route_path, sub_resource, route_pre=""):

nonlocal route_prefix

nonlocal resources_name

file_list = os.listdir(route_path)

if config.debug:

print("filelist:", file_list)

for file_item in file_list:

if file_item.startswith("_"):

continue

if file_item.startswith("."):

continue

if os.path.isdir(route_path + "/{}".format(file_item)):

recursive_find_route(route_path + "/{}".format(file_item), sub_resource + ".{}".format(file_item), "{}{}/".format(route_pre, file_item))

continue

if not check_file_right(file_item):

continue

get_route_tuple(file_item, route_prefix + route_pre, sub_resource)

recursive_find_route(route_file_path, resources_name)

if config.debug:

print("routelist:", route_list)

return route_list

# api route and processing functions

exist_route =

route_path = "./resources"

route_list = route(

route_path,

resources_name="resources",

route_prefix="flask/",

existing_route=exist_route)

for item in route_list:

api.add_resource(item[1], item[0])

if __name__ == "__main__":

複製**

routelist: [

('/hello_world', ),\ ('/flask/ab/testab/hello_world_python_test', ), \

('/flask/ab/hello_world_python', )

]複製**

元組第乙個元素則是路由,第二個元素是對應的實現類。

pythonweb開發 Python Web開發

參考原文 wsgi介面 wsgi web server gateway inte ce 是乙個介面,用來遮蔽底部的細節 如tcp的建立連線,http原始請求和響應格式等 wsgi介面定義非常簡單,只需要web開發者實現乙個函式,就可以響應客戶端的http請求。這個函式有兩個引數 environ 包含...

python web開發框架

django python web應用開發框架 django 應該是最出名的python框架,gae甚至erlang都有框架受它影響。django是走大而全的方向,它最出名的是其全自動化的管理後台 只需要使用起orm,做簡單的物件定義,它就能自動生成資料庫結構 以及全功能的管理後台。diesel 基...

Python Web開發框架

python中的web框架 flask例程 可重用成熟,穩健 可擴充套件性良好 提高開發速度 web框架中的概念 大包大攬的django 優點 完美文件。全套解決方案 cache,session,orm 強大的url路由配置 自助管理後台 缺點 系統緊耦合 自帶的orm不夠強大 template比較...