1
2
3
4
5
6
7 import base64
8 from StringIO import StringIO
9 import urlparse
10 import urllib
11
12 try:
13 from webob import Request as BaseRequest
14 except ImportError:
15 raise ImportError('WebOb (http://pypi.python.org/pypi/WebOb) is required')
16
17 from .wsgi_proxy import Proxy
18
19 __doc__ = '''Subclasses of webob.Request who use restkit to get a
20 webob.Response via restkit.ext.wsgi_proxy.Proxy.
21
22 Example::
23
24 >>> req = Request.blank('http://pypi.python.org/pypi/restkit')
25 >>> resp = req.get_response()
26 >>> print resp #doctest: +ELLIPSIS
27 200 OK
28 Date: ...
29 Transfer-Encoding: chunked
30 Content-Type: text/html; charset=utf-8
31 Server: Apache/2...
32 <BLANKLINE>
33 <?xml version="1.0" encoding="UTF-8"?>
34 ...
35
36
37 '''
38
39 PROXY = Proxy(allowed_methods=['GET', 'POST', 'HEAD', 'DELETE', 'PUT', 'PURGE'])
40
44 - def __get__(self, instance, klass):
45 if not instance:
46 return self
47 instance.method = self.name.upper()
48 def req(*args, **kwargs):
49 return instance.get_response(*args, **kwargs)
50 return req
51
52
54 get = Method('get')
55 post = Method('post')
56 put = Method('put')
57 head = Method('head')
58 delete = Method('delete')
59
61 if self.content_length < 0:
62 self.content_length = 0
63 if self.method in ('DELETE', 'GET'):
64 self.body = ''
65 elif self.method == 'POST' and self.POST:
66 body = urllib.urlencode(self.POST.copy())
67 stream = StringIO(body)
68 stream.seek(0)
69 self.body_file = stream
70 self.content_length = stream.len
71 if 'form' not in self.content_type:
72 self.content_type = 'application/x-www-form-urlencoded'
73 self.server_name = self.host
74 return BaseRequest.get_response(self, PROXY)
75
76 __call__ = get_response
77
79
80 path = url.lstrip('/')
81
82 if url.startswith("http://") or url.startswith("https://"):
83 u = urlparse.urlsplit(url)
84 if u.username is not None:
85 password = u.password or ""
86 encode = base64.b64encode("%s:%s" % (u.username, password))
87 self.headers['Authorization'] = 'Basic %s' % encode
88
89 self.scheme = u.scheme,
90 self.host = u.netloc.split("@")[-1]
91 self.path_info = u.path or "/"
92 self.query_string = u.query
93 url = urlparse.urlunsplit((u.scheme, u.netloc.split("@")[-1],
94 u.path, u.query, u.fragment))
95 else:
96
97 if '?' in path:
98 path, self.query_string = path.split('?', 1)
99 self.path_info = '/' + path
100
101
102 url = self.url
103 self.scheme, self.host, self.path_info = urlparse.urlparse(url)[0:3]
104