Commits

Alessandro Molina committed 28d903c

First import

Comments (0)

Files changed (7)

+.pyc
+.egg-info
+Introduction
+---------------
+
+Mobile Middleware is a middleware for WSGI applications.
+
+Thought to be used on Turbogears 2 applications it detects mobile browser and provides a way
+to detect and react to them. Detection expression can be customized and action can
+change from plain detection to exposing a specific custom template for mobile requests
+
+You will be able to see if your request is coming from a mobile browser with::
+
+    from tg import request
+    request.is_mobile
+
+Enabling Mobile Agents Detection
+----------------------------------
+
+In your application *config/middleware.py* import **MobileMiddleware**:: 
+
+    from tgext.mobilemiddleware import MobileMiddleware
+
+Change your **make_app** method::
+
+    app = make_base_app(global_conf, full_stack=True, **app_conf)
+    return MobileMiddleware(app, app_conf)
+
+Exposing Mobile Templates
+----------------------------
+
+**tgext.mobilemiddleware** implements a *@expose_mobile* decorator that works like *@expose*
+TurboGears2 decorator which can be used to specify which template to expose for mobie requests.
+
+This will work by registering a custom template renderer with 'mobile' custom format.
+*@expose_expose* supports the same template naming convention that @expose uses
+and can accept any rendering engine that has been registered in turbogears
+by specifing it as *engine:module.template_name* 
+
+Examples::
+
+    @expose('app.templates.index')
+    @expose_mobile('app.templates.mobile.index')
+    def index(self, *args, **kw):
+        return dict()
+
+
+Customizing User Agents Detection
+-----------------------------------
+
+**MobileMiddleware** by default checks user agent with a regular expression
+that can be customized by changing *[app:main]* section of your configuration
+file by adding something like::
+
+    mobile.agents = android|fennec|iemobile|iphone|ipod|ipad
+
+
+from setuptools import setup, find_packages
+import os
+
+version = '0.1'
+
+here = os.path.abspath(os.path.dirname(__file__))
+try:
+    README = open(os.path.join(here, 'README.rst')).read()
+except IOError:
+    README = ''
+
+setup(name='tgext.mobilemiddleware',
+      version=version,
+      description="Mobile Middleware utilities for Turbogears 2 detects mobile browsers",
+      long_description=README,
+      # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers
+      classifiers=[
+        "Environment :: Web Environment",
+        "Topic :: Software Development :: Libraries :: Python Modules",
+        "Framework :: TurboGears"
+        ],
+      keywords='turbogears pylons TG2',
+      author='Alessandro Molina',
+      author_email='alessandro.molina@axant.it',
+      url='http://bitbucket.org/_amol_/tgext.mobilemiddleware',
+      license='LGPL',
+      packages=find_packages(exclude=['ez_setup']),
+      namespace_packages=['tgext'],
+      include_package_data=True,
+      zip_safe=False,
+      install_requires=[
+      ],
+      entry_points="""
+      # -*- Entry points: -*-
+      """,
+      )

tgext/__init__.py

+# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
+try:
+    __import__('pkg_resources').declare_namespace(__name__)
+except ImportError:
+    from pkgutil import extend_path
+    __path__ = extend_path(__path__, __name__)

tgext/mobilemiddleware/__init__.py

+from middleware import MobileMiddleware
+from decorators import expose_mobile

tgext/mobilemiddleware/decorators.py

+import tg
+from tg import request, config
+from tg.decorators import use_custom_format, Decoration
+
+class expose_mobile(object):
+    def __init__(self, template, content_type='text/html'):
+        if template in config.get('renderers', []):
+            engine, template = template, ''
+        elif ':' in template:
+            engine, template = template.split(':', 1)
+        elif template:
+            engine = config.get('default_renderer')
+        else:
+            engine, template = None, None
+
+        self.template = template
+        self.engine = engine
+        self.content_type = content_type
+
+    def hook_func(self, *args, **kwargs):
+        if request.is_mobile:
+            use_custom_format(self.func, 'mobile')
+        else:
+            #currently turbogears needs to reset the custom_format at each request or it will
+            #use the last requested custom format for every request.
+            deco = Decoration.get_decoration(self.func)
+            deco.render_custom_format = None
+
+    def __call__(self, func):
+        self.func = func
+        deco = Decoration.get_decoration(func)
+        deco.register_custom_template_engine('mobile', self.content_type, self.engine, self.template, [])
+        deco.register_hook('before_render', self.hook_func)
+        return func

tgext/mobilemiddleware/middleware.py

+from webob import Request
+import re
+from tg import redirect
+
+class MobileMiddleware(object):
+    def __init__(self, application, config):
+        self.application = application
+
+        mobile_re_config = config.get('mobile.agents', 'android|fennec|iemobile|iphone|ipod|ipad')
+        self.mobile_re = re.compile(mobile_re_config, re.IGNORECASE)
+
+    def __call__(self, environ, start_response):
+        req = Request(environ)
+
+        user_agent = req.headers.get('User-Agent', None)
+        if user_agent and self.mobile_re.search(user_agent):
+            req.is_mobile = True
+        else:
+            req.is_mobile = False
+
+        resp = req.get_response(self.application)
+        return resp(environ, start_response)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.