[英]Extraction pattern from a defined pattern list using a given string without regex in python
我目前正在創建一個支持 RESTful 的 HTTP 服務器。 為了像 /user/:user/:id 一樣支持 url,我創建了一種從 url 查找端點的機制。
我當前的代碼:
self.index_array= [
"POST-/foo/__",
"GET-/user/__/__"
]
self.index = {
"/foo/__": ["POST"],
"/user/__/__": ["GET"]
}
self.endpoints = [EndPointClass(...), EndPointClass(...)]
def get(self, method, path):
# Static
if path in self.index and method in self.index[path]:
return self.endpoints[self.index_array.index(method + "-" + path)]
# Dynamic
parts = path.split("/")
for a in parts:
test = path.replace(a, "__", 1)
if method + "-" + test in self.index_array:
return self.endpoints[self.index_array.index(method + "-" + test)]
上面的代碼可以路由 /foo/bar 之類的路徑,但不能路由具有多個路徑參數的路徑,例如 /user/username/1234。 我正在考慮將其拆分為方法並遞歸處理,但是隨着路徑嵌套的加深,這種想法會減慢執行速度。
另外,我不使用正則表達式的原因是因為我相信使用正則表達式會導致可怕的回溯並減慢進程。
誰能告訴我如何路由包含多個路徑參數的端點?
我正在使用翻譯器,所以如果您有任何問題,請發表評論,我會盡力回答。 如果您有任何問題或意見,請給我留言。
謝謝。
有一百萬種方法可以做到這一點,只要對自己保持簡單即可。 您可以使用字典將 index_array 轉換為 index_tree,例如:
index_tree = {
"POST":{"foo":{"endpoint":1}}
"GET": {
"user":{
"username": {"endpoint":2},
"email":{"endpoint":5}
},
"bar":{
"DirtyGoose": {"endpoint":3},
"3HornUnicorn": {"endpoint":4}
}
}
}
然后在拆分后簡單地導航它們:
nodes = path.split()
cur = index_tree
for i, node in enumerate(nodes):
if "endpoint" in cur:
if i == len(nodes) - 1:
return cur["endpoint"], None
return cur["endpoint"], nodes[i+1:] # arguments for your path
if node not in cur:
return None, None
cur = cur[node] # this will go as deep as you want until "endpoint" or incorrect node
但是您也可以在不拆分的情況下執行此操作:然后將其保存為所有可能路徑的排序列表,然后平分以找到看起來像您的路徑。 所有這些都不在路徑中 - 扔掉或用作參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.