This repository has been archived by the owner on Jan 13, 2022. It is now read-only.
forked from buchanae/basket
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
create news app, basic HTTP API for subscribing
- Loading branch information
Showing
9 changed files
with
209 additions
and
27 deletions.
There are no files selected for viewing
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
from django.db import models | ||
|
||
# Create your models here. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
<!DOCTYPE html> | ||
<html> | ||
<head> | ||
</head> | ||
<body> | ||
<form action="http://localhost:8000/news/subscribe/" method="post"> | ||
<div> | ||
Email: <input type="text" name="email" /> | ||
</div> | ||
<input type="submit" /> | ||
</form> | ||
</body> | ||
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
from functools import wraps | ||
|
||
from suds import WebFault | ||
from suds.client import Client | ||
|
||
|
||
class UnathorizedException(Exception): | ||
pass | ||
|
||
|
||
def logged_in(f): | ||
""" Decorator to ensure an authenticated session with Responsys | ||
before calling a function """ | ||
|
||
@wraps(f) | ||
def wrapper(inst, *args, **kwargs): | ||
if not inst.session: | ||
raise UnauthorizedException("Not logged in to Responsys, " | ||
"must call login()") | ||
f(inst, *args, **kwargs) | ||
return wrapper | ||
|
||
|
||
class Responsys(object): | ||
WSDL_URL = 'https://ws2.responsys.net/webservices/wsdl/ResponsysWS_Level1.wsdl' | ||
|
||
def __init__(self): | ||
self.client = None | ||
self.session = None | ||
|
||
def login(self, user, pass_): | ||
""" Login and create a Responsys session, returns False on | ||
failure """ | ||
|
||
if not self.client: | ||
self.client = Client(self.__class__.WSDL_URL) | ||
elif self.session: | ||
self.logout() | ||
|
||
try: | ||
res = self.client.service.login(user, pass_) | ||
except WebFault, e: | ||
return False | ||
|
||
self.session = res['sessionId'] | ||
|
||
# Set auth token for all requests | ||
header = self.client.factory.create('SessionHeader') | ||
header.sessionId = self.session | ||
self.client.set_options(soapheaders=header) | ||
|
||
@logged_in | ||
def logout(self): | ||
""" Logout and expire the current Responsys session """ | ||
|
||
self.client.service.logout() | ||
self.session = None | ||
|
||
@logged_in | ||
def merge_list_members(self, folder, list_, fields, records): | ||
""" | ||
Add data to the list located at <folder>/<list_> in | ||
Responsys. | ||
<fields> is an array of field names | ||
<records> is a single record or an array of records to insert | ||
(record = array). If the email already exists, its data will | ||
be updated | ||
""" | ||
|
||
client = self.client | ||
records = [records] if isinstance(records[0], basestring) else records | ||
|
||
def make_record(record): | ||
data = client.factory.create('Record') | ||
data.fieldValues = record | ||
return data | ||
|
||
target = client.factory.create('InteractObject') | ||
target.folderName = folder | ||
target.objectName = list_ | ||
|
||
data = client.factory.create('RecordData') | ||
data.fieldNames = fields | ||
data.records = [make_record(r) for r in records] | ||
|
||
# Configure the action to update the data when it matches on | ||
# the email address field, otherwise insert a new entry, and | ||
# default opt in | ||
rule = client.factory.create('ListMergeRule') | ||
rule.insertOnNoMatch = True | ||
rule.updateOnMatch = 'REPLACE_ALL' | ||
rule.matchColumnName1 = 'EMAIL_ADDRESS_' | ||
rule.matchOperator = 'NONE' | ||
rule.optinValue = 'I' | ||
rule.optoutValue = 'O' | ||
rule.htmlValue = 'H' | ||
rule.textValue = 'T' | ||
rule.rejectRecordIfChannelEmpty = 'E' | ||
rule.defaultPermissionStatus = 'OPTIN' | ||
|
||
self.client.service.mergeListMembers(target, data, rule) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
""" | ||
This file demonstrates two different styles of tests (one doctest and one | ||
unittest). These will both pass when you run "manage.py test". | ||
Replace these with more appropriate tests for your application. | ||
""" | ||
|
||
from django.test import TestCase | ||
|
||
class SimpleTest(TestCase): | ||
def test_basic_addition(self): | ||
""" | ||
Tests that 1 + 1 always equals 2. | ||
""" | ||
self.failUnlessEqual(1 + 1, 2) | ||
|
||
__test__ = {"doctest": """ | ||
Another way to test that 1 + 1 is equal to 2. | ||
>>> 1 + 1 == 2 | ||
True | ||
"""} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
from django.conf.urls.defaults import * | ||
from views import subscribe | ||
|
||
urlpatterns = patterns('', | ||
url('^subscribe/$', subscribe), | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
from datetime import date | ||
import urlparse | ||
|
||
from django.http import (HttpResponse, HttpResponseRedirect, | ||
HttpResponseBadRequest, HttpResponseForbidden) | ||
from django.views.decorators.csrf import csrf_exempt | ||
from django.conf import settings | ||
|
||
from responsys import Responsys | ||
|
||
|
||
@csrf_exempt | ||
def subscribe(request): | ||
if request.method == 'POST': | ||
data = request.POST | ||
|
||
# validate parameters | ||
for name in ['email']: | ||
if name not in data: | ||
return HttpResponseBadRequest('%s is missing' % name) | ||
|
||
record = {'EMAIL_ADDRESS_': data['email'], | ||
'EMAIL_FORMAT_': data.get('format', 'H'), | ||
'COUNTRY_': data.get('country', 'en'), | ||
'MOZILLA_AND_YOU_FLG': 'Y', | ||
'MOZILLA_AND_YOU_DATE': date.today().strftime('%Y-%m-%d')} | ||
|
||
# do the subscription | ||
rs = Responsys() | ||
rs.login(settings.RESPONSYS_USER, settings.RESPONSYS_PASS) | ||
rs.merge_list_members(settings.RESPONSYS_FOLDER, | ||
settings.RESPONSYS_LIST, | ||
record.keys(), | ||
record.values()) | ||
rs.logout() | ||
|
||
# redirect back to the page, if any | ||
next = data.get('next', request.META.get('HTTP_REFERER', None)) | ||
if next: | ||
parts = urlparse.urlsplit(next) | ||
query = '%s%s%s' % (parts.query, | ||
'&' if parts.query else '', | ||
'subscribed') | ||
next = urlparse.urlunsplit((parts.scheme, | ||
parts.netloc, | ||
parts.path, | ||
query, | ||
parts.fragment)) | ||
return HttpResponseRedirect(next) | ||
return HttpResponse('Success! You have been subscribed.') | ||
|
||
return HttpResponseBadRequest('GET is not supported') | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters