python-ox/ox/django/views.py

62 lines
1.9 KiB
Python
Raw Normal View History

2010-12-22 09:39:34 +00:00
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
2012-02-20 21:33:55 +00:00
import cookielib
import urllib2
from StringIO import StringIO
2010-12-22 09:39:34 +00:00
from celery.utils import get_full_cls_name
from celery.backends import default_backend
2012-02-20 21:33:55 +00:00
from django.http import HttpResponse
from django.conf import settings
2010-12-22 09:39:34 +00:00
from shortcuts import json_response
2012-02-20 21:33:55 +00:00
import ox
2010-12-22 09:39:34 +00:00
def task_status(request, task_id):
response = json_response(status=200, text='ok')
status = default_backend.get_status(task_id)
res = default_backend.get_result(task_id)
response['data'] = {
'id': task_id,
'status': status,
'result': res
}
if status in default_backend.EXCEPTION_STATES:
traceback = default_backend.get_traceback(task_id)
response['data'].update({'result': str(res.args[0]),
'exc': get_full_cls_name(res.__class__),
'traceback': traceback})
return response
2012-02-20 21:33:55 +00:00
class SessionCookieJar(cookielib.LWPCookieJar):
def save(self):
return "#LWP-Cookies-2.0\n" + self.as_lwp_str()
def load(self, data, ignore_discard=True, ignore_expires=True):
f = StringIO(data)
self._really_load(f, 'memory', ignore_discard, ignore_expires)
def api_proxy(request):
url = settings.OXAPI_URL
cj = SessionCookieJar()
if 'cj' in request.session:
cj.load(request.session['cj'])
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [
('User-Agent', request.META.get('HTTP_USER_AGENT'))
]
form = ox.MultiPartForm()
for key in request.POST:
form.add_field(key, request.POST[key])
r = urllib2.Request(url)
body = str(form)
r.add_header('Content-type', form.get_content_type())
r.add_header('Content-length', len(body))
r.add_data(body)
f = opener.open(r)
response = HttpResponse(f.read())
request.session['cj'] = cj.save()
return response