/
request.py
1801 lines (1577 loc) · 63.1 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 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,
parse_auth,
parse_int,
parse_int_safe,
parse_range,
serialize_auth,
serialize_if_range,
serialize_int,
serialize_range,
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']
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'), True))
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
# encoding used to encode/decode script_name/path_info
url_encoding = 'utf-8'
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)
_charset = None
@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
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')
# raw wsgi values (bytes on py2, bytes-tunneled-via-text on py3)
script_name = deprecated_property(
environ_getter('SCRIPT_NAME', ''),
'script_name',
'deprecated in WebOb 1.2, use scriptname or scriptname_bytes instead',
'1.4')
path_info = deprecated_property(
environ_getter('PATH_INFO'),
'path_info',
'deprecated in WebOb 1.2, use pathinfo or pathinfo_bytes instead',
'1.4')
if PY3: # pragma: no cover
def _bytes_to_wsgi(self, val):
return val.decode('latin-1')
def _bytes_from_wsgi(self, val):
return val.encode('latin-1')
else:
def _bytes_from_wsgi(self, val):
return val
def _bytes_to_wsgi(self, val):
return val
def _pathinfo__get(self):
""" Returns the decoded value of ``PATH_INFO`` WSGI variable as text
(a ``unicode`` value on Python 2, a ``str`` value on Python 3). On
Python 2, ``pathinfo`` will return the value of
``environ['PATH_INFO']`` decoded from the request's URL encoding, but
on Python 3, it will return the value of ``environ['PATH_INFO']``
encoded to Latin-1, *then* decoded from the request's URL encoding as
per the PEP 333 spec.
This differs from the older deprecated ``path_info`` descriptor
because it "WSGI-decodes" the value before returning it. The "raw"
``environ['PATH_INFO']`` value is not a sensible value to use across
software that must run on both Python 2 and Python 3, because Python
2 ``environ['PATH_INFO']`` will be bytes, and Python 3
``environ['PATH_INFO']`` will be bytes-tunnelled-via-text (as per PEP
3333).
If no ``PATH_INFO`` is in the environ, the string '/' will be
returned.
If you attempt to set this value, you must pass a text value, not
bytes. On Python 2, the value will be encoded to the request's URL
encoding (usually UTF-8) and stored in the ``PATH_INFO`` environment
variable as bytes. On Python 3, it will be encoded to to the
request's URL encoding, then the resulting encoded value will be
decoded to Latin-1 and stored in the ``PATH_INFO`` environment
variable as text.
The request attribute named ``upath_info`` is an alias for this
attribute.
"""
val = self.environ.get('PATH_INFO', None)
if val is not None: # optimization
return self._bytes_from_wsgi(val).decode(self.url_encoding)
return '/'
def _pathinfo__set(self, val):
if not isinstance(val, text_type):
raise ValueError(
'setting pathinfo requires text type, not %r' % val)
val = self._bytes_to_wsgi(val.encode(self.url_encoding))
self.environ['PATH_INFO'] = val
pathinfo = property(_pathinfo__get,
_pathinfo__set,
_pathinfo__get.__doc__)
upath_info = pathinfo # bw compat (forever)
def _pathinfo_bytes__get(self):
""" Returns the decoded value of ``PATH_INFO`` WSGI variable as bytes
(A ``str`` value on Python 2, a ``bytes`` value on Python 3). On
Python 2, ``pathinfo_bytes`` will return the raw value of
``environ['PATH_INFO']`` but on Python 3, it will return the value of
``environ['PATH_INFO']`` encoded to Latin-1, as per the PEP 333 spec.
This behvaior differs from the older deprecated ``path_info``
descriptor because it "WSGI-decodes" the value before returning it on
Python 3. The "raw" ``environ['PATH_INFO']`` value is not a sensible
value to use across software that must run on both Python 2 and
Python 3, because Python 2 ``environ['PATH_INFO']`` will be bytes,
and Python 3 ``environ['PATH_INFO']`` will be
bytes-tunnelled-via-text (as per PEP 3333).
If no ``PATH_INFO`` is in the environ, the byte value b'/' will be
returned.
If you attempt to set this value, you must pass a binary (bytes)
value, not text. On Python 2, the value will be encoded to the
request's URL encoding (usually UTF-8) and stored in the
``PATH_INFO`` environment variable as bytes. On Python 3, it will be
encoded to to the request's URL encoding, then the resulting encoded
value will be decoded to Latin-1 and stored in the ``PATH_INFO``
environment variable as text.
"""
val = self.environ.get('PATH_INFO', None)
if val is not None:
return self._bytes_from_wsgi(val)
return b'/'
def _pathinfo_bytes__set(self, val):
if not isinstance(val, bytes):
raise ValueError(
'setting pathinfo_bytes requires binary input, not %r' % val)
val = self._bytes_to_wsgi(val)
self.environ['PATH_INFO'] = val
pathinfo_bytes = property(_pathinfo_bytes__get,
_pathinfo_bytes__set,
_pathinfo_bytes__get.__doc__)
def _scriptname__get(self):
""" Returns the decoded value of the ``SCRIPT_NAME`` WSGI variable as
text (a ``unicode`` value on Python 2, a ``str`` value on Python 3).
On Python 2, ``scriptname`` will return the value of
``environ['SCRIPT_NAME']`` deoded using the request's URL encoding,
but on Python 3, it will return the value of
``environ['SCRIPT_NAME']`` encoded to Latin-1, *then* decoded using
the request's URL encoding as per the PEP 333 spec.
This differs from the older deprecated ``script_name`` descriptor
because it "WSGI-decodes" the value before returning it on Python 3.
The "raw" ``environ['SCRIPT_NAME']`` value is not a sensible value to
use across software that must run on both Python 2 and Python 3,
because Python 2 ``environ['SCRIPT_NAME']`` will be bytes, and Python
3 ``environ['SCRIPT_NAME']`` will be bytes-tunnelled-via-text (as per
PEP 3333).
If ``SCRIPT_NAME`` does not exist in the environ, an empty text value
will be returned.
If you attempt to set this value, you must pass a text value, not
bytes. On Python 2, the value will be encoded to UTF-8 and stored in
the ``SCRIPT_NAME`` environment variable as bytes. On Python 3, it
will be encoded to UTF-8, then the resulting value will be decoded to
Latin-1 and stored in the ``SCRIPT_NAME`` environment variable as
text.
The request attribute named ``uscript_name`` is an alias for this
attribute.
"""
val = self.environ.get('SCRIPT_NAME', '')
if val: # optimization
return self._bytes_from_wsgi(val).decode(self.url_encoding)
return val
def _scriptname__set(self, val):
if not isinstance(val, text_type):
raise ValueError(
'setting scriptname requires text type, not %r' % val)
val = self._bytes_to_wsgi(val.encode(self.url_encoding))
self.environ['SCRIPT_NAME'] = val
scriptname = property(_scriptname__get,
_scriptname__set,
_scriptname__get.__doc__)
uscript_name = scriptname # bw compat (forever)
def _scriptname_bytes__get(self):
""" Returns the value of ``SCRIPT_NAME`` WSGI variable as a
bytestring (a ``str`` value on Python 2, a ``bytes`` value on Python
3). This means that on Python 2, ``scriptname_bytes`` will return
the raw value of ``SCRIPT_NAME`` but on Python 3, it will return the
value of ``SCRIPT_NAME`` encoded to Latin-1, as per the PEP 3333
spec.
This differs from the older deprecated ``script_name`` descriptor
because it WSGI-decodes the value before returning it onm Python 3.
The "raw" ``environ['SCRIPT_NAME']`` value is not a sensible value to
use across software that must run on both Python 2 and Python 3,
because Python 2 ``environ['SCRIPT_NAME']`` will be bytes, and Python
3 ``environ['SCRIPT_NAME']`` will be bytes-tunnelled-via-text (as per
PEP 3333).
If ``SCRIPT_NAME`` does not exist in the environ, the empty byte will
be returned.
If you attempt to set this value, you must pass a bytes value, not
text. On Python 2, stored in the ``SCRIPT_NAME`` environment
variable as bytes unchanged. On Python 3, it will be decoded to
Latin-1, and stored in the ``SCRIPT_NAME`` environment variable as
text.
"""
val = self.environ.get('SCRIPT_NAME', '')
return self._bytes_from_wsgi(val)
def _scriptname_bytes__set(self, val):
if not isinstance(val, bytes):
raise ValueError(
'setting scriptname_bytes requires binary input, not %r' % val)
val = self._bytes_to_wsgi(val)
self.environ['SCRIPT_NAME'] = val
scriptname_bytes = property(_scriptname_bytes__get,
_scriptname_bytes__set,
_scriptname_bytes__get.__doc__)
_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 = self.environ['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
url = e['wsgi.url_scheme'] + '://'
if e.get('HTTP_HOST'):
host = e['HTTP_HOST']
if ':' in host:
host, port = host.split(':', 1)
else:
port = None
else:
host = e['SERVER_NAME']
port = e['SERVER_PORT']
if self.environ['wsgi.url_scheme'] == 'https':
if port == '443':
port = None
elif self.environ['wsgi.url_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)
"""
return self.host_url + url_quote(self.scriptname_bytes, PATH_SAFE)
@property
def path_url(self):
"""
The URL including script name and path info, but not query string
"""
return self.application_url + url_quote(self.pathinfo_bytes, PATH_SAFE)
@property
def path(self):
"""
The path of the request, without host or query string
"""
return (url_quote(self.scriptname_bytes, PATH_SAFE) +
url_quote(self.pathinfo_bytes, 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
if self.environ.get('QUERY_STRING'):
url += '?' + self.environ['QUERY_STRING']
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 scriptname
"""
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 bytestring segment of PATH_INFO, pushing it onto
SCRIPT_NAME, and returning the popped segment, which will be a
bytestring. 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. The pattern must always match against
a bytes object (not unicode).
"""
path = self.pathinfo_bytes
if not path:
return None
slashes = b''
while path.startswith(b'/'):
slashes += b'/'
path = path[1:]
idx = path.find(b'/')
if idx == -1:
idx = len(path)
r = path[:idx]
if pattern is None or re.match(pattern, r):
self.scriptname_bytes += slashes + r
self.pathinfo_bytes = path[idx:]
return r
def path_info_peek(self):
"""
Returns the next bytestring segment on PATH_INFO, or None if there is
no next segment. Doesn't modify the environment.
"""
path = self.pathinfo_bytes
if not path:
return None
path = path.lstrip(b'/')
return path.split(b'/', 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__)
@property
def json_body(self):
return json.loads(self.body.decode(self.charset))
@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 requests with
an appropriate Content-Type are also supported.
"""
env = self.environ
if self.method not in ('POST', 'PUT'):
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