Fix exception from improperly imported http.cookies
[fwx] / phial.py
index 081f262..411c077 100644 (file)
--- a/phial.py
+++ b/phial.py
@@ -1,5 +1,5 @@
 import collections
-import http.cookie
+import http.cookies
 import json
 import urllib.parse
 
@@ -49,9 +49,9 @@ class Request(_Request):
                 content_length = 0
 
         try:
-            cookie = http.cookie.SimpleCookie(env.get('HTTP_COOKIE'))
+            cookie = http.cookies.SimpleCookie(env.get('HTTP_COOKIE'))
         except:
-            cookie = http.cookie.SimpleCookie()
+            cookie = http.cookies.SimpleCookie()
 
 
         try:
@@ -191,6 +191,50 @@ class RedirectResponse(_RedirectResponse):
     def content(self):
         return (b'',)
 
+REQUEST_METHODS = (
+    'GET',
+    'HEAD',
+    'POST',
+    'PUT',
+    'PATCH',
+    'DELETE',
+    'CONNECT',
+    'OPTIONS',
+    'TRACE',
+)
+
+def default_method_not_allowed_handler(request):
+    return Response('')
+
+def default_options_handler(handlers):
+    def handler(request):
+        return Response(','.join(handlers.keys()))
+    return handler
+
+def route_on_method(**kwargs):
+    handlers = {}
+    for method in REQUEST_METHODS:
+        if method in kwargs:
+            handlers[method] = kwargs.pop(method)
+
+    method_not_allowed_handler = kwargs.pop(
+        'method_not_allowed',
+        default_method_not_allowed_handler,
+    )
+
+    assert len(kwargs) == 0
+
+    if 'OPTIONS' not in handlers:
+        handlers['OPTIONS'] = default_options_handler(handlers)
+
+    def handler(request):
+        return handlers.get(
+            request.method.upper(),
+            method_not_allowed_handler,
+        )(request)
+
+    return handler
+
 def _get_status(response):
     return {
         200: '200 OK',