Skip to content

Commit

Permalink
API
Browse files Browse the repository at this point in the history
  • Loading branch information
the-glu committed Jan 13, 2014
1 parent 1d863d7 commit 17882db
Show file tree
Hide file tree
Showing 10 changed files with 227 additions and 2 deletions.
7 changes: 6 additions & 1 deletion client/httpd.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,12 @@ def start():
@app.route('/back')
def back():

return render_template('back.html', result='ok' in request.args)
transaction_list = api.get_transactions(max_transaction=3)

transaction_details = api.get_transaction(transaction_list[0]['reference'])
transaction_logs = api.get_transaction_logs(transaction_list[0]['reference'])

return render_template('back.html', result='ok' in request.args, last_transactions=transaction_list, last_transaction_detail=transaction_details, last_transaction_logs=transaction_logs)


@app.route('/ipn', methods=['POST'])
Expand Down
57 changes: 57 additions & 0 deletions client/libs/polybanking.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,60 @@ def check_ipn(self, post_data):
return (False, 'CONFIG', None, None, None, None)

return (True, '', data['reference'], data['postfinance_status'], data['postfinance_status_good'] == 'True', datetime.datetime.strptime(data['last_update'][:-6], '%Y-%m-%d %H:%M:%S'))

def get_transactions(self, max_transaction=100):
"""Return the list of transactions, maximum max_transaction"""

data = {}

data['config_id'] = self.config_id
data['secret'] = self.keyAPI
data['max_transaction'] = max_transaction

try:
result = requests.post(self.server + '/api/transactions/', data=data).json()
if result['result'] != 'ok':
return None

return result['data']

except:
return None

def get_transaction(self, reference):
"""Return details about a transaction"""

data = {}

data['config_id'] = self.config_id
data['secret'] = self.keyAPI
data['reference'] = reference

try:
result = requests.post(self.server + '/api/transactions/' + reference + '/', data=data).json()
if result['result'] != 'ok':
return None

return result['data']

except:
return None

def get_transaction_logs(self, reference):
"""Return logs about a transaction"""

data = {}

data['config_id'] = self.config_id
data['secret'] = self.keyAPI
data['reference'] = reference

try:
result = requests.post(self.server + '/api/transactions/' + reference + '/logs/', data=data).json()
if result['result'] != 'ok':
return None

return result['data']

except:
return None
37 changes: 36 additions & 1 deletion client/templates/back.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,38 @@
<h3>PolyBanking Test/Demo client</h3>

We're back. {% if result %}Status seem ok{% else %}Status seem err{%endif %}
We're back. {% if result %}Status seem ok{% else %}Status seem err{%endif %}<br /><br />

Last transactions:

<ul>
{% for t in last_transactions %}
<li>{{t}}</li>
{% endfor %}
</ul>


{% if last_transaction_detail %}
Last transaction details:

<ul>
{% for key,val in last_transaction_detail.items() %}
<li><b>{{key}}</b>: {{val}}</li>
{% endfor %}
</ul>

{% endif %}


{% if last_transaction_logs %}
Last transaction logs:

<ul>
{% for log in last_transaction_logs %}
<li>
{% for key,val in log.items() %}
<b>{{key}}</b>: {{val}},
{% endfor %}
</li>
{% endfor %}
</ul>
{% endif %}
Empty file added server/api/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions server/api/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
16 changes: 16 additions & 0 deletions server/api/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this 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.assertEqual(1 + 1, 2)
14 changes: 14 additions & 0 deletions server/api/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*-

from django.conf.urls import patterns, url

urlpatterns = patterns(
'api.views',


url(r'^transactions/$', 'transactions_list'),

url(r'^transactions/(?P<reference>.*)/logs/$', 'transactions_show_logs'),
url(r'^transactions/(?P<reference>.*)/$', 'transactions_show'),

)
68 changes: 68 additions & 0 deletions server/api/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# -*- coding: utf-8 -*-

from django.shortcuts import get_object_or_404, render_to_response, redirect
from django.template import RequestContext
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_exempt
from django.http import Http404, HttpResponse, HttpResponseForbidden, HttpResponseNotFound
from django.utils.encoding import smart_str
from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required, user_passes_test
from django.http import HttpResponseRedirect
from django.db import connections
from django.core.paginator import InvalidPage, EmptyPage, Paginator
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _


import json


from configs.models import Config
from paiements.models import Transaction, TransactionLog


@csrf_exempt
def transactions_list(request):
"""Return the list of transaction"""

config = get_object_or_404(Config, pk=request.POST.get('config_id', -1), key_api=request.POST.get('secret', '#'))

max_transaction = int(request.POST.get('max_transaction', '100'))

retour = []

for transaction in config.transaction_set.order_by('-creation_date').all()[:max_transaction]:
retour.append({'reference': transaction.reference})

return HttpResponse(json.dumps({'result': 'ok', 'data': retour}))


@csrf_exempt
def transactions_show(request, reference):
"""Return details of a transaction"""

config = get_object_or_404(Config, pk=request.POST.get('config_id', -1), key_api=request.POST.get('secret', '#'))

transaction = get_object_or_404(Transaction, config=config, reference=reference)

return HttpResponse(json.dumps({'result': 'ok', 'data': transaction.dump_api()}))


@csrf_exempt
def transactions_show_logs(request, reference):
"""Return logs of a transaction"""

config = get_object_or_404(Config, pk=request.POST.get('config_id', -1), key_api=request.POST.get('secret', '#'))

transaction = get_object_or_404(Transaction, config=config, reference=reference)

retour = []

for log in transaction.transactionlog_set.order_by('-when').all():
retour.append(log.dump_api())

return HttpResponse(json.dumps({'result': 'ok', 'data': retour}))
1 change: 1 addition & 0 deletions server/app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
(r'^users/logout$', 'django.contrib.auth.views.logout', {'next_page': '/'}),

url(r'', include('main.urls')),
url(r'^api/', include('api.urls')),
url(r'^users/', include('users.urls')),
url(r'^configs/', include('configs.urls')),
url(r'^paiements/', include('paiements.urls')),
Expand Down
26 changes: 26 additions & 0 deletions server/paiements/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,19 @@ def internal_status_good(self):
def __unicode__(self):
return self.reference

def dump_api(self):
"""Return values for API"""

retour = {}

for val in ['reference', 'extra_data', 'amount', 'postfinance_id', 'postfinance_status', 'internal_status', 'ipn_needed', 'creation_date', 'last_userforwarded_date', 'last_user_back_from_postfinance_date', 'last_postfinance_ipn_date', 'last_ipn_date']:
retour[val] = str(getattr(self, val))

for cal, name in [('get_postfinance_status_display', 'postfinance_status_text'), ('get_internal_status_display', 'internal_status_text')]:
retour[name] = getattr(self, cal)()

return retour


class TransactionLog(models.Model):
"""A transaction log"""
Expand All @@ -113,3 +126,16 @@ class TransactionLog(models.Model):
)

log_type = models.CharField(max_length=64, choices=LOG_TYPE)

def dump_api(self):
"""Return values for API"""

retour = {}

for val in ['when', 'extra_data', 'log_type']:
retour[val] = str(getattr(self, val))

for cal, name in [('get_log_type_display', 'log_type_text')]:
retour[name] = getattr(self, cal)()

return retour

0 comments on commit 17882db

Please sign in to comment.