Skip to content
Browse files

initial commit

  • Loading branch information...
0 parents commit d9c2e4a0b9e2500ae4a52abe63f224b50bb6722f @madisona committed Jan 10, 2012
7 .gitignore
@@ -0,0 +1,7 @@
+
+*.pyc
+*.pyo
+
+.idea/*
+local.db
+.DS_Store
21 README
@@ -0,0 +1,21 @@
+
+django-mobile-views is a simple app to help detect mobile browsers
+and serve a different template for them.
+
+It works by inspecting the user agent.
+
+
+To use, either use one of the mobile generic views, or add the MobileMixin
+to your class based view.
+
+from mobile_views.generic_views import MobileTemplateView
+
+class HomePage(MobileTemplateView):
+ template_name = 'myapp/home_page.html'
+ mobile_template_name = 'myapp/mobile_home_page.html'
+
+
+And that's it!
+
+There is also a 'FullSiteView' provided that when accessed will set a cookie
+to prevent being served the mobile template. The cookie lasts until browser close.
0 example/__init__.py
No changes.
14 example/manage.py
@@ -0,0 +1,14 @@
+#!/usr/bin/env python
+from django.core.management import execute_manager
+import imp
+try:
+ imp.find_module('settings') # Assumed to be in the same directory.
+except ImportError:
+ import sys
+ sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
+ sys.exit(1)
+
+import settings
+
+if __name__ == "__main__":
+ execute_manager(settings)
160 example/settings.py
@@ -0,0 +1,160 @@
+# Django settings for example project.
+
+# app lives in a directory above our example
+# project so we need to make sure it is findable on our path.
+import sys
+from os.path import abspath, dirname, join
+
+PROJECT_DIR = abspath(dirname(__file__))
+
+project_parent = abspath(join(PROJECT_DIR, '..'))
+for path in (project_parent, PROJECT_DIR):
+ if path not in sys.path:
+ sys.path.insert(0, path)
+
+DEBUG = True
+TEMPLATE_DEBUG = DEBUG
+
+from os.path import abspath, dirname, join
+
+ADMINS = (
+ # ('Your Name', 'your_email@example.com'),
+)
+
+MANAGERS = ADMINS
+
+DATABASES = {
+ 'default': {
+ 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
+ 'NAME': join(PROJECT_DIR, 'local.db'), # Or path to database file if using sqlite3.
+ 'USER': '', # Not used with sqlite3.
+ 'PASSWORD': '', # Not used with sqlite3.
+ 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
+ 'PORT': '', # Set to empty string for default. Not used with sqlite3.
+ }
+}
+
+# Local time zone for this installation. Choices can be found here:
+# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
+# although not all choices may be available on all operating systems.
+# On Unix systems, a value of None will cause Django to use the same
+# timezone as the operating system.
+# If running in a Windows environment this must be set to the same as your
+# system time zone.
+TIME_ZONE = 'America/Chicago'
+
+# Language code for this installation. All choices can be found here:
+# http://www.i18nguy.com/unicode/language-identifiers.html
+LANGUAGE_CODE = 'en-us'
+
+SITE_ID = 1
+
+# If you set this to False, Django will make some optimizations so as not
+# to load the internationalization machinery.
+USE_I18N = True
+
+# If you set this to False, Django will not format dates, numbers and
+# calendars according to the current locale
+USE_L10N = True
+
+# Absolute filesystem path to the directory that will hold user-uploaded files.
+# Example: "/home/media/media.lawrence.com/media/"
+MEDIA_ROOT = ''
+
+# URL that handles the media served from MEDIA_ROOT. Make sure to use a
+# trailing slash.
+# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
+MEDIA_URL = ''
+
+# Absolute path to the directory static files should be collected to.
+# Don't put anything in this directory yourself; store your static files
+# in apps' "static/" subdirectories and in STATICFILES_DIRS.
+# Example: "/home/media/media.lawrence.com/static/"
+STATIC_ROOT = ''
+
+# URL prefix for static files.
+# Example: "http://media.lawrence.com/static/"
+STATIC_URL = '/static/'
+
+# URL prefix for admin static files -- CSS, JavaScript and images.
+# Make sure to use a trailing slash.
+# Examples: "http://foo.com/static/admin/", "/static/admin/".
+ADMIN_MEDIA_PREFIX = '/static/admin/'
+
+# Additional locations of static files
+STATICFILES_DIRS = (
+ # Put strings here, like "/home/html/static" or "C:/www/django/static".
+ # Always use forward slashes, even on Windows.
+ # Don't forget to use absolute paths, not relative paths.
+)
+
+# List of finder classes that know how to find static files in
+# various locations.
+STATICFILES_FINDERS = (
+ 'django.contrib.staticfiles.finders.FileSystemFinder',
+ 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
+# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
+)
+
+# Make this unique, and don't share it with anybody.
+SECRET_KEY = 't=k2&cq$#6bw*&w&#2wyxj1b2159xnv!n^$*d7b!3gbt8c5q#k'
+
+# List of callables that know how to import templates from various sources.
+TEMPLATE_LOADERS = (
+ 'django.template.loaders.filesystem.Loader',
+ 'django.template.loaders.app_directories.Loader',
+# 'django.template.loaders.eggs.Loader',
+)
+
+MIDDLEWARE_CLASSES = (
+ 'django.middleware.common.CommonMiddleware',
+ 'django.contrib.sessions.middleware.SessionMiddleware',
+ 'django.middleware.csrf.CsrfViewMiddleware',
+ 'django.contrib.auth.middleware.AuthenticationMiddleware',
+ 'django.contrib.messages.middleware.MessageMiddleware',
+)
+
+ROOT_URLCONF = 'example.urls'
+
+TEMPLATE_DIRS = (
+ # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
+ # Always use forward slashes, even on Windows.
+ # Don't forget to use absolute paths, not relative paths.
+)
+
+INSTALLED_APPS = (
+ 'django.contrib.auth',
+ 'django.contrib.contenttypes',
+ 'django.contrib.sessions',
+ 'django.contrib.sites',
+ 'django.contrib.messages',
+ 'django.contrib.staticfiles',
+ # Uncomment the next line to enable the admin:
+ # 'django.contrib.admin',
+ # Uncomment the next line to enable admin documentation:
+ # 'django.contrib.admindocs',
+ 'mobile_views',
+)
+
+# A sample logging configuration. The only tangible logging
+# performed by this configuration is to send an email to
+# the site admins on every HTTP 500 error.
+# See http://docs.djangoproject.com/en/dev/topics/logging for
+# more details on how to customize your logging configuration.
+LOGGING = {
+ 'version': 1,
+ 'disable_existing_loggers': False,
+ 'handlers': {
+ 'mail_admins': {
+ 'level': 'ERROR',
+ 'class': 'django.utils.log.AdminEmailHandler'
+ }
+ },
+ 'loggers': {
+ 'django.request': {
+ 'handlers': ['mail_admins'],
+ 'level': 'ERROR',
+ 'propagate': True,
+ },
+ }
+}
17 example/urls.py
@@ -0,0 +1,17 @@
+from django.conf.urls.defaults import patterns, include, url
+
+# Uncomment the next two lines to enable the admin:
+# from django.contrib import admin
+# admin.autodiscover()
+
+urlpatterns = patterns('',
+ # Examples:
+ # url(r'^$', 'example.views.home', name='home'),
+ # url(r'^example/', include('example.foo.urls')),
+
+ # Uncomment the admin/doc line below to enable admin documentation:
+ # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
+
+ # Uncomment the next line to enable the admin:
+ # url(r'^admin/', include(admin.site.urls)),
+)
1 mobile_views/__init__.py
@@ -0,0 +1 @@
+VERSION = "0.1.1"
72 mobile_views/generic_views.py
@@ -0,0 +1,72 @@
+
+from django.views import generic
+
+from mobile_views import utilities
+
+__all__ = (
+ 'MobileTemplateView', 'MobileDetailView', 'MobileFormView',
+ 'MobileCreateView', 'MobileRedirectView',
+)
+
+class MobileMixin(object):
+ """
+ MobileMixin is a supplement to django's generic views.
+
+ The mobile mixin uses the user agent to match a regular expression
+ that is know to indicate a mobile device.
+
+ If the device is mobile and the user doesn't have a 'no_mobile'
+ cookie set, the Mixin will try to render the mobile template if
+ it exists, falling back to the regular template if not.
+
+ """
+ template_name = None
+ mobile_template_name = None
+
+ def use_mobile(self):
+ return utilities.use_mobile(self.request)
+
+ def set_mobile_cookie(self, response):
+ response.set_cookie('no_mobile', True)
+
+ def delete_mobile_cookie(self, response):
+ response.delete_cookie('no_mobile')
+
+ def get_template_names(self):
+ """
+ Returns a list of template names to be used for the request. Must return
+ a list. May not be called if render_to_response is overridden.
+ """
+ if self.use_mobile():
+ return self.get_mobile_template_name()
+ else:
+ return self.get_default_template_name()
+
+ def get_default_template_name(self):
+ if self.template_name is None:
+ return []
+ return [self.template_name]
+
+ def get_mobile_template_name(self):
+ if self.mobile_template_name is None:
+ return self.get_default_template_name()
+ return [self.mobile_template_name]
+
+
+# The views below just piggyback on django's generic views
+# adding the mobile mixin...
+
+class MobileTemplateView(MobileMixin, generic.TemplateView):
+ pass
+
+class MobileDetailView(MobileMixin, generic.DetailView):
+ pass
+
+class MobileFormView(MobileMixin, generic.FormView):
+ pass
+
+class MobileCreateView(MobileMixin, generic.CreateView):
+ pass
+
+class MobileRedirectView(MobileMixin, generic.RedirectView):
+ permanent = False
0 mobile_views/models.py
No changes.
112 mobile_views/tests.py
@@ -0,0 +1,112 @@
+
+import mock
+
+from django import test
+from django.http import HttpResponse, HttpRequest
+
+from mobile_views import views, utilities, generic_views
+
+class MobileMixinTests(test.TestCase):
+
+ def setUp(self):
+ self.request = mock.Mock(spec=HttpRequest)
+ self.request.META = {}
+ self.mixin = generic_views.MobileMixin()
+ self.mixin.request = self.request
+
+ def test_sets_no_mobile_cookie(self):
+ response = mock.Mock(spec=HttpResponse)
+ self.mixin.set_mobile_cookie(response)
+ self.assertEqual((('no_mobile', True), {}), response.set_cookie.call_args)
+
+ def test_deletes_no_mobile_cookie(self):
+ response = mock.Mock(spec=HttpResponse)
+ self.mixin.delete_mobile_cookie(response)
+ self.assertEqual((('no_mobile',), {}), response.delete_cookie.call_args)
+
+ @mock.patch('mobile_views.utilities.use_mobile', mock.Mock(return_value=True))
+ def test_return_true_when_utilities_function_uses_mobile(self):
+ self.assertEqual(True, self.mixin.use_mobile())
+
+ @mock.patch('mobile_views.utilities.use_mobile', mock.Mock(return_value=False))
+ def test_return_true_when_utilities_function_uses_mobile(self):
+ self.assertEqual(False, self.mixin.use_mobile())
+
+ @mock.patch('mobile_views.generic_views.MobileMixin.use_mobile', mock.Mock(return_value=True))
+ def test_returns_mobile_template_name_when_use_mobile(self):
+ self.mixin.mobile_template_name = mock.sentinel.mobile_template_name
+ self.assertEqual([self.mixin.mobile_template_name], self.mixin.get_template_names())
+
+ @mock.patch('mobile_views.generic_views.MobileMixin.use_mobile', mock.Mock(return_value=False))
+ def test_returns_template_name_when_not_use_mobile(self):
+ self.mixin.template_name = mock.sentinel.template_name
+ self.assertEqual([self.mixin.template_name], self.mixin.get_template_names())
+
+ @mock.patch('mobile_views.generic_views.MobileMixin.use_mobile', mock.Mock(return_value=False))
+ def test_returns_empty_list_when_not_use_mobile_and_template_name_not_defined(self):
+ self.assertEqual([], self.mixin.get_template_names())
+
+class MobileUtilitiesTests(test.TestCase):
+
+ def test_returns_true_when_user_agent_matches_android(self):
+ request = mock.Mock(spec=HttpRequest)
+ request.META = {'HTTP_USER_AGENT': 'android'}
+ self.assertTrue(utilities.is_mobile(request))
+
+ def test_returns_true_when_user_agent_matches_iphone(self):
+ request = mock.Mock(spec=HttpRequest)
+ request.META = {'HTTP_USER_AGENT': 'iphone'}
+ self.assertTrue(utilities.is_mobile(request))
+
+ def test_returns_false_when_user_agent_does_not_match_lists(self):
+ request = mock.Mock(spec=HttpRequest)
+ request.META = {'HTTP_USER_AGENT': 'chrome'}
+ self.assertFalse(utilities.is_mobile(request))
+
+ def test_returns_true_when_user_has_no_mobile_cookie(self):
+ request = mock.Mock(spec=HttpRequest)
+ request.COOKIES = {'no_mobile': 'True'}
+ self.assertTrue(utilities.user_declined_mobile(request))
+
+ def test_returns_false_when_user_does_not_have_no_mobile_cookie(self):
+ request = mock.Mock(spec=HttpRequest)
+ request.COOKIES = {}
+ self.assertFalse(utilities.user_declined_mobile(request))
+
+ @mock.patch('mobile_views.utilities.is_mobile', mock.Mock(return_value=True))
+ @mock.patch('mobile_views.utilities.user_declined_mobile', mock.Mock(return_value=False))
+ def test_returns_true_when_is_mobile_and_not_user_declined_mobile(self):
+ self.assertEqual(True, utilities.use_mobile(mock.Mock()))
+
+ @mock.patch('mobile_views.utilities.is_mobile', mock.Mock(return_value=False))
+ @mock.patch('mobile_views.utilities.user_declined_mobile', mock.Mock(return_value=False))
+ def test_returns_false_when_not_is_mobile(self):
+ self.assertEqual(False, utilities.use_mobile(mock.Mock()))
+
+ @mock.patch('mobile_views.utilities.is_mobile', mock.Mock(return_value=True))
+ @mock.patch('mobile_views.utilities.user_declined_mobile', mock.Mock(return_value=True))
+ def test_returns_false_when_is_mobile_and_user_declined_mobile(self):
+ self.assertEqual(False, utilities.use_mobile(mock.Mock()))
+
+class FullSiteViewTests(test.TestCase):
+
+ def setUp(self):
+ self.view = views.FullSiteView()
+
+ def test_returns_follow_parameter(self):
+ self.view.request = mock.Mock()
+ self.view.request.GET = {'follow': mock.sentinel.follow}
+ self.assertEqual(mock.sentinel.follow, self.view.get_redirect_url())
+
+ def test_returns_root_url_when_no_follow_parameter(self):
+ self.view.request = mock.Mock()
+ self.view.request.GET = {}
+ self.assertEqual('/', self.view.get_redirect_url())
+
+ @mock.patch('mobile_views.views.FullSiteView.set_mobile_cookie')
+ @mock.patch('mobile_views.views.MobileRedirectView.get')
+ def test_sets_mobile_cookie_on_get_request(self, redirect_get, set_mobile_cookie):
+ response = mock.Mock(spec=HttpResponse)
+ redirect_get.return_value = response
+ views.FullSiteView().get(mock.Mock())
+ self.assertTrue(((response,), {}), set_mobile_cookie.call_args)
8 mobile_views/urls.py
@@ -0,0 +1,8 @@
+
+from django.conf.urls.defaults import patterns, url
+
+from mobile_views import views
+
+urlpatterns = patterns('',
+ url(r'full-site/$', views.FullSiteView.as_view(), name="full_site"),
+)
43 mobile_views/utilities.py
@@ -0,0 +1,43 @@
+
+import re
+
+# a regular expression to match a user agent, case insensitive
+MOBILE_RE_1 = re.compile(
+ r'android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|'
+ 'ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|'
+ 'phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|'
+ 'vodafone|wap|windows (ce|phone)|xda|xiino', re.I)
+
+MOBILE_RE_2 = re.compile(
+ r'1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|'
+ 'ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|'
+ 'au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|'
+ 'bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|'
+ 'da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|'
+ 'em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|'
+ 'gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|'
+ 'hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|'
+ 'i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|'
+ 'ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|'
+ 'lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|'
+ 'mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|'
+ 'mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|'
+ 'on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|'
+ 'pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|'
+ 'qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|'
+ 'sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|'
+ 'sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|'
+ 'sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|'
+ 'to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|'
+ 'vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|'
+ 'webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-', re.I)
+
+def is_mobile(request):
+ user_agent = request.META.get('HTTP_USER_AGENT', '')
+ return bool(MOBILE_RE_1.search(user_agent) or MOBILE_RE_2.search(user_agent[0:4]))
+
+def user_declined_mobile(request):
+ return bool(request.COOKIES.get('no_mobile', False))
+
+def use_mobile(request):
+ return bool(is_mobile(request) and not user_declined_mobile(request))
21 mobile_views/views.py
@@ -0,0 +1,21 @@
+__author__ = 'amadison'
+
+from mobile_views.generic_views import MobileRedirectView
+
+
+__all__ = ('FullSiteView', )
+
+class FullSiteView(MobileRedirectView):
+ """
+ this view will set a 'no_mobile' cookie and redirect to whatever
+ the follow url is. The cookie will remain for the session of the
+ browser and prevent any further re-directing to a mobile template.
+ """
+
+ def get_redirect_url(self, **kwargs):
+ return self.request.GET.get('follow', '/')
+
+ def get(self, request, *args, **kwargs):
+ response = super(FullSiteView, self).get(request, *args, **kwargs)
+ self.set_mobile_cookie(response)
+ return response
35 setup.py
@@ -0,0 +1,35 @@
+
+from setuptools import setup, find_packages
+
+REQUIREMENTS = (
+ 'django>=1.3',
+)
+TEST_REQUIREMENTS = (
+ 'mock',
+)
+
+from mobile_views import VERSION
+
+setup(
+ name="django-mobile-views",
+ version=VERSION,
+ author="Aaron Madison",
+ description="Some mixins to serve mobile templates when mobile detected.",
+ long_description=open('README', 'r').read(),
+ url="https://github.com/madisona/django-mobile-views",
+ packages=find_packages(exclude=["example"]),
+ install_requires=REQUIREMENTS,
+ tests_require=TEST_REQUIREMENTS,
+ zip_safe=False,
+ classifiers = [
+ "Development Status :: 4 - Beta",
+ "Environment :: Web Environment",
+ "Framework :: Django",
+ "Intended Audience :: Developers",
+ "License :: OSI Approved :: BSD License",
+ "Operating System :: OS Independent",
+ "Programming Language :: Python",
+ "Topic :: Software Development",
+ "Topic :: Software Development :: Libraries :: Application Frameworks",
+ ],
+ )

0 comments on commit d9c2e4a

Please sign in to comment.
Something went wrong with that request. Please try again.