Parcourir la source

server: pre-compile URL matching regular expressions

Helge Jung il y a 9 ans
Parent
commit
4c947dcbfe
1 fichiers modifiés avec 16 ajouts et 9 suppressions
  1. 16 9
      ffstatus/server.py

+ 16 - 9
ffstatus/server.py

@@ -38,6 +38,13 @@ ISP_NORMALIZATIONS = [
                flags=re.IGNORECASE),
 ]
 
+REGEX_QUERYPARAM = re.compile(
+    r'(?P<key>.+?)=(?P<value>.+?)(&|$)')
+REGEX_URL_NODEINFO = re.compile(
+    r'node/(?P<id>[a-fA-F0-9]{12})(?P<cmd>\.json|/[a-zA-Z0-9_\-\.]+)$')
+REGEX_URL_NODESTATUS = re.compile(
+    r'status/([a-f0-9]{12})$')
+
 
 def normalize_ispname(isp):
     """Removes all matches on ISP_NORMALIZATIONS."""
@@ -65,9 +72,9 @@ class BatcaveHttpRequestHandler(BaseHTTPRequestHandler):
         path = url.group('path')
         query = {}
         if not url.group('query') is None:
-            for m in re.finditer(r'(?P<key>.+?)=(?P<value>.+?)(&|$)', url.group('query')):
-                query[m.group('key')] = m.group('value')
         return ( path, query )
+            for match in REGEX_QUERYPARAM.finditer(url.group('query')):
+                query[match.group('key')] = match.group('value')
 
     def do_GET(self):
         """Handles all HTTP GET requests."""
@@ -99,10 +106,10 @@ class BatcaveHttpRequestHandler(BaseHTTPRequestHandler):
 
         # /node/<id>.json - node's data
         # /node/<id>/field - return specific field from node's data
-        m = re.match(r'node/(?P<id>[a-fA-F0-9]{12})(?P<cmd>\.json|/[a-zA-Z0-9_\-\.]+)$', path)
-        if m != None:
-            cmd = m.group('cmd')
-            nodeid = m.group('id').lower()
+        match = REGEX_URL_NODEINFO.match(path)
+        if match is not None:
+            cmd = match.group('cmd')
+            nodeid = match.group('id').lower()
             if cmd == '.json':
                 self.respond_node(nodeid)
             else:
@@ -110,9 +117,9 @@ class BatcaveHttpRequestHandler(BaseHTTPRequestHandler):
             return
 
         # /status/<id> - node's status
-        m = re.match(r'status/([a-f0-9]{12})$', path)
-        if m != None:
-            self.respond_nodestatus(m.group(1))
+        match = REGEX_URL_NODESTATUS.match(path)
+        if match is not None:
+            self.respond_nodestatus(match.group(1))
             return
 
         # no match -> 404