Starting > Designing > Developing > Testing > Running
Home | News | Blogs | About

A minimal mobile-aware web app with Python & cloud-based device detection

In this article we'll look at a how to make a minimal device-aware web application. The point of this article is not to demonstrate a useful application but rather to show just how little code is required to make an app that is fully device aware, and that can change its presentation entirely depending on the nature of the device accessing it.

To keep things simple and lightweight we'll use Python in conjunction with web.py and DeviceAtlas Personal (the cloud-based version of DeviceAtlas).

Web.py is a minimalist Python web framework that suits this example because it is simple and lightweight but the techniques demonstrated here will work equally well in any other web framework. You will need to install web.py if you want to run this example.

easy_install web.py

DeviceAtlas Personal is a device detection web service that requires no installation, configuration or maintenance – it just works. To make this easier to incorporate into a Python project I've attached a Python module to this article that wraps the web service into a convenience function that does everything you need.

Without further ado, here is the code:

import web
from DeviceAtlas import DaPersonal
 
urls = ( '/', 'index',)
app = web.application(urls, globals())
 
pageTemplate = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>test page</title></head><body><p>Hello, %s user</p><p>%s</p></body></html>'
 
class index:
    def GET(self):
        props = DaPersonal.get_device_properties(web.ctx.env['HTTP_USER_AGENT'])
        if props.has_key('mobileDevice') and props['mobileDevice']:
            return pageTemplate % ('mobile', props)
        else:
            return pageTemplate % ('sedentary', '')
 
if __name__ == "__main__":
    app.run()

Run the server as follows:

python test_app.py

Now, accessing the URL http://localhost:8080/ will result in two different outputs:

Desktop browser

Hello, sedentary user

Mobile browser

Hello, mobile user

{u'mobileDevice': True, u'isBrowser': False, u'displayWidth': 320, u'displayHeight': 480, '_source': 'cache'}

Notes

Closing Comments

This is an extremely simple application, clearly, but it nonetheless demonstrates a couple of key points:

AttachmentSize
test_app.zip5.06 KB

Posted by ronan 49 weeks ago

Switcher iconSwitch to our desktop site | mobiThinking