forked from Pylons/webob
/
request.py
1720 lines (1512 loc) · 57.7 KB
/
request.py
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import binascii
import cgi
import io
import os
import re
import sys
import tempfile
import mimetypes
try:
import simplejson as json
except ImportError:
import json
import warnings
from webob.acceptparse import (
AcceptLanguage,
AcceptCharset,
MIMEAccept,
MIMENilAccept,
NoAccept,
accept_property,
)
from webob.cachecontrol import (
CacheControl,
serialize_cache_control,
)
from webob.compat import (
PY3,
bytes_,
integer_types,
native_,
parse_qsl_text,
reraise,
text_type,
url_encode,
url_quote,
url_unquote,
quote_plus,
urlparse,
)
from webob.cookies import RequestCookies
from webob.descriptors import (
CHARSET_RE,
SCHEME_RE,
converter,
converter_date,
environ_getter,
environ_decoder,
parse_auth,
parse_int,
parse_int_safe,
parse_range,
serialize_auth,
serialize_if_range,
serialize_int,
serialize_range,
upath_property,
deprecated_property,
)
from webob.etag import (
IfRange,
AnyETag,
NoETag,
etag_property,
)
from webob.headers import EnvironHeaders
from webob.multidict import (
NestedMultiDict,
MultiDict,
NoVars,
GetDict,
)
from webob.util import warn_deprecation
__all__ = ['BaseRequest', 'Request', 'LegacyRequest']
class _NoDefault:
def __repr__(self):
return '(No Default)'
NoDefault = _NoDefault()
PATH_SAFE = '/:@&+$,'
http_method_probably_has_body = dict.fromkeys(
('GET', 'HEAD', 'DELETE', 'TRACE'), False)
http_method_probably_has_body.update(
dict.fromkeys(('POST', 'PUT', 'PATCH'), True))
_LATIN_ENCODINGS = (
'ascii', 'latin-1', 'latin', 'latin_1', 'l1', 'latin1',
'iso-8859-1', 'iso8859_1', 'iso_8859_1', 'iso8859', '8859',
)
class BaseRequest(object):
## The limit after which request bodies should be stored on disk
## if they are read in (under this, and the request body is stored
## in memory):
request_body_tempfile_limit = 10*1024
_charset = None
def __init__(self, environ, charset=None, unicode_errors=None,
decode_param_names=None, **kw):
if type(environ) is not dict:
raise TypeError(
"WSGI environ must be a dict; you passed %r" % (environ,))
if unicode_errors is not None:
warnings.warn(
"You unicode_errors=%r to the Request constructor. Passing a "
"``unicode_errors`` value to the Request is no longer "
"supported in WebOb 1.2+. This value has been ignored " % (
unicode_errors,),
DeprecationWarning
)
if decode_param_names is not None:
warnings.warn(
"You passed decode_param_names=%r to the Request constructor. "
"Passing a ``decode_param_names`` value to the Request "
"is no longer supported in WebOb 1.2+. This value has "
"been ignored " % (decode_param_names,),
DeprecationWarning
)
if not _is_utf8(charset):
raise DeprecationWarning(
"You passed charset=%r to the Request constructor. As of "
"WebOb 1.2, if your application needs a non-UTF-8 request "
"charset, please construct the request without a charset or "
"with a charset of 'None', then use ``req = "
"req.decode(charset)``" % charset
)
d = self.__dict__
d['environ'] = environ
if kw:
cls = self.__class__
if 'method' in kw:
# set method first, because .body setters
# depend on it for checks
self.method = kw.pop('method')
for name, value in kw.items():
if not hasattr(cls, name):
raise TypeError(
"Unexpected keyword: %s=%r" % (name, value))
setattr(self, name, value)
if PY3: # pragma: no cover
def encget(self, key, default=NoDefault, encattr=None):
val = self.environ.get(key, default)
if val is NoDefault:
raise KeyError(key)
if val is default:
return default
if not encattr:
return val
encoding = getattr(self, encattr)
if encoding in _LATIN_ENCODINGS: # shortcut
return val
return bytes_(val, 'latin-1').decode(encoding)
else:
def encget(self, key, default=NoDefault, encattr=None):
val = self.environ.get(key, default)
if val is NoDefault:
raise KeyError(key)
if val is default:
return default
if encattr is None:
return val
encoding = getattr(self, encattr)
return val.decode(encoding)
def encset(self, key, val, encattr=None):
if encattr:
encoding = getattr(self, encattr)
else:
encoding = 'ascii'
if PY3: # pragma: no cover
self.environ[key] = bytes_(val, encoding).decode('latin-1')
else:
self.environ[key] = bytes_(val, encoding)
@property
def charset(self):
if self._charset is None:
charset = detect_charset(self._content_type_raw)
if _is_utf8(charset):
charset = 'UTF-8'
self._charset = charset
return self._charset
@charset.setter
def charset(self, charset):
if _is_utf8(charset):
charset = 'UTF-8'
if charset != self.charset:
raise DeprecationWarning("Use req = req.decode(%r)" % charset)
def decode(self, charset=None, errors='strict'):
charset = charset or self.charset
if charset == 'UTF-8':
return self
# cookies and path are always utf-8
t = Transcoder(charset, errors)
new_content_type = CHARSET_RE.sub('; charset="UTF-8"',
self._content_type_raw)
content_type = self.content_type
r = self.__class__(
self.environ.copy(),
query_string=t.transcode_query(self.query_string),
content_type=new_content_type,
)
if content_type == 'application/x-www-form-urlencoded':
r.body = bytes_(t.transcode_query(native_(r.body)))
return r
elif content_type != 'multipart/form-data':
return r
fs_environ = self.environ.copy()
fs_environ.setdefault('CONTENT_LENGTH', '0')
fs_environ['QUERY_STRING'] = ''
if PY3: # pragma: no cover
fs = cgi.FieldStorage(fp=self.body_file,
environ=fs_environ,
keep_blank_values=True,
encoding=charset,
errors=errors)
else:
fs = cgi.FieldStorage(fp=self.body_file,
environ=fs_environ,
keep_blank_values=True)
fout = t.transcode_fs(fs, r._content_type_raw)
# this order is important, because setting body_file
# resets content_length
r.body_file = fout
r.content_length = fout.tell()
fout.seek(0)
return r
# this is necessary for correct warnings depth for both
# BaseRequest and Request (due to AdhocAttrMixin.__setattr__)
_setattr_stacklevel = 2
def _body_file__get(self):
"""
Input stream of the request (wsgi.input).
Setting this property resets the content_length and seekable flag
(unlike setting req.body_file_raw).
"""
if not self.is_body_readable:
return io.BytesIO()
r = self.body_file_raw
clen = self.content_length
if not self.is_body_seekable and clen is not None:
# we need to wrap input in LimitedLengthFile
# but we have to cache the instance as well
# otherwise this would stop working
# (.remaining counter would reset between calls):
# req.body_file.read(100)
# req.body_file.read(100)
env = self.environ
wrapped, raw = env.get('webob._body_file', (0,0))
if raw is not r:
wrapped = LimitedLengthFile(r, clen)
wrapped = io.BufferedReader(wrapped)
env['webob._body_file'] = wrapped, r
r = wrapped
return r
def _body_file__set(self, value):
if isinstance(value, bytes):
warn_deprecation(
"Please use req.body = b'bytes' or req.body_file = fileobj",
'1.2',
self._setattr_stacklevel
)
self.content_length = None
self.body_file_raw = value
self.is_body_seekable = False
self.is_body_readable = True
def _body_file__del(self):
self.body = b''
body_file = property(_body_file__get,
_body_file__set,
_body_file__del,
doc=_body_file__get.__doc__)
body_file_raw = environ_getter('wsgi.input')
@property
def body_file_seekable(self):
"""
Get the body of the request (wsgi.input) as a seekable file-like
object. Middleware and routing applications should use this
attribute over .body_file.
If you access this value, CONTENT_LENGTH will also be updated.
"""
if not self.is_body_seekable:
self.make_body_seekable()
return self.body_file_raw
url_encoding = environ_getter('webob.url_encoding', 'UTF-8')
scheme = environ_getter('wsgi.url_scheme')
method = environ_getter('REQUEST_METHOD', 'GET')
http_version = environ_getter('SERVER_PROTOCOL')
content_length = converter(
environ_getter('CONTENT_LENGTH', None, '14.13'),
parse_int_safe, serialize_int, 'int')
remote_user = environ_getter('REMOTE_USER', None)
remote_addr = environ_getter('REMOTE_ADDR', None)
query_string = environ_getter('QUERY_STRING', '')
server_name = environ_getter('SERVER_NAME')
server_port = converter(
environ_getter('SERVER_PORT'),
parse_int, serialize_int, 'int')
script_name = environ_decoder('SCRIPT_NAME', '', encattr='url_encoding')
path_info = environ_decoder('PATH_INFO', encattr='url_encoding')
# bw compat
uscript_name = script_name
upath_info = path_info
_content_type_raw = environ_getter('CONTENT_TYPE', '')
def _content_type__get(self):
"""Return the content type, but leaving off any parameters (like
charset, but also things like the type in ``application/atom+xml;
type=entry``)
If you set this property, you can include parameters, or if
you don't include any parameters in the value then existing
parameters will be preserved.
"""
return self._content_type_raw.split(';', 1)[0]
def _content_type__set(self, value=None):
if value is not None:
value = str(value)
if ';' not in value:
content_type = self._content_type_raw
if ';' in content_type:
value += ';' + content_type.split(';', 1)[1]
self._content_type_raw = value
content_type = property(_content_type__get,
_content_type__set,
_content_type__set,
_content_type__get.__doc__)
_headers = None
def _headers__get(self):
"""
All the request headers as a case-insensitive dictionary-like
object.
"""
if self._headers is None:
self._headers = EnvironHeaders(self.environ)
return self._headers
def _headers__set(self, value):
self.headers.clear()
self.headers.update(value)
headers = property(_headers__get, _headers__set, doc=_headers__get.__doc__)
@property
def client_addr(self):
"""
The effective client IP address as a string. If the
``HTTP_X_FORWARDED_FOR`` header exists in the WSGI environ, this
attribute returns the client IP address present in that header
(e.g. if the header value is ``192.168.1.1, 192.168.1.2``, the value
will be ``192.168.1.1``). If no ``HTTP_X_FORWARDED_FOR`` header is
present in the environ at all, this attribute will return the value
of the ``REMOTE_ADDR`` header. If the ``REMOTE_ADDR`` header is
unset, this attribute will return the value ``None``.
.. warning::
It is possible for user agents to put someone else's IP or just
any string in ``HTTP_X_FORWARDED_FOR`` as it is a normal HTTP
header. Forward proxies can also provide incorrect values (private
IP addresses etc). You cannot "blindly" trust the result of this
method to provide you with valid data unless you're certain that
``HTTP_X_FORWARDED_FOR`` has the correct values. The WSGI server
must be behind a trusted proxy for this to be true.
"""
e = self.environ
xff = e.get('HTTP_X_FORWARDED_FOR')
if xff is not None:
addr = xff.split(',')[0].strip()
else:
addr = e.get('REMOTE_ADDR')
return addr
@property
def host_port(self):
"""
The effective server port number as a string. If the ``HTTP_HOST``
header exists in the WSGI environ, this attribute returns the port
number present in that header. If the ``HTTP_HOST`` header exists but
contains no explicit port number: if the WSGI url scheme is "https" ,
this attribute returns "443", if the WSGI url scheme is "http", this
attribute returns "80" . If no ``HTTP_HOST`` header is present in
the environ at all, this attribute will return the value of the
``SERVER_PORT`` header (which is guaranteed to be present).
"""
e = self.environ
host = e.get('HTTP_HOST')
if host is not None:
if ':' in host:
host, port = host.split(':', 1)
else:
url_scheme = e['wsgi.url_scheme']
if url_scheme == 'https':
port = '443'
else:
port = '80'
else:
port = e['SERVER_PORT']
return port
@property
def host_url(self):
"""
The URL through the host (no path)
"""
e = self.environ
scheme = e.get('wsgi.url_scheme')
url = scheme + '://'
host = e.get('HTTP_HOST')
if host is not None:
if ':' in host:
host, port = host.split(':', 1)
else:
port = None
else:
host = e.get('SERVER_NAME')
port = e.get('SERVER_PORT')
if scheme == 'https':
if port == '443':
port = None
elif scheme == 'http':
if port == '80':
port = None
url += host
if port:
url += ':%s' % port
return url
@property
def application_url(self):
"""
The URL including SCRIPT_NAME (no PATH_INFO or query string)
"""
bscript_name = bytes_(self.script_name, self.url_encoding)
return self.host_url + url_quote(bscript_name, PATH_SAFE)
@property
def path_url(self):
"""
The URL including SCRIPT_NAME and PATH_INFO, but not QUERY_STRING
"""
bpath_info = bytes_(self.path_info, self.url_encoding)
return self.application_url + url_quote(bpath_info, PATH_SAFE)
@property
def path(self):
"""
The path of the request, without host or query string
"""
bscript = bytes_(self.script_name, self.url_encoding)
bpath = bytes_(self.path_info, self.url_encoding)
return url_quote(bscript, PATH_SAFE) + url_quote(bpath, PATH_SAFE)
@property
def path_qs(self):
"""
The path of the request, without host but with query string
"""
path = self.path
qs = self.environ.get('QUERY_STRING')
if qs:
path += '?' + qs
return path
@property
def url(self):
"""
The full request URL, including QUERY_STRING
"""
url = self.path_url
qs = self.environ.get('QUERY_STRING')
if qs:
url += '?' + qs
return url
def relative_url(self, other_url, to_application=False):
"""
Resolve other_url relative to the request URL.
If ``to_application`` is True, then resolve it relative to the
URL with only SCRIPT_NAME
"""
if to_application:
url = self.application_url
if not url.endswith('/'):
url += '/'
else:
url = self.path_url
return urlparse.urljoin(url, other_url)
def path_info_pop(self, pattern=None):
"""
'Pops' off the next segment of PATH_INFO, pushing it onto
SCRIPT_NAME, and returning the popped segment. Returns None if
there is nothing left on PATH_INFO.
Does not return ``''`` when there's an empty segment (like
``/path//path``); these segments are just ignored.
Optional ``pattern`` argument is a regexp to match the return value
before returning. If there is no match, no changes are made to the
request and None is returned.
"""
path = self.path_info
if not path:
return None
slashes = ''
while path.startswith('/'):
slashes += '/'
path = path[1:]
idx = path.find('/')
if idx == -1:
idx = len(path)
r = path[:idx]
if pattern is None or re.match(pattern, r):
self.script_name += slashes + r
self.path_info = path[idx:]
return r
def path_info_peek(self):
"""
Returns the next segment on PATH_INFO, or None if there is no
next segment. Doesn't modify the environment.
"""
path = self.path_info
if not path:
return None
path = path.lstrip('/')
return path.split('/', 1)[0]
def _urlvars__get(self):
"""
Return any *named* variables matched in the URL.
Takes values from ``environ['wsgiorg.routing_args']``.
Systems like ``routes`` set this value.
"""
if 'paste.urlvars' in self.environ:
return self.environ['paste.urlvars']
elif 'wsgiorg.routing_args' in self.environ:
return self.environ['wsgiorg.routing_args'][1]
else:
result = {}
self.environ['wsgiorg.routing_args'] = ((), result)
return result
def _urlvars__set(self, value):
environ = self.environ
if 'wsgiorg.routing_args' in environ:
environ['wsgiorg.routing_args'] = (
environ['wsgiorg.routing_args'][0], value)
if 'paste.urlvars' in environ:
del environ['paste.urlvars']
elif 'paste.urlvars' in environ:
environ['paste.urlvars'] = value
else:
environ['wsgiorg.routing_args'] = ((), value)
def _urlvars__del(self):
if 'paste.urlvars' in self.environ:
del self.environ['paste.urlvars']
if 'wsgiorg.routing_args' in self.environ:
if not self.environ['wsgiorg.routing_args'][0]:
del self.environ['wsgiorg.routing_args']
else:
self.environ['wsgiorg.routing_args'] = (
self.environ['wsgiorg.routing_args'][0], {})
urlvars = property(_urlvars__get,
_urlvars__set,
_urlvars__del,
doc=_urlvars__get.__doc__)
def _urlargs__get(self):
"""
Return any *positional* variables matched in the URL.
Takes values from ``environ['wsgiorg.routing_args']``.
Systems like ``routes`` set this value.
"""
if 'wsgiorg.routing_args' in self.environ:
return self.environ['wsgiorg.routing_args'][0]
else:
# Since you can't update this value in-place, we don't need
# to set the key in the environment
return ()
def _urlargs__set(self, value):
environ = self.environ
if 'paste.urlvars' in environ:
# Some overlap between this and wsgiorg.routing_args; we need
# wsgiorg.routing_args to make this work
routing_args = (value, environ.pop('paste.urlvars'))
elif 'wsgiorg.routing_args' in environ:
routing_args = (value, environ['wsgiorg.routing_args'][1])
else:
routing_args = (value, {})
environ['wsgiorg.routing_args'] = routing_args
def _urlargs__del(self):
if 'wsgiorg.routing_args' in self.environ:
if not self.environ['wsgiorg.routing_args'][1]:
del self.environ['wsgiorg.routing_args']
else:
self.environ['wsgiorg.routing_args'] = (
(), self.environ['wsgiorg.routing_args'][1])
urlargs = property(_urlargs__get,
_urlargs__set,
_urlargs__del,
_urlargs__get.__doc__)
@property
def is_xhr(self):
"""Is X-Requested-With header present and equal to ``XMLHttpRequest``?
Note: this isn't set by every XMLHttpRequest request, it is
only set if you are using a Javascript library that sets it
(or you set the header yourself manually). Currently
Prototype and jQuery are known to set this header."""
return self.environ.get('HTTP_X_REQUESTED_WITH', '') == 'XMLHttpRequest'
def _host__get(self):
"""Host name provided in HTTP_HOST, with fall-back to SERVER_NAME"""
if 'HTTP_HOST' in self.environ:
return self.environ['HTTP_HOST']
else:
return '%(SERVER_NAME)s:%(SERVER_PORT)s' % self.environ
def _host__set(self, value):
self.environ['HTTP_HOST'] = value
def _host__del(self):
if 'HTTP_HOST' in self.environ:
del self.environ['HTTP_HOST']
host = property(_host__get, _host__set, _host__del, doc=_host__get.__doc__)
def _body__get(self):
"""
Return the content of the request body.
"""
if not self.is_body_readable:
return b''
self.make_body_seekable() # we need this to have content_length
r = self.body_file.read(self.content_length)
self.body_file_raw.seek(0)
return r
def _body__set(self, value):
if value is None:
value = b''
if not isinstance(value, bytes):
raise TypeError("You can only set Request.body to bytes (not %r)"
% type(value))
if not http_method_probably_has_body.get(self.method, True):
if not value:
self.content_length = None
self.body_file_raw = io.BytesIO()
return
self.content_length = len(value)
self.body_file_raw = io.BytesIO(value)
self.is_body_seekable = True
def _body__del(self):
self.body = b''
body = property(_body__get, _body__set, _body__del, doc=_body__get.__doc__)
def _json_body__get(self):
"""Access the body of the request as JSON"""
return json.loads(self.body.decode(self.charset))
def _json_body__set(self, value):
self.body = json.dumps(value, separators=(',', ':')).encode(self.charset)
def _json_body__del(self):
del self.body
json = json_body = property(_json_body__get, _json_body__set, _json_body__del)
def _text__get(self):
"""
Get/set the text value of the body
"""
if not self.charset:
raise AttributeError(
"You cannot access Request.text unless charset is set")
body = self.body
return body.decode(self.charset)
def _text__set(self, value):
if not self.charset:
raise AttributeError(
"You cannot access Response.text unless charset is set")
if not isinstance(value, text_type):
raise TypeError(
"You can only set Request.text to a unicode string "
"(not %s)" % type(value))
self.body = value.encode(self.charset)
def _text__del(self):
del self.body
text = property(_text__get, _text__set, _text__del, doc=_text__get.__doc__)
@property
def POST(self):
"""
Return a MultiDict containing all the variables from a form
request. Returns an empty dict-like object for non-form requests.
Form requests are typically POST requests, however PUT & PATCH requests
with an appropriate Content-Type are also supported.
"""
env = self.environ
if self.method not in ('POST', 'PUT', 'PATCH'):
return NoVars('Not a form request')
if 'webob._parsed_post_vars' in env:
vars, body_file = env['webob._parsed_post_vars']
if body_file is self.body_file_raw:
return vars
content_type = self.content_type
if ((self.method == 'PUT' and not content_type)
or content_type not in
('',
'application/x-www-form-urlencoded',
'multipart/form-data')
):
# Not an HTML form submission
return NoVars('Not an HTML form submission (Content-Type: %s)'
% content_type)
self._check_charset()
if self.is_body_seekable:
self.body_file_raw.seek(0)
fs_environ = env.copy()
# FieldStorage assumes a missing CONTENT_LENGTH, but a
# default of 0 is better:
fs_environ.setdefault('CONTENT_LENGTH', '0')
fs_environ['QUERY_STRING'] = ''
if PY3: # pragma: no cover
fs = cgi.FieldStorage(
fp=self.body_file,
environ=fs_environ,
keep_blank_values=True,
encoding='utf8')
vars = MultiDict.from_fieldstorage(fs)
else:
fs = cgi.FieldStorage(
fp=self.body_file,
environ=fs_environ,
keep_blank_values=True)
vars = MultiDict.from_fieldstorage(fs)
#ctype = self.content_type or 'application/x-www-form-urlencoded'
ctype = self._content_type_raw or 'application/x-www-form-urlencoded'
f = FakeCGIBody(vars, ctype)
self.body_file = io.BufferedReader(f)
env['webob._parsed_post_vars'] = (vars, self.body_file_raw)
return vars
@property
def GET(self):
"""
Return a MultiDict containing all the variables from the
QUERY_STRING.
"""
env = self.environ
source = env.get('QUERY_STRING', '')
if 'webob._parsed_query_vars' in env:
vars, qs = env['webob._parsed_query_vars']
if qs == source:
return vars
data = []
if source:
# this is disabled because we want to access req.GET
# for text/plain; charset=ascii uploads for example
#self._check_charset()
data = parse_qsl_text(source)
#d = lambda b: b.decode('utf8')
#data = [(d(k), d(v)) for k,v in data]
vars = GetDict(data, env)
env['webob._parsed_query_vars'] = (vars, source)
return vars
def _check_charset(self):
if self.charset != 'UTF-8':
raise DeprecationWarning(
"Requests are expected to be submitted in UTF-8, not %s. "
"You can fix this by doing req = req.decode('%s')" % (
self.charset, self.charset)
)
@property
def params(self):
"""
A dictionary-like object containing both the parameters from
the query string and request body.
"""
params = NestedMultiDict(self.GET, self.POST)
return params
@property
def cookies(self):
"""
Return a dictionary of cookies as found in the request.
"""
return RequestCookies(self.environ)
@cookies.setter
def cookies(self, val):
self.environ.pop('HTTP_COOKIE', None)
r = RequestCookies(self.environ)
r.update(val)
def copy(self):
"""
Copy the request and environment object.
This only does a shallow copy, except of wsgi.input
"""
self.make_body_seekable()
env = self.environ.copy()
new_req = self.__class__(env)
new_req.copy_body()
return new_req
def copy_get(self):
"""
Copies the request and environment object, but turning this request
into a GET along the way. If this was a POST request (or any other
verb) then it becomes GET, and the request body is thrown away.
"""
env = self.environ.copy()
return self.__class__(env, method='GET', content_type=None,
body=b'')
# webob.is_body_seekable marks input streams that are seekable
# this way we can have seekable input without testing the .seek() method
is_body_seekable = environ_getter('webob.is_body_seekable', False)
#is_body_readable = environ_getter('webob.is_body_readable', False)
def _is_body_readable__get(self):
"""
webob.is_body_readable is a flag that tells us
that we can read the input stream even though
CONTENT_LENGTH is missing. This allows FakeCGIBody
to work and can be used by servers to support
chunked encoding in requests.
For background see https://bitbucket.org/ianb/webob/issue/6
"""
if http_method_probably_has_body.get(self.method):
# known HTTP method with body
return True
elif self.content_length is not None:
# unknown HTTP method, but the Content-Length
# header is present
return True
else:
# last resort -- rely on the special flag
return self.environ.get('webob.is_body_readable', False)
def _is_body_readable__set(self, flag):
self.environ['webob.is_body_readable'] = bool(flag)
is_body_readable = property(_is_body_readable__get, _is_body_readable__set,
doc=_is_body_readable__get.__doc__
)
def make_body_seekable(self):
"""
This forces ``environ['wsgi.input']`` to be seekable.
That means that, the content is copied into a BytesIO or temporary
file and flagged as seekable, so that it will not be unnecessarily
copied again.
After calling this method the .body_file is always seeked to the
start of file and .content_length is not None.
The choice to copy to BytesIO is made from
``self.request_body_tempfile_limit``
"""
if self.is_body_seekable:
self.body_file_raw.seek(0)
else:
self.copy_body()
def copy_body(self):
"""
Copies the body, in cases where it might be shared with
another request object and that is not desired.
This copies the body in-place, either into a BytesIO object
or a temporary file.
"""
if not self.is_body_readable:
# there's no body to copy
self.body = b''
elif self.content_length is None:
# chunked body or FakeCGIBody
self.body = self.body_file_raw.read()
self._copy_body_tempfile()
else:
# try to read body into tempfile
did_copy = self._copy_body_tempfile()
if not did_copy:
# it wasn't necessary, so just read it into memory
self.body = self.body_file.read(self.content_length)
def _copy_body_tempfile(self):
"""
Copy wsgi.input to tempfile if necessary. Returns True if it did.
"""
tempfile_limit = self.request_body_tempfile_limit
todo = self.content_length
assert isinstance(todo, integer_types), todo
if not tempfile_limit or todo <= tempfile_limit:
return False
fileobj = self.make_tempfile()
input = self.body_file
while todo > 0:
data = input.read(min(todo, 65536))
if not data:
# Normally this should not happen, because LimitedLengthFile
# should have raised an exception by now.
# It can happen if the is_body_seekable flag is incorrect.
raise DisconnectionError(
"Client disconnected (%s more bytes were expected)"
% todo
)
fileobj.write(data)
todo -= len(data)
fileobj.seek(0)
self.body_file_raw = fileobj
self.is_body_seekable = True
return True
def make_tempfile(self):
"""
Create a tempfile to store big request body.
This API is not stable yet. A 'size' argument might be added.
"""
return tempfile.TemporaryFile()
def remove_conditional_headers(self,
remove_encoding=True,
remove_range=True,
remove_match=True,
remove_modified=True):
"""
Remove headers that make the request conditional.
These headers can cause the response to be 304 Not Modified,
which in some cases you may not want to be possible.
This does not remove headers like If-Match, which are used for
conflict detection.
"""
check_keys = []
if remove_range:
check_keys += ['HTTP_IF_RANGE', 'HTTP_RANGE']
if remove_match: