middleware.py
4.27 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
from importlib import import_module
import sys
import pickle
from django.conf import settings
from django.http import Http404
from django.utils import six
from floraconcierge import shortcuts
from floraconcierge.apiauth.models import User
from floraconcierge.cache import get_request_cache, new_request_cache
from floraconcierge.client import ApiClient
from floraconcierge.errors import ResultObjectNotFoundError, MiddlewareError
def import_string(dotted_path):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImportError if the import failed.
Helper function from django 1.7
"""
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
msg = "%s doesn't look like a module path" % dotted_path
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
try:
# noinspection PyUnboundLocalVariable
module = import_module(module_path)
except ImportError as e:
six.reraise(ImportError, ImportError('%s. Tried to import %s' % (e.message, module_path)), sys.exc_info()[2])
try:
# noinspection PyUnboundLocalVariable
return getattr(module, class_name)
except AttributeError:
msg = 'Module "%s" does not define a "%s" attribute/class' % (
dotted_path, class_name)
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
def initialize_apiclient(request):
err_pattern = 'floraconcierge.middleware.ApiClientMiddleware requires to be set settings.%s'
api_id = getattr(settings, 'FLORACONCIERGE_API_ID', None)
if not api_id:
raise ValueError(err_pattern % 'FLORACONCIERGE_API_ID')
secret = getattr(settings, 'FLORACONCIERGE_API_SECRET', None)
if not secret:
raise ValueError(err_pattern % 'FLORACONCIERGE_API_SECRET')
client = ApiClient(api_id, secret)
sess_env = pickle.loads(pickle.dumps(request.session.get("__floraconcierge_api_env", None)))
restored = False
if sess_env:
client.env = sess_env
restored = True
init_env = getattr(settings, 'FLORACONCIERGE_API_INIT_ENV', None)
if init_env:
init_env = import_string(init_env)
env = init_env(client, request, restored)
if env:
client.env = env
return client
class ApiClientMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
init = getattr(settings, 'FLORACONCIERGE_API_INIT_CLIENT', None)
if init:
init = import_string(init)
client = init(request)
else:
client = initialize_apiclient(request)
request.api = client
request.apienv = client.env
shortcuts.activate(client)
response = self.get_response(request)
if hasattr(request, 'apienv') and hasattr(request, 'user'):
# Support api user authentication
if isinstance(request.user, User) and request.user.info:
request.apienv.user_auth_key = request.user.info.auth.auth_key
else:
request.apienv.user_auth_key = ''
request.session['__floraconcierge_api_env'] = request.apienv
return response
class ApiObjectNotFound404:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
try:
res = self.get_response(request)
except ResultObjectNotFoundError:
raise Http404
return res
_cache_cls = None
class RequestCacheMiddleware:
def __init__(self, get_response):
self.get_response = get_response
@staticmethod
def cache_cls():
global _cache_cls
if not _cache_cls:
cls = getattr(settings, 'FLORACONCIERGE_CACHE_CLASS', None)
if not cls:
raise MiddlewareError('Please define FLORACONCIERGE_CACHE_CLASS in settings for RequestCacheMiddleware')
_cache_cls = import_string(cls)
return _cache_cls
def __call__(self, request):
try:
cache = get_request_cache()
except MiddlewareError:
cache = new_request_cache(self.cache_cls())
cache.clear()
request.cache = cache
return self.get_response(request)