Django経由でAmazon SNSを使ってPush通知を送る(Part4:Django編)
この記事はDjangoでAmazon SNSを使用してiPhoneにPush通知を配信するまでの流れのPart4です。
流れとしては以下のようになります。太字の箇所が今回説明する箇所となります。
Part1(準備編)
1.iOSに通知するメッセージを送るサーバー構築(今回はAmazon SNSサービスを使用)
2.通知サービスが有効になったApp IDを作成
3.Apple Push Notification Service(APNs)とサーバー間でメッセージをやりとりするための証明書を作成
4.Provisioning Profileを作成
Part2(iOS編)
5.iOSアプリに実装して端末識別用のDevice Tokenを取得してサーバーに送信
Part3(Amazon SNS編)
6.Amazon SNSのセットアップ
Part4(Django編)
7.Django側からAmazon SNSを経由して送信
ではDjango側の実装を行なっていきます。 なお今回はPython2.7.5,Django1.6で実装を行なっていきます。 またAmazon WebServiceのライブラリ、botoをインストールしておいてください。
まずはDjangoアプリを作成します。
# プロジェクトの作成
django-admin.py startproject pushserver
# deviceアプリを作成
cd pushserver
django-admin.py startapp devices
次にdeviceモデルを作成します。
pushserver/devices/models.py
import uuid
from django.db import models
from boto.sns import sns_connection
class Device(models.Model, Base):
device_token = models.CharField(max_length=200, blank=False, unique=True, null=False)
def register(self):
'''
Amazon SNSにデバイストークンを登録します。
'''
sns_connection = boto.sns.connect_to_region('ap-northeast-1',
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY)
#ARNはAmazon SNS Mobile Pointに記載されています。
sns_connection.create_platform_endpoint(
platform_application_arn=ARN,
token=self.device_token,
custom_user_data='test')
次にpushserver/settings.pyのINSTALLED_APPSの中に’devices’を追記して以下のコマンドでDBを作成します。
python manage.py syncdb
pushserver/urls.py
/devicesで始まるurlに関する処理はdevices/urls.pyに処理をするようにさせます。
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^devices/',include('devices.urls')),
)
pushserver/devices/urls.py
/devices/tokenのリクエストが来たら、/devices/views.pyのtoken_view()
メソッドが呼ばれるようにします。
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^token$',views.token_view,name='token'),
)
pushserver/devices/views.py
/devices/tokenにPOSTリクエストが来たら、DeviceTokenを持ったDeviceをDBに保存します。
def token_view(request):
if request.method == "POST":
device_token = request.body[1:-1]
device = Device.get_or_create(device_token =device_token)
device.register()
return HttpResponse("success!")
ここまでの作業を行ってpython manage.py runserver
を行なってサーバーを起動させたままにして Part2で作成したiOSアプリを開くとDeviceTokenがDBに保存されます!
次にAmazon Web ServiceをPython側から簡単に扱えるBotoというライブラリを使ってpython manage.py devices publish
というコマンドを入力するとすべてのDeviceにPush通知を行う実装を行います。
devices/management/commands/publish.py
#coding: utf-8
import boto
from django.core.management.base import BaseCommand,CommandError
from devices.models import Device
import re
import os
import boto.sns
from django.conf import settings
class Command(BaseCommand):
help = 'setup'
def handle(self,*args,**options):
AWS_ACCESS_KEY = settings.LOCAL_AWS_ACCESS_KEY
AWS_SECRET_KEY = settings.LOCAL_AWS_SECRET_KEY
# Amazon SNS Mobile Pointに記載されているarnを入力
arn = 'arn:aws:sns:ap-northeast-1.../APP_NAME/APP_SANDBOX'
sns_connection = boto.sns.connect_to_region('ap-northeast-1',
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY)
for device in Device.objects.all():
res = sns_connection.create_platform_endpoint(
platform_application_arn= arn,
token = device.device_token,
custom_user_data = 'test'
)
endpoint = res.get('CreatePlatformEndpointResponse').get('CreatePlatformEndpointResult').get('EndpointArn')
sns_connection.publish(target_arn=endpoint, message=u"Hello from Django")
Done!
ここまでがきちんと出来ていると
python manage.py devices publish
というコマンドを入力すると登録したすべてのデバイスにPush通知が行われます! お疲れ様でした:)