Commits

imbolc  committed afc1e94

auto urlname by function name, middlewares as class

  • Participants
  • Parent commits 61365fa

Comments (0)

Files changed (7)

 *.swp
 *.egg-info/
 dist/
-update_pypi.sh
-push.sh
+update_pypi.sh

File pysi/__init__.py

 
 from wsgi import App, Request, Response, redirect
 from config import cfg
-from exceptions import NotFound, Redirect, PermanentRedirect, BasicAuth
+from exceptions import NotFound, BasicAuth
 from routing import urls, add_apps, add_urls, url4, auto_routing
 from decorators import as_response, as_text, as_html, as_json, to_template
 from decorators import route, error, basic_auth, anticache, view
 from template import render_to_string, render_to_response
+from util import cached_property
 import signal

File pysi/decorators.py

     from django.utils import simplejson as json
 
 from wsgi import Response
-from exceptions import BasicAuth, Redirect
+from exceptions import BasicAuth
 from routing import urls
 from config import cfg
 from util import anticache_headers
 from template import render_to_response
 
+def get_urlname(func):
+    if not getattr(func, '_pysi_urlname', None):
+        mod_name = func.func_globals['__name__']
+        app_name = mod_name[:-6] if mod_name.endswith('.views') else None
+        urlname = '%s.%s' % (app_name, func.__name__) if app_name else func.__name__
+        setattr(func, '_pysi_urlname', urlname)
+    return func._pysi_urlname
 
-def route(url, urlname=None):
+def route(url):
     ''' Декоратор роутинга '''
     def wrapper(func):
+        urlname = get_urlname(func)
         urls.add_rule(url, func, urlname)
         return func
     return wrapper
                     res = dumper(res)
                 res = Response(res, **response_kwargs)
             return res
+        wrapper._pysi_urlname = get_urlname(func)
         return wrapper
     return decorator
     
                 return res
             return render_to_response(
                 rq, fn, res, **response_kwargs)
+        wrapper._pysi_urlname = get_urlname(func)
         return wrapper
     return decorator
 
         res = func(*args, **kwargs)
         res.headers.update(anticache_headers())
         return res
+    wrapper._pysi_urlname = get_urlname(func)
     return wrapper
 
 def error(code):
     def wrapper(rq, *args, **kwargs):
         rq.basic_user
         return func(rq, *args, **kwargs)
+    wrapper._pysi_urlname = get_urlname(func)
     return wrapper
     
-def view(url_or_list, template='text', **response_kwargs):
+def view(url, template=None, **response_kwargs):
     '''
-    Роутинг + шаблонизация + дефолтный урлнейм (app.func_name)
+    Роутинг + шаблонизация
     '''
     def wrapper(func):
-        mod_name = func.func_globals['__name__']
-        app_name = mod_name[:-6] if mod_name.endswith('.views') else None
-        urlname = '%s.%s' % (app_name, func.__name__) if app_name else func.__name__
-        if template == 'text':
-            func = as_text(**response_kwargs)(func)
-        elif template == 'json':
-            func = as_json(**response_kwargs)(func)
-        elif template == 'html':
-            func = as_html(**response_kwargs)(func)
-        else:
-            func = to_template(template, **response_kwargs)(func)
-        for url in [url_or_list] if isinstance(url_or_list, basestring) else url_or_list:
-            urls.add_rule(url, func, urlname)
+        urlname = get_urlname(func)
+        if template:
+            if template == 'text':
+                func = as_text(**response_kwargs)(func)
+            elif template == 'json':
+                func = as_json(**response_kwargs)(func)
+            elif template == 'html':
+                func = as_html(**response_kwargs)(func)
+            else:
+                func = to_template(template, **response_kwargs)(func)
+        urls.add_rule(url, func, urlname)
         return func
     return wrapper
 

File pysi/exceptions.py

 class NotFound(Exception):
     pass
 
-class Redirect(Exception):
-    '''Deprecated'''
-    def __init__(self, url, **kwargs):
-        self.res = wsgi.redirect(url, **kwargs)
-
-class PermanentRedirect(Exception):
-    '''Deprecated'''
-    def __init__(self, url, **kwargs):
-        self.res = wsgi.redirect(url, permanent=True, **kwargs)
-
 class BasicAuth(Exception):
     def __init__(self):
         self.res = wsgi.Response('Authorization Error', 

File pysi/middlewares.py

     ANTICACHE_PREFIXES = ('/', ),
 )
 
-def basic_auth_middleware(rq):
-    '''Basic-auth request middleware'''
-    if rq.path.startswith(cfg.BASIC_AUTH_PREFIXES):
-        rq.basic_user
+class BasicAuth(object):
+    def process_request(self, rq):
+        if rq.path.startswith(cfg.BASIC_AUTH_PREFIXES):
+            rq.basic_user
 
-def anticache_middleware(rq, res):
-    '''Browser anti-cache response middleware'''
-    if rq.path.startswith(cfg.ANTICACHE_PREFIXES):
-        res.headers.update(anticache_headers())
 
-def flash_middleware(rq, res):
-    '''Flash messages response middleware'''
-    if rq._new_flashes:
-        val = base64.urlsafe_b64encode(marshal.dumps(rq._new_flashes))
-        res.set_cookie(cfg.FLASH_COOKIE_NAME, val)
-    elif rq._clear_flashes:
-        res.delete_cookie(cfg.FLASH_COOKIE_NAME)
+class AntiCache(object):
+    def process_response(self, rq, res):
+        '''Browser anti-cache response middleware'''
+        if rq.path.startswith(cfg.ANTICACHE_PREFIXES):
+            res.headers.update(anticache_headers())
+
+
+class Flash(object):
+    def process_response(self, rq, res):
+        '''Flash messages response middleware'''
+        if rq._new_flashes:
+            val = base64.urlsafe_b64encode(marshal.dumps(rq._new_flashes))
+            res.set_cookie(cfg.FLASH_COOKIE_NAME, val)
+        elif rq._clear_flashes:
+            res.delete_cookie(cfg.FLASH_COOKIE_NAME)
 
     
 

File pysi/wsgi.py

 
 from util import cached_property, make_traceback, obj_from_str, list_obj_from_str
 from config import cfg
-from exceptions import NotFound, Redirect, PermanentRedirect, BasicAuth
+from exceptions import NotFound, BasicAuth
 from routing import auto_routing, add_apps, url4
 from multidict import MultiDict, HeaderDict
 
         add_apps(cfg.INSTALLED_APPS)
         
         list_obj_from_str(cfg.CONTEXT_PROCESSORS)
-        list_obj_from_str(cfg.REQUEST_MIDDLEWARES)
-        list_obj_from_str(cfg.RESPONSE_MIDDLEWARES)
+        mdls = list_obj_from_str(cfg.MIDDLEWARES)
+        self.request_middlewares = [m().process_request for m in mdls
+            if hasattr(m, 'process_request')]
+        self.response_middlewares = [m().process_response for m in mdls
+            if hasattr(m, 'process_response')]
+        self.response_middlewares.reverse()
 
         self.routing = obj_from_str(cfg.ROUTING)
         if isinstance(self.routing, (tuple, list)):
     def _call(self, environ, start_response):
         rq = Request(environ)
         try:
-            for middleware in cfg.REQUEST_MIDDLEWARES:
+            for middleware in self.request_middlewares:
                 middleware(rq)
             res = self.routing(rq)
             if not isinstance(res, Response):
                 res = Response(unicode(res), content_type='text/plain')
-            for middleware in cfg.RESPONSE_MIDDLEWARES:
+            for middleware in self.response_middlewares:
                 middleware(rq, res)
         except Response, e:
             res = e
-        except (Redirect, PermanentRedirect, BasicAuth), e:
+        except BasicAuth, e:
             res = e.res
         except NotFound, e:
             if cfg.DEBUG:
 from setuptools import setup
 
 PACKAGE = 'pysi'
-VERSION = '0.4'
+VERSION = '0.5'
 
 if __name__ == '__main__':
     # Compile the list of packages available, because distutils doesn't have