-
-
Notifications
You must be signed in to change notification settings - Fork 924
/
request.py
1939 lines (1560 loc) · 74.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
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Request class."""
from datetime import datetime
from uuid import UUID
from falcon import DEFAULT_MEDIA_TYPE
from falcon import errors
from falcon import request_helpers as helpers
from falcon import util
from falcon.forwarded import _parse_forwarded_header
from falcon.forwarded import Forwarded # NOQA
from falcon.media import Handlers
from falcon.util import json
from falcon.util import structures
from falcon.util.misc import isascii
from falcon.util.uri import parse_host, parse_query_string
from falcon.vendor import mimeparse
DEFAULT_ERROR_LOG_FORMAT = ('{0:%Y-%m-%d %H:%M:%S} [FALCON] [ERROR]'
' {1} {2}{3} => ')
TRUE_STRINGS = frozenset(['true', 'True', 't', 'yes', 'y', '1', 'on'])
FALSE_STRINGS = frozenset(['false', 'False', 'f', 'no', 'n', '0', 'off'])
WSGI_CONTENT_HEADERS = frozenset(['CONTENT_TYPE', 'CONTENT_LENGTH'])
# PERF(kgriffs): Avoid an extra namespace lookup when using these functions
strptime = datetime.strptime
now = datetime.now
class Request:
"""Represents a client's HTTP request.
Note:
`Request` is not meant to be instantiated directly by responders.
Args:
env (dict): A WSGI environment dict passed in from the server. See
also PEP-3333.
Keyword Arguments:
options (dict): Set of global options passed from the App handler.
Attributes:
env (dict): Reference to the WSGI environ ``dict`` passed in from the
server. (See also PEP-3333.)
context (object): Empty object to hold any data (in its attributes)
about the request which is specific to your app (e.g. session
object). Falcon itself will not interact with this attribute after
it has been initialized.
Note:
**New in 2.0:** The default `context_type` (see below) was
changed from :class:`dict` to a bare class; the preferred way to
pass request-specific data is now to set attributes directly on
the `context` object. For example::
req.context.role = 'trial'
req.context.user = 'guest'
context_type (class): Class variable that determines the factory or
type to use for initializing the `context` attribute. By default,
the framework will instantiate bare objects (instances of the bare
:class:`falcon.Context` class). However, you may override this
behavior by creating a custom child class of ``falcon.Request``,
and then passing that new class to `falcon.App()` by way of the
latter's `request_type` parameter.
Note:
When overriding `context_type` with a factory function (as
opposed to a class), the function is called like a method of
the current Request instance. Therefore the first argument is
the Request instance itself (self).
scheme (str): URL scheme used for the request. Either 'http' or
'https'.
Note:
If the request was proxied, the scheme may not
match what was originally requested by the client.
:py:attr:`forwarded_scheme` can be used, instead,
to handle such cases.
forwarded_scheme (str): Original URL scheme requested by the
user agent, if the request was proxied. Typical values are
'http' or 'https'.
The following request headers are checked, in order of
preference, to determine the forwarded scheme:
- ``Forwarded``
- ``X-Forwarded-For``
If none of these headers are available, or if the
Forwarded header is available but does not contain a
"proto" parameter in the first hop, the value of
:attr:`scheme` is returned instead.
(See also: RFC 7239, Section 1)
method (str): HTTP method requested (e.g., 'GET', 'POST', etc.)
host (str): Host request header field
forwarded_host (str): Original host request header as received
by the first proxy in front of the application server.
The following request headers are checked, in order of
preference, to determine the forwarded scheme:
- ``Forwarded``
- ``X-Forwarded-Host``
If none of the above headers are available, or if the
Forwarded header is available but the "host"
parameter is not included in the first hop, the value of
:attr:`host` is returned instead.
Note:
Reverse proxies are often configured to set the Host
header directly to the one that was originally
requested by the user agent; in that case, using
:attr:`host` is sufficient.
(See also: RFC 7239, Section 4)
port (int): Port used for the request. If the Host header is present
in the request, but does not specify a port, the default one for the
given schema is returned (80 for HTTP and 443 for HTTPS). If the
request does not include a Host header, the listening port for the
WSGI server is returned instead.
netloc (str): Returns the "host:port" portion of the request
URL. The port may be omitted if it is the default one for
the URL's schema (80 for HTTP and 443 for HTTPS).
subdomain (str): Leftmost (i.e., most specific) subdomain from the
hostname. If only a single domain name is given, `subdomain`
will be ``None``.
Note:
If the hostname in the request is an IP address, the value
for `subdomain` is undefined.
root_path (str): The initial portion of the request URI's path that
corresponds to the application object, so that the
application knows its virtual "location". This may be an
empty string, if the application corresponds to the "root"
of the server.
(Corresponds to the "SCRIPT_NAME" environ variable defined
by PEP-3333.)
app (str): Deprecated alias for :attr:`root_path`.
uri (str): The fully-qualified URI for the request.
url (str): Alias for :attr:`uri`.
forwarded_uri (str): Original URI for proxied requests. Uses
:attr:`forwarded_scheme` and :attr:`forwarded_host` in
order to reconstruct the original URI requested by the user
agent.
relative_uri (str): The path and query string portion of the
request URI, omitting the scheme and host.
prefix (str): The prefix of the request URI, including scheme,
host, and WSGI app (if any).
forwarded_prefix (str): The prefix of the original URI for
proxied requests. Uses :attr:`forwarded_scheme` and
:attr:`forwarded_host` in order to reconstruct the
original URI.
path (str): Path portion of the request URI (not including query
string).
Warning:
If this attribute is to be used by the app for any upstream
requests, any non URL-safe characters in the path must be URL
encoded back before making the request.
Note:
``req.path`` may be set to a new value by a
``process_request()`` middleware method in order to influence
routing. If the original request path was URL encoded, it will
be decoded before being returned by this attribute.
query_string (str): Query string portion of the request URI, without
the preceding '?' character.
uri_template (str): The template for the route that was matched for
this request. May be ``None`` if the request has not yet been
routed, as would be the case for ``process_request()`` middleware
methods. May also be ``None`` if your app uses a custom routing
engine and the engine does not provide the URI template when
resolving a route.
remote_addr(str): IP address of the closest client or proxy to
the WSGI server.
This property is determined by the value of ``REMOTE_ADDR``
in the WSGI environment dict. Since this address is not
derived from an HTTP header, clients and proxies can not
forge it.
Note:
If your application is behind one or more reverse
proxies, you can use :py:attr:`~.access_route`
to retrieve the real IP address of the client.
access_route(list): IP address of the original client, as well
as any known addresses of proxies fronting the WSGI server.
The following request headers are checked, in order of
preference, to determine the addresses:
- ``Forwarded``
- ``X-Forwarded-For``
- ``X-Real-IP``
If none of these headers are available, the value of
:py:attr:`~.remote_addr` is used instead.
Note:
Per `RFC 7239`_, the access route may contain "unknown"
and obfuscated identifiers, in addition to IPv4 and
IPv6 addresses
.. _RFC 7239: https://tools.ietf.org/html/rfc7239
Warning:
Headers can be forged by any client or proxy. Use this
property with caution and validate all values before
using them. Do not rely on the access route to authorize
requests.
forwarded (list): Value of the Forwarded header, as a parsed list
of :class:`falcon.Forwarded` objects, or ``None`` if the header
is missing. If the header value is malformed, Falcon will
make a best effort to parse what it can.
(See also: RFC 7239, Section 4)
date (datetime): Value of the Date header, converted to a
``datetime`` instance. The header value is assumed to
conform to RFC 1123.
auth (str): Value of the Authorization header, or ``None`` if the
header is missing.
user_agent (str): Value of the User-Agent header, or ``None`` if the
header is missing.
referer (str): Value of the Referer header, or ``None`` if
the header is missing.
accept (str): Value of the Accept header, or ``'*/*'`` if the header is
missing.
client_accepts_json (bool): ``True`` if the Accept header indicates
that the client is willing to receive JSON, otherwise ``False``.
client_accepts_msgpack (bool): ``True`` if the Accept header indicates
that the client is willing to receive MessagePack, otherwise
``False``.
client_accepts_xml (bool): ``True`` if the Accept header indicates that
the client is willing to receive XML, otherwise ``False``.
cookies (dict):
A dict of name/value cookie pairs. The returned object should be
treated as read-only to avoid unintended side-effects.
If a cookie appears more than once in the request, only the first
value encountered will be made available here.
See also: :meth:`~falcon.Request.get_cookie_values`
content_type (str): Value of the Content-Type header, or ``None`` if
the header is missing.
content_length (int): Value of the Content-Length header converted
to an ``int``, or ``None`` if the header is missing.
stream: File-like input object for reading the body of the
request, if any. This object provides direct access to the
server's data stream and is non-seekable. In order to
avoid unintended side effects, and to provide maximum
flexibility to the application, Falcon itself does not
buffer or spool the data in any way.
Since this object is provided by the WSGI
server itself, rather than by Falcon, it may behave
differently depending on how you host your app. For example,
attempting to read more bytes than are expected (as
determined by the Content-Length header) may or may not
block indefinitely. It's a good idea to test your WSGI
server to find out how it behaves.
This can be particulary problematic when a request body is
expected, but none is given. In this case, the following
call blocks under certain WSGI servers::
# Blocks if Content-Length is 0
data = req.stream.read()
The workaround is fairly straightforward, if verbose::
# If Content-Length happens to be 0, or the header is
# missing altogether, this will not block.
data = req.stream.read(req.content_length or 0)
Alternatively, when passing the stream directly to a
consumer, it may be necessary to branch off the
value of the Content-Length header::
if req.content_length:
doc = json.load(req.stream)
For a slight performance cost, you may instead wish to use
:py:attr:`bounded_stream`, which wraps the native WSGI
input object to normalize its behavior.
Note:
If an HTML form is POSTed to the API using the
*application/x-www-form-urlencoded* media type, and
the :py:attr:`~.RequestOptions.auto_parse_form_urlencoded`
option is set, the framework
will consume `stream` in order to parse the parameters
and merge them into the query string parameters. In this
case, the stream will be left at EOF.
bounded_stream: File-like wrapper around `stream` to normalize
certain differences between the native input objects
employed by different WSGI servers. In particular,
`bounded_stream` is aware of the expected Content-Length of
the body, and will never block on out-of-bounds reads,
assuming the client does not stall while transmitting the
data to the server.
For example, the following will not block when
Content-Length is 0 or the header is missing altogether::
data = req.bounded_stream.read()
This is also safe::
doc = json.load(req.bounded_stream)
media (object): Property that acts as an alias for
:meth:`~.get_media`. This alias provides backwards-compatibility
for apps that were built for versions of the framework prior to
3.0::
# Equivalent to: deserialized_media = req.get_media()
deserialized_media = req.media
expect (str): Value of the Expect header, or ``None`` if the
header is missing.
range (tuple of int): A 2-member ``tuple`` parsed from the value of the
Range header.
The two members correspond to the first and last byte
positions of the requested resource, inclusive. Negative
indices indicate offset from the end of the resource,
where -1 is the last byte, -2 is the second-to-last byte,
and so forth.
Only continous ranges are supported (e.g., "bytes=0-0,-1" would
result in an HTTPBadRequest exception when the attribute is
accessed.)
range_unit (str): Unit of the range parsed from the value of the
Range header, or ``None`` if the header is missing
if_match (list): Value of the If-Match header, as a parsed list of
:class:`falcon.ETag` objects or ``None`` if the header is missing
or its value is blank.
This property provides a list of all ``entity-tags`` in the
header, both strong and weak, in the same order as listed in
the header.
(See also: RFC 7232, Section 3.1)
if_none_match (list): Value of the If-None-Match header, as a parsed
list of :class:`falcon.ETag` objects or ``None`` if the header is
missing or its value is blank.
This property provides a list of all ``entity-tags`` in the
header, both strong and weak, in the same order as listed in
the header.
(See also: RFC 7232, Section 3.2)
if_modified_since (datetime): Value of the If-Modified-Since header,
or ``None`` if the header is missing.
if_unmodified_since (datetime): Value of the If-Unmodified-Since
header, or ``None`` if the header is missing.
if_range (str): Value of the If-Range header, or ``None`` if the
header is missing.
headers (dict): Raw HTTP headers from the request with
canonical dash-separated names. Parsing all the headers
to create this dict is done the first time this attribute
is accessed, and the returned object should be treated as
read-only. Note that this parsing can be costly, so unless you
need all the headers in this format, you should instead use the
``get_header()`` method or one of the convenience attributes
to get a value for a specific header.
params (dict): The mapping of request query parameter names to their
values. Where the parameter appears multiple times in the query
string, the value mapped to that parameter key will be a list of
all the values in the order seen.
options (dict): Set of global options passed from the App handler.
"""
__slots__ = (
'__dict__',
'_bounded_stream',
'_cached_access_route',
'_cached_forwarded',
'_cached_forwarded_prefix',
'_cached_forwarded_uri',
'_cached_headers',
'_cached_prefix',
'_cached_relative_uri',
'_cached_uri',
'_params',
'_wsgierrors',
'content_type',
'context',
'env',
'method',
'options',
'path',
'query_string',
'stream',
'uri_template',
'_media',
)
_cookies = None
_cookies_collapsed = None
_cached_if_match = None
_cached_if_none_match = None
# Child classes may override this
context_type = structures.Context
_wsgi_input_type_known = False
def __init__(self, env, options=None):
self.env = env
self.options = options if options else RequestOptions()
self._wsgierrors = env['wsgi.errors']
self.method = env['REQUEST_METHOD']
self.uri_template = None
self._media = None
# NOTE(kgriffs): PEP 3333 specifies that PATH_INFO may be the
# empty string, so normalize it in that case.
path = env['PATH_INFO'] or '/'
# PEP 3333 specifies that the PATH_INFO variable is always
# "bytes tunneled as latin-1" and must be encoded back.
#
# NOTE(kgriffs): The decoded path may contain UTF-8 characters.
# But according to the WSGI spec, no strings can contain chars
# outside ISO-8859-1. Therefore, to reconcile the URI
# encoding standard that allows UTF-8 with the WSGI spec
# that does not, WSGI servers tunnel the string via
# ISO-8859-1, e.g.:
#
# tunnelled_path = path.encode('utf-8').decode('iso-8859-1')
# perf(vytas): Only decode the tunnelled path in case it is not ASCII.
# For ASCII-strings, the below decoding chain is a no-op.
if not isascii(path):
path = path.encode('iso-8859-1').decode('utf-8', 'replace')
if (self.options.strip_url_path_trailing_slash and
len(path) != 1 and path.endswith('/')):
self.path = path[:-1]
else:
self.path = path
# PERF(ueg1990): try/catch cheaper and faster (and more Pythonic)
try:
self.query_string = env['QUERY_STRING']
except KeyError:
self.query_string = ''
self._params = {}
else:
if self.query_string:
self._params = parse_query_string(
self.query_string,
keep_blank=self.options.keep_blank_qs_values,
csv=self.options.auto_parse_qs_csv,
)
else:
self._params = {}
self._cached_access_route = None
self._cached_forwarded = None
self._cached_forwarded_prefix = None
self._cached_forwarded_uri = None
self._cached_headers = None
self._cached_prefix = None
self._cached_relative_uri = None
self._cached_uri = None
try:
self.content_type = self.env['CONTENT_TYPE']
except KeyError:
self.content_type = None
self.stream = env['wsgi.input']
self._bounded_stream = None # Lazy wrapping
# PERF(kgriffs): Technically, we should spend a few more
# cycles and parse the content type for real, but
# this heuristic will work virtually all the time.
if (
self.options.auto_parse_form_urlencoded and
self.content_type is not None and
'application/x-www-form-urlencoded' in self.content_type and
# NOTE(kgriffs): Within HTTP, a payload for a GET or HEAD
# request has no defined semantics, so we don't expect a
# body in those cases. We would normally not expect a body
# for OPTIONS either, but RFC 7231 does allow for it.
self.method not in ('GET', 'HEAD')
):
self._parse_form_urlencoded()
self.context = self.context_type()
def __repr__(self):
return '<%s: %s %r>' % (self.__class__.__name__, self.method, self.url)
# ------------------------------------------------------------------------
# Properties
# ------------------------------------------------------------------------
user_agent = helpers.header_property('HTTP_USER_AGENT')
auth = helpers.header_property('HTTP_AUTHORIZATION')
expect = helpers.header_property('HTTP_EXPECT')
if_range = helpers.header_property('HTTP_IF_RANGE')
referer = helpers.header_property('HTTP_REFERER')
@property
def forwarded(self):
# PERF(kgriffs): We could DRY up this memoization pattern using
# a decorator, but that would incur additional overhead without
# resorting to some trickery to rewrite the body of the method
# itself (vs. simply wrapping it with some memoization logic).
# At some point we might look into this but I don't think
# it's worth it right now.
if self._cached_forwarded is None:
forwarded = self.get_header('Forwarded')
if forwarded is None:
return None
self._cached_forwarded = _parse_forwarded_header(forwarded)
return self._cached_forwarded
@property
def client_accepts_json(self):
return self.client_accepts('application/json')
@property
def client_accepts_msgpack(self):
return (self.client_accepts('application/x-msgpack') or
self.client_accepts('application/msgpack'))
@property
def client_accepts_xml(self):
return self.client_accepts('application/xml')
@property
def accept(self):
# NOTE(kgriffs): Per RFC, a missing accept header is
# equivalent to '*/*'
try:
return self.env['HTTP_ACCEPT'] or '*/*'
except KeyError:
return '*/*'
@property
def content_length(self):
try:
value = self.env['CONTENT_LENGTH']
except KeyError:
return None
# NOTE(kgriffs): Normalize an empty value to behave as if
# the header were not included; wsgiref, at least, inserts
# an empty CONTENT_LENGTH value if the request does not
# set the header. Gunicorn and uWSGI do not do this, but
# others might if they are trying to match wsgiref's
# behavior too closely.
if not value:
return None
try:
value_as_int = int(value)
except ValueError:
msg = 'The value of the header must be a number.'
raise errors.HTTPInvalidHeader(msg, 'Content-Length')
if value_as_int < 0:
msg = 'The value of the header must be a positive number.'
raise errors.HTTPInvalidHeader(msg, 'Content-Length')
return value_as_int
@property
def bounded_stream(self):
if self._bounded_stream is None:
self._bounded_stream = self._get_wrapped_wsgi_input()
return self._bounded_stream
@property
def date(self):
return self.get_header_as_datetime('Date')
@property
def if_match(self):
# TODO(kgriffs): It may make sense at some point to create a
# header property generator that DRY's up the memoization
# pattern for us.
# PERF(kgriffs): It probably isn't worth it to set
# self._cached_if_match to a special type/object to distinguish
# between the variable being unset and the header not being
# present in the request. The reason is that if the app
# gets a None back on the first reference to property, it
# probably isn't going to access the property again (TBD).
if self._cached_if_match is None:
header_value = self.env.get('HTTP_IF_MATCH')
if header_value:
self._cached_if_match = helpers._parse_etags(header_value)
return self._cached_if_match
@property
def if_none_match(self):
if self._cached_if_none_match is None:
header_value = self.env.get('HTTP_IF_NONE_MATCH')
if header_value:
self._cached_if_none_match = helpers._parse_etags(header_value)
return self._cached_if_none_match
@property
def if_modified_since(self):
return self.get_header_as_datetime('If-Modified-Since')
@property
def if_unmodified_since(self):
return self.get_header_as_datetime('If-Unmodified-Since')
@property
def range(self):
value = self.get_header('Range')
if value is None:
return None
if '=' in value:
unit, sep, req_range = value.partition('=')
else:
msg = "The value must be prefixed with a range unit, e.g. 'bytes='"
raise errors.HTTPInvalidHeader(msg, 'Range')
if ',' in req_range:
msg = 'The value must be a continuous range.'
raise errors.HTTPInvalidHeader(msg, 'Range')
try:
first, sep, last = req_range.partition('-')
if not sep:
raise ValueError()
if first:
return (int(first), int(last or -1))
elif last:
return (-int(last), -1)
else:
msg = 'The range offsets are missing.'
raise errors.HTTPInvalidHeader(msg, 'Range')
except ValueError:
href = 'http://goo.gl/zZ6Ey'
href_text = 'HTTP/1.1 Range Requests'
msg = 'It must be a range formatted according to RFC 7233.'
raise errors.HTTPInvalidHeader(msg, 'Range', href=href,
href_text=href_text)
@property
def range_unit(self):
value = self.get_header('Range')
if value is None:
return None
if value and '=' in value:
unit, sep, req_range = value.partition('=')
return unit
else:
msg = "The value must be prefixed with a range unit, e.g. 'bytes='"
raise errors.HTTPInvalidHeader(msg, 'Range')
@property
def root_path(self):
# PERF(kgriffs): try..except is faster than get() assuming that
# we normally expect the key to exist. Even though PEP-3333
# allows WSGI servers to omit the key when the value is an
# empty string, uwsgi, gunicorn, waitress, and wsgiref all
# include it even in that case.
try:
return self.env['SCRIPT_NAME']
except KeyError:
return ''
app = root_path
@property
def scheme(self):
return self.env['wsgi.url_scheme']
@property
def forwarded_scheme(self):
# PERF(kgriffs): Since the Forwarded header is still relatively
# new, we expect X-Forwarded-Proto to be more common, so
# try to avoid calling self.forwarded if we can, since it uses a
# try...catch that will usually result in a relatively expensive
# raised exception.
if 'HTTP_FORWARDED' in self.env:
first_hop = self.forwarded[0]
scheme = first_hop.scheme or self.scheme
else:
# PERF(kgriffs): This call should normally succeed, so
# just go for it without wasting time checking it
# first. Note also that the indexing operator is
# slightly faster than using get().
try:
scheme = self.env['HTTP_X_FORWARDED_PROTO'].lower()
except KeyError:
scheme = self.env['wsgi.url_scheme']
return scheme
@property
def uri(self):
if self._cached_uri is None:
# PERF: For small numbers of items, '+' is faster
# than ''.join(...). Concatenation is also generally
# faster than formatting.
value = (self.scheme + '://' +
self.netloc +
self.relative_uri)
self._cached_uri = value
return self._cached_uri
url = uri
@property
def forwarded_uri(self):
if self._cached_forwarded_uri is None:
# PERF: For small numbers of items, '+' is faster
# than ''.join(...). Concatenation is also generally
# faster than formatting.
value = (self.forwarded_scheme + '://' +
self.forwarded_host +
self.relative_uri)
self._cached_forwarded_uri = value
return self._cached_forwarded_uri
@property
def relative_uri(self):
if self._cached_relative_uri is None:
if self.query_string:
self._cached_relative_uri = (self.app + self.path + '?' +
self.query_string)
else:
self._cached_relative_uri = self.app + self.path
return self._cached_relative_uri
@property
def prefix(self):
if self._cached_prefix is None:
self._cached_prefix = (
self.scheme + '://' +
self.netloc +
self.app
)
return self._cached_prefix
@property
def forwarded_prefix(self):
if self._cached_forwarded_prefix is None:
self._cached_forwarded_prefix = (
self.forwarded_scheme + '://' +
self.forwarded_host +
self.app
)
return self._cached_forwarded_prefix
@property
def host(self):
try:
# NOTE(kgriffs): Prefer the host header; the web server
# isn't supposed to mess with it, so it should be what
# the client actually sent.
host_header = self.env['HTTP_HOST']
host, port = parse_host(host_header)
except KeyError:
# PERF(kgriffs): According to PEP-3333, this header
# will always be present.
host = self.env['SERVER_NAME']
return host
@property
def forwarded_host(self):
# PERF(kgriffs): Since the Forwarded header is still relatively
# new, we expect X-Forwarded-Host to be more common, so
# try to avoid calling self.forwarded if we can, since it uses a
# try...catch that will usually result in a relatively expensive
# raised exception.
if 'HTTP_FORWARDED' in self.env:
first_hop = self.forwarded[0]
host = first_hop.host or self.netloc
else:
# PERF(kgriffs): This call should normally succeed, assuming
# that the caller is expecting a forwarded header, so
# just go for it without wasting time checking it
# first.
try:
host = self.env['HTTP_X_FORWARDED_HOST']
except KeyError:
host = self.netloc
return host
@property
def subdomain(self):
# PERF(kgriffs): .partition is slightly faster than .split
subdomain, sep, remainder = self.host.partition('.')
return subdomain if sep else None
@property
def headers(self):
# NOTE(kgriffs: First time here will cache the dict so all we
# have to do is clone it in the future.
if self._cached_headers is None:
headers = self._cached_headers = {}
env = self.env
for name, value in env.items():
if name.startswith('HTTP_'):
# NOTE(kgriffs): Don't take the time to fix the case
# since headers are supposed to be case-insensitive
# anyway.
headers[name[5:].replace('_', '-')] = value
elif name in WSGI_CONTENT_HEADERS:
headers[name.replace('_', '-')] = value
return self._cached_headers
@property
def params(self):
return self._params
@property
def cookies(self):
if self._cookies_collapsed is None:
if self._cookies is None:
header_value = self.get_header('Cookie')
if header_value:
self._cookies = helpers.parse_cookie_header(header_value)
else:
self._cookies = {}
self._cookies_collapsed = {n: v[0] for n, v in self._cookies.items()}
return self._cookies_collapsed
@property
def access_route(self):
if self._cached_access_route is None:
# NOTE(kgriffs): Try different headers in order of
# preference; if none are found, fall back to REMOTE_ADDR.
#
# If one of these headers is present, but its value is
# malformed such that we end up with an empty list, or
# a non-empty list containing malformed values, go ahead
# and return the results as-is. The alternative would be
# to fall back to another header or to REMOTE_ADDR, but
# that only masks the problem; the operator needs to be
# aware that an upstream proxy is malfunctioning.
if 'HTTP_FORWARDED' in self.env:
self._cached_access_route = []
for hop in self.forwarded:
if hop.src is not None:
host, __ = parse_host(hop.src)
self._cached_access_route.append(host)
elif 'HTTP_X_FORWARDED_FOR' in self.env:
addresses = self.env['HTTP_X_FORWARDED_FOR'].split(',')
self._cached_access_route = [ip.strip() for ip in addresses]
elif 'HTTP_X_REAL_IP' in self.env:
self._cached_access_route = [self.env['HTTP_X_REAL_IP']]
if self._cached_access_route:
if self._cached_access_route[-1] != self.remote_addr:
self._cached_access_route.append(self.remote_addr)
else:
self._cached_access_route = [self.remote_addr]
return self._cached_access_route
@property
def remote_addr(self):
try:
value = self.env['REMOTE_ADDR']
except KeyError:
value = '127.0.0.1'
return value
@property
def port(self):
try:
host_header = self.env['HTTP_HOST']
default_port = 80 if self.env['wsgi.url_scheme'] == 'http' else 443
host, port = parse_host(host_header, default_port=default_port)
except KeyError:
# NOTE(kgriffs): Normalize to an int, since that is the type
# returned by parse_host().
#
# NOTE(kgriffs): In the case that SERVER_PORT was used,
# PEP-3333 requires that the port never be an empty string.
port = int(self.env['SERVER_PORT'])
return port
@property
def netloc(self):
env = self.env
# NOTE(kgriffs): According to PEP-3333 we should first
# try to use the Host header if present.
#
# PERF(kgriffs): try..except is faster than get() when we
# expect the key to be present most of the time.
try:
netloc_value = env['HTTP_HOST']
except KeyError:
netloc_value = env['SERVER_NAME']
port = env['SERVER_PORT']
if self.scheme == 'https':
if port != '443':
netloc_value += ':' + port
else:
if port != '80':
netloc_value += ':' + port
return netloc_value
def get_media(self):
"""Returns a deserialized form of the request stream.
The first time this method is called, the request stream will be
deserialized using the Content-Type header as well as the media-type
handlers configured via :class:`falcon.RequestOptions`. The result will
be cached and returned in subsequent calls::
deserialized_media = req.get_media()
If the matched media handler raises an error while attempting to
deserialize the request body, the exception will propagate up
to the caller.
See also :ref:`media` for more information regarding media handling.
Warning:
This operation will consume the request stream the first time
it's called and cache the results. Follow-up calls will just
retrieve a cached version of the object.
"""
if self._media is not None or self.bounded_stream.eof:
return self._media
handler = self.options.media_handlers.find_by_media_type(
self.content_type,
self.options.default_media_type