1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
import coip.mimeparse as mimeparse
import re
from django.conf import settings
from django.shortcuts import render_to_response
from django.core.exceptions import ObjectDoesNotExist
from datetime import datetime
from pprint import pprint
from django.http import HttpResponse
from django.core import serializers
default_suffix_mapping = {"\.htm(l?)$": "text/html",
"\.json$": "application/json",
"\.rss$": "application/rss+xml",
"\.torrent$": "application/x-bittorrent"}
def _accept_types(request, suffix):
for r in suffix.keys():
p = re.compile(r)
if p.search(request.path):
return suffix.get(r)
return None
def timeAsrfc822 ( theTime ) :
import rfc822
return rfc822 . formatdate ( rfc822 . mktime_tz ( rfc822 . parsedate_tz ( theTime . strftime ( "%a, %d %b %Y %H:%M:%S" ) ) ) )
def make_response_dict(request,d={}):
if request.user.is_authenticated():
d['user'] = request.user
profile = None
try:
profile = request.user.profile.get();
except ObjectDoesNotExist:
profile = UserProfile()
d['profile'] = profile
#d['stomp_host'] = STOMP_HOST
#d['stomp_port'] = STOMP_PORT
#d['orbited_prefix'] = ORBITED_PREFIX
#d['announce_url'] = ANNOUNCE_URL
#d['date'] = timeAsrfc822(datetime.now())
#if DEBUG is not None:
# d['debug'] = True
return d
def json_response(data):
json_serializer = serializers.get_serializer("json")()
json_serializer.serialize()
json_serializer.serialize(data)
r = HttpResponse(data.getvalue(),content_type='application/json')
r['Cache-Control'] = 'no-cache, must-revalidate'
r['Pragma'] = 'no-cache'
return r
def respond_to(request, template_mapping, dict={}, suffix_mapping=default_suffix_mapping):
accept = _accept_types(request, suffix_mapping)
if accept is None:
accept = (request.META['HTTP_ACCEPT'].split(','))[0]
content_type = mimeparse.best_match(template_mapping.keys(), accept)
template = None
if template_mapping.has_key(content_type):
template = template_mapping[content_type]
else:
template = template_mapping["text/html"]
if callable(template):
response = template(make_response_dict(request,dict))
elif isinstance(template, HttpResponse):
response = template
response['Content-Type'] = "%s; charset=%s" % (content_type, settings.DEFAULT_CHARSET)
else:
response = render_to_response(template,make_response_dict(request,dict))
response['Content-Type'] = "%s; charset=%s" % (content_type, settings.DEFAULT_CHARSET)
return response
|