Archive

Posts Tagged ‘python’

Urban Airship and RESTful Puts with Python

September 8th, 2009 jeremy 2 comments

This will be a quick post with a bit of code.  I wanted to share this since I had an awful time finding some working code snippets to communicate with Urban Airship to do Push notifications to Apple for  iPhones.

This code snippet will register a new device with Urban Airship that can then receive Push notifications.

import urllib2
from simplejson import dumps as json_dumps

user   = UAPUSH_USER
passwd = UAPUSH_PASS
base_url = UAPUSH_BASE_URL

# push_payload = {
    # 'aps': { 'badge': 2 },
    # 'device_tokens': [ 'devToken01', 'devToken02', etc ]
    # }

def _http_request(url,payload,is_put=False):
    headers = {"Content-type": "application/json" }
    authinfo = urllib2.HTTPBasicAuthHandler()
    authinfo.add_password("API", url, user, passwd )
    opener = urllib2.build_opener(authinfo)
    req  = urllib2.Request(url, payload, headers)
    if is_put: req.get_method = lambda: 'PUT'
    data = opener.open(req)
    return data.read()

def register_device(dev_token, tags):
    # dev_token is a string of hex returned from
    #     registerForRemoteNotificationTypes:
    # tags is a list of string based tags
    content = {"tags": tags}
    url = "%sdevice_tokens/%s" % (base_url, dev_token)
    print _http_request(url, json_dumps(content), is_put=True)

There’s nothing magical here. I just found it a bit interesting to have an HTTP base authenticated PUT request to a restful service and figured I’d show how to tie these all together.

Categories: iPhone creation Tags: , , ,