FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[Original HTTPS Page]
cpython/Lib/urllib/parse.py at 3.15 · python/cpython · GitHub
python
cpython
Repository navigation
Code
Issues
5k+
(5k+)
Pull requests
2.7k
(2.7k)
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
cpython
/
Lib
/
urllib
/
parse.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
1407 lines (1170 loc) · 49.9 KB
Breadcrumbs
cpython
/
Lib
/
urllib
/
parse.py
Copy path
File metadata and controls
1407 lines (1170 loc) · 49.9 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""Parse (absolute and relative) URLs.
urllib.parse module is based upon the following RFC specifications.
RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding
and L. Masinter, January 2005.
RFC 2732 : "Format for Literal IPv6 Addresses in URL's by R.Hinden, B.Carpenter
and L.Masinter, December 1999.
RFC 2396: "Uniform Resource Identifiers (URI)": Generic Syntax by T.
Berners-Lee, R. Fielding, and L. Masinter, August 1998.
RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zawinski, July 1998.
RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, UC Irvine, June
1995.
RFC 1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M.
McCahill, December 1994
RFC 3986 is considered the current standard and any future changes to
urllib.parse module should conform with it. The urllib.parse module is
currently not entirely compliant with this RFC due to defacto
scenarios for parsing, and for backward compatibility purposes, some
parsing quirks from older RFCs are retained. The testcases in
test_urlparse.py provides a good indicator of parsing behavior.
The WHATWG URL Parser spec should also be considered. We are not compliant with
it either due to existing user code API behavior expectations (Hyrum's Law).
It serves as a useful guide when making changes.
"""
from
collections
import
namedtuple
import
functools
import
math
import
re
import
types
import
warnings
import
ipaddress
__all__
=
[
"urlparse"
,
"urlunparse"
,
"urljoin"
,
"urldefrag"
,
"urlsplit"
,
"urlunsplit"
,
"urlencode"
,
"parse_qs"
,
"parse_qsl"
,
"quote"
,
"quote_plus"
,
"quote_from_bytes"
,
"unquote"
,
"unquote_plus"
,
"unquote_to_bytes"
,
"DefragResult"
,
"ParseResult"
,
"SplitResult"
,
"DefragResultBytes"
,
"ParseResultBytes"
,
"SplitResultBytes"
]
# A classification of schemes.
# The empty string classifies URLs with no scheme specified,
# being the default value returned by “urlsplit” and “urlparse”.
uses_relative
=
[
''
,
'ftp'
,
'http'
,
'gopher'
,
'nntp'
,
'imap'
,
'wais'
,
'file'
,
'https'
,
'shttp'
,
'mms'
,
'prospero'
,
'rtsp'
,
'rtsps'
,
'rtspu'
,
'sftp'
,
'svn'
,
'svn+ssh'
,
'ws'
,
'wss'
]
uses_netloc
=
[
''
,
'ftp'
,
'http'
,
'gopher'
,
'nntp'
,
'telnet'
,
'imap'
,
'wais'
,
'file'
,
'mms'
,
'https'
,
'shttp'
,
'snews'
,
'prospero'
,
'rtsp'
,
'rtsps'
,
'rtspu'
,
'rsync'
,
'svn'
,
'svn+ssh'
,
'sftp'
,
'nfs'
,
'git'
,
'git+ssh'
,
'ws'
,
'wss'
,
'itms-services'
]
uses_params
=
[
''
,
'ftp'
,
'hdl'
,
'prospero'
,
'http'
,
'imap'
,
'https'
,
'shttp'
,
'rtsp'
,
'rtsps'
,
'rtspu'
,
'sip'
,
'sips'
,
'mms'
,
'sftp'
,
'tel'
]
# These are not actually used anymore, but should stay for backwards
# compatibility. (They are undocumented, but have a public-looking name.)
non_hierarchical
=
[
'gopher'
,
'hdl'
,
'mailto'
,
'news'
,
'telnet'
,
'wais'
,
'imap'
,
'snews'
,
'sip'
,
'sips'
]
uses_query
=
[
''
,
'http'
,
'wais'
,
'imap'
,
'https'
,
'shttp'
,
'mms'
,
'gopher'
,
'rtsp'
,
'rtsps'
,
'rtspu'
,
'sip'
,
'sips'
]
uses_fragment
=
[
''
,
'ftp'
,
'hdl'
,
'http'
,
'gopher'
,
'news'
,
'nntp'
,
'wais'
,
'https'
,
'shttp'
,
'snews'
,
'file'
,
'prospero'
]
# Characters valid in scheme names
scheme_chars
=
(
'abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'0123456789'
'+-.'
)
# Leading and trailing C0 control and space to be stripped per WHATWG spec.
# == "".join([chr(i) for i in range(0, 0x20 + 1)])
_WHATWG_C0_CONTROL_OR_SPACE
=
'
\x00
\x01
\x02
\x03
\x04
\x05
\x06
\x07
\x08
\t
\n
\x0b
\x0c
\r
\x0e
\x0f
\x10
\x11
\x12
\x13
\x14
\x15
\x16
\x17
\x18
\x19
\x1a
\x1b
\x1c
\x1d
\x1e
\x1f
'
# Unsafe bytes to be removed per WHATWG spec
_UNSAFE_URL_BYTES_TO_REMOVE
=
[
'
\t
'
,
'
\r
'
,
'
\n
'
]
def
clear_cache
():
"""Clear internal performance caches. Undocumented; some tests want it."""
urlsplit
.
cache_clear
()
_byte_quoter_factory
.
cache_clear
()
# Helpers for bytes handling
# We deliberately require applications that
# handle improperly quoted URLs to do their
# own decoding and encoding.
_implicit_encoding
=
'ascii'
_implicit_errors
=
'strict'
def
_noop
(
obj
):
return
obj
def
_encode_result
(
obj
,
encoding
=
_implicit_encoding
,
errors
=
_implicit_errors
):
return
obj
.
encode
(
encoding
,
errors
)
def
_decode_args
(
args
,
encoding
=
_implicit_encoding
,
errors
=
_implicit_errors
):
return
tuple
(
x
.
decode
(
encoding
,
errors
)
if
x
else
''
if
x
is
not
None
else
None
for
x
in
args
)
def
_coerce_args
(
*
args
):
# Invokes decode if necessary to create str args
# and returns the coerced inputs along with
# an appropriate result coercion function
# - noop for str inputs
# - encoding function otherwise
str_input
=
None
for
arg
in
args
:
if
arg
:
if
str_input
is
None
:
str_input
=
isinstance
(
arg
,
str
)
else
:
if
isinstance
(
arg
,
str
)
!=
str_input
:
raise
TypeError
(
"Cannot mix str and non-str arguments"
)
if
str_input
is
None
:
for
arg
in
args
:
if
arg
is
not
None
:
str_input
=
isinstance
(
arg
,
str
)
break
if
str_input
is
not
False
:
return
args
+
(
_noop
,)
return
_decode_args
(
args
)
+
(
_encode_result
,)
# Result objects are more helpful than simple tuples
class
_ResultMixinStr
(
object
):
"""Standard approach to encoding parsed results from str to bytes"""
__slots__
=
()
def
encode
(
self
,
encoding
=
'ascii'
,
errors
=
'strict'
):
result
=
self
.
_encoded_counterpart
(
*
(
x
.
encode
(
encoding
,
errors
)
if
x
is
not
None
else
None
for
x
in
self
))
try
:
result
.
_keep_empty
=
self
.
_keep_empty
except
AttributeError
:
pass
return
result
class
_ResultMixinBytes
(
object
):
"""Standard approach to decoding parsed results from bytes to str"""
__slots__
=
()
def
decode
(
self
,
encoding
=
'ascii'
,
errors
=
'strict'
):
result
=
self
.
_decoded_counterpart
(
*
(
x
.
decode
(
encoding
,
errors
)
if
x
is
not
None
else
None
for
x
in
self
))
try
:
result
.
_keep_empty
=
self
.
_keep_empty
except
AttributeError
:
pass
return
result
class
_NetlocResultMixinBase
(
object
):
"""Shared methods for the parsed result objects containing a netloc element"""
__slots__
=
()
@
property
def
username
(
self
):
return
self
.
_userinfo
[
0
]
@
property
def
password
(
self
):
return
self
.
_userinfo
[
1
]
@
property
def
hostname
(
self
):
hostname
=
self
.
_hostinfo
[
0
]
if
not
hostname
:
return
None
# Scoped IPv6 address may have zone info, which must not be lowercased
# like http://[fe80::822a:a8ff:fe49:470c%tESt]:1234/keys
separator
=
'%'
if
isinstance
(
hostname
,
str
)
else
b'%'
hostname
,
percent
,
zone
=
hostname
.
partition
(
separator
)
return
hostname
.
lower
()
+
percent
+
zone
@
property
def
port
(
self
):
port
=
self
.
_hostinfo
[
1
]
if
port
is
not
None
:
if
port
.
isdigit
()
and
port
.
isascii
():
port
=
int
(
port
)
else
:
raise
ValueError
(
f"Port could not be cast to integer value as
{
port
!r
}
"
)
if
not
(
0
<=
port
<=
65535
):
raise
ValueError
(
"Port out of range 0-65535"
)
return
port
__class_getitem__
=
classmethod
(
types
.
GenericAlias
)
class
_NetlocResultMixinStr
(
_NetlocResultMixinBase
,
_ResultMixinStr
):
__slots__
=
()
@
property
def
_userinfo
(
self
):
netloc
=
self
.
netloc
if
netloc
is
None
:
return
None
,
None
userinfo
,
have_info
,
hostinfo
=
netloc
.
rpartition
(
'@'
)
if
have_info
:
username
,
have_password
,
password
=
userinfo
.
partition
(
':'
)
if
not
have_password
:
password
=
None
else
:
username
=
password
=
None
return
username
,
password
@
property
def
_hostinfo
(
self
):
netloc
=
self
.
netloc
if
netloc
is
None
:
return
None
,
None
_
,
_
,
hostinfo
=
netloc
.
rpartition
(
'@'
)
_
,
have_open_br
,
bracketed
=
hostinfo
.
partition
(
'['
)
if
have_open_br
:
hostname
,
_
,
port
=
bracketed
.
partition
(
']'
)
_
,
_
,
port
=
port
.
partition
(
':'
)
else
:
hostname
,
_
,
port
=
hostinfo
.
partition
(
':'
)
if
not
port
:
port
=
None
return
hostname
,
port
class
_NetlocResultMixinBytes
(
_NetlocResultMixinBase
,
_ResultMixinBytes
):
__slots__
=
()
@
property
def
_userinfo
(
self
):
netloc
=
self
.
netloc
if
netloc
is
None
:
return
None
,
None
userinfo
,
have_info
,
hostinfo
=
netloc
.
rpartition
(
b'@'
)
if
have_info
:
username
,
have_password
,
password
=
userinfo
.
partition
(
b':'
)
if
not
have_password
:
password
=
None
else
:
username
=
password
=
None
return
username
,
password
@
property
def
_hostinfo
(
self
):
netloc
=
self
.
netloc
if
netloc
is
None
:
return
None
,
None
_
,
_
,
hostinfo
=
netloc
.
rpartition
(
b'@'
)
_
,
have_open_br
,
bracketed
=
hostinfo
.
partition
(
b'['
)
if
have_open_br
:
hostname
,
_
,
port
=
bracketed
.
partition
(
b']'
)
_
,
_
,
port
=
port
.
partition
(
b':'
)
else
:
hostname
,
_
,
port
=
hostinfo
.
partition
(
b':'
)
if
not
port
:
port
=
None
return
hostname
,
port
_UNSPECIFIED
=
sentinel
(
"_UNSPECIFIED"
,
repr
=
"<not specified>"
)
_MISSING_AS_NONE_DEFAULT
=
False
class
_ResultBase
:
__slots__
=
()
def
__replace__
(
self
,
/
,
**
kwargs
):
result
=
super
().
__replace__
(
**
kwargs
)
try
:
result
.
_keep_empty
=
self
.
_keep_empty
except
AttributeError
:
pass
return
result
def
_replace
(
self
,
/
,
**
kwargs
):
result
=
super
().
_replace
(
**
kwargs
)
try
:
result
.
_keep_empty
=
self
.
_keep_empty
except
AttributeError
:
pass
return
result
def
__copy__
(
self
):
return
self
def
__deepcopy__
(
self
,
memo
):
return
self
def
__getstate__
(
self
):
state
=
super
().
__getstate__
()
try
:
if
state
[
1
][
'_keep_empty'
]
==
_MISSING_AS_NONE_DEFAULT
:
del
state
[
1
][
'_keep_empty'
]
if
state
==
(
None
, {}):
state
=
None
except
LookupError
:
pass
return
state
class
_DefragResultBase
(
_ResultBase
,
namedtuple
(
'_DefragResultBase'
,
'url fragment'
)):
__slots__
=
(
'_keep_empty'
,)
def
geturl
(
self
):
if
self
.
fragment
or
(
self
.
fragment
is
not
None
and
getattr
(
self
,
'_keep_empty'
,
_MISSING_AS_NONE_DEFAULT
)):
return
self
.
url
+
self
.
_HASH
+
self
.
fragment
else
:
return
self
.
url
class
_SplitResultBase
(
_ResultBase
,
namedtuple
(
'_SplitResultBase'
,
'scheme netloc path query fragment'
)):
__slots__
=
(
'_keep_empty'
,)
def
geturl
(
self
):
return
urlunsplit
(
self
)
class
_ParseResultBase
(
_ResultBase
,
namedtuple
(
'_ParseResultBase'
,
'scheme netloc path params query fragment'
)):
__slots__
=
(
'_keep_empty'
,)
def
geturl
(
self
):
return
urlunparse
(
self
)
_DefragResultBase
.
__doc__
=
"""
DefragResult(url, fragment)
A 2-tuple that contains the url without fragment identifier and the fragment
identifier as a separate argument.
"""
_DefragResultBase
.
url
.
__doc__
=
"""The URL with no fragment identifier."""
_DefragResultBase
.
fragment
.
__doc__
=
"""
Fragment identifier separated from URL, that allows indirect identification of a
secondary resource by reference to a primary resource and additional identifying
information.
"""
_SplitResultBase
.
__doc__
=
"""
SplitResult(scheme, netloc, path, query, fragment)
A 5-tuple that contains the different components of a URL. Similar to
ParseResult, but does not split params.
"""
_SplitResultBase
.
scheme
.
__doc__
=
"""Specifies URL scheme for the request."""
_SplitResultBase
.
netloc
.
__doc__
=
"""
Network location where the request is made to.
"""
_SplitResultBase
.
path
.
__doc__
=
"""
The hierarchical path, such as the path to a file to download.
"""
_SplitResultBase
.
query
.
__doc__
=
"""
The query component, that contains non-hierarchical data, that along with data
in path component, identifies a resource in the scope of URI's scheme and
network location.
"""
_SplitResultBase
.
fragment
.
__doc__
=
"""
Fragment identifier, that allows indirect identification of a secondary resource
by reference to a primary resource and additional identifying information.
"""
_ParseResultBase
.
__doc__
=
"""
ParseResult(scheme, netloc, path, params, query, fragment)
A 6-tuple that contains components of a parsed URL.
"""
_ParseResultBase
.
scheme
.
__doc__
=
_SplitResultBase
.
scheme
.
__doc__
_ParseResultBase
.
netloc
.
__doc__
=
_SplitResultBase
.
netloc
.
__doc__
_ParseResultBase
.
path
.
__doc__
=
_SplitResultBase
.
path
.
__doc__
_ParseResultBase
.
params
.
__doc__
=
"""
Parameters for last path element used to dereference the URI in order to provide
access to perform some operation on the resource.
"""
_ParseResultBase
.
query
.
__doc__
=
_SplitResultBase
.
query
.
__doc__
_ParseResultBase
.
fragment
.
__doc__
=
_SplitResultBase
.
fragment
.
__doc__
# For backwards compatibility, alias _NetlocResultMixinStr
# ResultBase is no longer part of the documented API, but it is
# retained since deprecating it isn't worth the hassle
ResultBase
=
_NetlocResultMixinStr
# Structured result objects for string data
class
DefragResult
(
_DefragResultBase
,
_ResultMixinStr
):
__slots__
=
()
_HASH
=
'#'
class
SplitResult
(
_SplitResultBase
,
_NetlocResultMixinStr
):
__slots__
=
()
class
ParseResult
(
_ParseResultBase
,
_NetlocResultMixinStr
):
__slots__
=
()
# Structured result objects for bytes data
class
DefragResultBytes
(
_DefragResultBase
,
_ResultMixinBytes
):
__slots__
=
()
_HASH
=
b'#'
class
SplitResultBytes
(
_SplitResultBase
,
_NetlocResultMixinBytes
):
__slots__
=
()
class
ParseResultBytes
(
_ParseResultBase
,
_NetlocResultMixinBytes
):
__slots__
=
()
# Set up the encode/decode result pairs
def
_fix_result_transcoding
():
_result_pairs
=
(
(
DefragResult
,
DefragResultBytes
),
(
SplitResult
,
SplitResultBytes
),
(
ParseResult
,
ParseResultBytes
),
)
for
_decoded
,
_encoded
in
_result_pairs
:
_decoded
.
_encoded_counterpart
=
_encoded
_encoded
.
_decoded_counterpart
=
_decoded
_fix_result_transcoding
()
del
_fix_result_transcoding
def
urlparse
(
url
,
scheme
=
None
,
allow_fragments
=
True
,
*
,
missing_as_none
=
_MISSING_AS_NONE_DEFAULT
):
"""Parse a URL into 6 components:
<scheme>://<netloc>/<path>;<params>?<query>#<fragment>
The result is a named 6-tuple with fields corresponding to the
above. It is either a ParseResult or ParseResultBytes object,
depending on the type of the url parameter.
The username, password, hostname, and port sub-components of netloc
can also be accessed as attributes of the returned object.
The scheme argument provides the default value of the scheme
component when no scheme is found in url.
If allow_fragments is False, no attempt is made to separate the
fragment component from the previous component, which can be either
path or query.
Note that % escapes are not expanded.
urlsplit() should generally be used instead of urlparse().
"""
url
,
scheme
,
_coerce_result
=
_coerce_args
(
url
,
scheme
)
if
url
is
None
:
url
=
''
scheme
,
netloc
,
url
,
params
,
query
,
fragment
=
_urlparse
(
url
,
scheme
,
allow_fragments
)
if
not
missing_as_none
:
if
scheme
is
None
:
scheme
=
''
if
netloc
is
None
:
netloc
=
''
if
params
is
None
:
params
=
''
if
query
is
None
:
query
=
''
if
fragment
is
None
:
fragment
=
''
result
=
ParseResult
(
scheme
,
netloc
,
url
,
params
,
query
,
fragment
)
result
=
_coerce_result
(
result
)
result
.
_keep_empty
=
missing_as_none
return
result
def
_urlparse
(
url
,
scheme
=
None
,
allow_fragments
=
True
):
scheme
,
netloc
,
url
,
query
,
fragment
=
_urlsplit
(
url
,
scheme
,
allow_fragments
)
if
(
scheme
or
''
)
in
uses_params
and
';'
in
url
:
url
,
params
=
_splitparams
(
url
,
missing_as_none
=
True
)
else
:
params
=
None
return
(
scheme
,
netloc
,
url
,
params
,
query
,
fragment
)
def
_splitparams
(
url
,
missing_as_none
=
False
):
if
'/'
in
url
:
i
=
url
.
find
(
';'
,
url
.
rfind
(
'/'
))
if
i
<
0
:
return
url
,
None
if
missing_as_none
else
''
else
:
i
=
url
.
find
(
';'
)
return
url
[:
i
],
url
[
i
+
1
:]
def
_splitnetloc
(
url
,
start
=
0
):
delim
=
len
(
url
)
# position of end of domain part of url, default is end
for
c
in
'/?#'
:
# look for delimiters; the order is NOT important
wdelim
=
url
.
find
(
c
,
start
)
# find first of this delim
if
wdelim
>=
0
:
# if found
delim
=
min
(
delim
,
wdelim
)
# use earliest delim position
return
url
[
start
:
delim
],
url
[
delim
:]
# return (domain, rest)
def
_checknetloc
(
netloc
):
if
not
netloc
or
netloc
.
isascii
():
return
# looking for characters like \u2100 that expand to 'a/c'
# IDNA uses NFKC equivalence, so normalize for this check
import
unicodedata
n
=
netloc
.
replace
(
'@'
,
''
)
# ignore characters already included
n
=
n
.
replace
(
':'
,
''
)
# but not the surrounding text
n
=
n
.
replace
(
'#'
,
''
)
n
=
n
.
replace
(
'?'
,
''
)
netloc2
=
unicodedata
.
normalize
(
'NFKC'
,
n
)
if
n
==
netloc2
:
return
for
c
in
'/?#@:'
:
if
c
in
netloc2
:
raise
ValueError
(
"netloc '"
+
netloc
+
"' contains invalid "
+
"characters under NFKC normalization"
)
def
_check_bracketed_netloc
(
netloc
):
# Note that this function must mirror the splitting
# done in NetlocResultMixins._hostinfo().
hostname_and_port
=
netloc
.
rpartition
(
'@'
)[
2
]
before_bracket
,
have_open_br
,
bracketed
=
hostname_and_port
.
partition
(
'['
)
if
have_open_br
:
# No data is allowed before a bracket.
if
before_bracket
:
raise
ValueError
(
"Invalid IPv6 URL"
)
hostname
,
_
,
port
=
bracketed
.
partition
(
']'
)
# No data is allowed after the bracket but before the port delimiter.
if
port
and
not
port
.
startswith
(
":"
):
raise
ValueError
(
"Invalid IPv6 URL"
)
else
:
hostname
,
_
,
port
=
hostname_and_port
.
partition
(
':'
)
_check_bracketed_host
(
hostname
)
# Valid bracketed hosts are defined in
# https://www.rfc-editor.org/rfc/rfc3986#page-49 and https://url.spec.whatwg.org/
def
_check_bracketed_host
(
hostname
):
if
hostname
.
startswith
((
'v'
,
'V'
)):
if
not
re
.
match
(
r"\A[vV][a-fA-F0-9]+\..+\z"
,
hostname
):
raise
ValueError
(
f"IPvFuture address is invalid"
)
else
:
ip
=
ipaddress
.
ip_address
(
hostname
)
# Throws Value Error if not IPv6 or IPv4
if
isinstance
(
ip
,
ipaddress
.
IPv4Address
):
raise
ValueError
(
f"An IPv4 address cannot be in brackets"
)
# typed=True avoids BytesWarnings being emitted during cache key
# comparison since this API supports both bytes and str input.
@
functools
.
lru_cache
(
typed
=
True
)
def
urlsplit
(
url
,
scheme
=
None
,
allow_fragments
=
True
,
*
,
missing_as_none
=
_MISSING_AS_NONE_DEFAULT
):
"""Parse a URL into 5 components:
<scheme>://<netloc>/<path>?<query>#<fragment>
The result is a named 5-tuple with fields corresponding to the
above. It is either a SplitResult or SplitResultBytes object,
depending on the type of the url parameter.
The username, password, hostname, and port sub-components of netloc
can also be accessed as attributes of the returned object.
The scheme argument provides the default value of the scheme
component when no scheme is found in url.
If allow_fragments is False, no attempt is made to separate the
fragment component from the previous component, which can be either
path or query.
Note that % escapes are not expanded.
"""
url
,
scheme
,
_coerce_result
=
_coerce_args
(
url
,
scheme
)
if
url
is
None
:
url
=
''
scheme
,
netloc
,
url
,
query
,
fragment
=
_urlsplit
(
url
,
scheme
,
allow_fragments
)
if
not
missing_as_none
:
if
scheme
is
None
:
scheme
=
''
if
netloc
is
None
:
netloc
=
''
if
query
is
None
:
query
=
''
if
fragment
is
None
:
fragment
=
''
result
=
SplitResult
(
scheme
,
netloc
,
url
,
query
,
fragment
)
result
=
_coerce_result
(
result
)
result
.
_keep_empty
=
missing_as_none
return
result
def
_urlsplit
(
url
,
scheme
=
None
,
allow_fragments
=
True
):
# Only lstrip url as some applications rely on preserving trailing space.
# (https://url.spec.whatwg.org/#concept-basic-url-parser would strip both)
url
=
url
.
lstrip
(
_WHATWG_C0_CONTROL_OR_SPACE
)
for
b
in
_UNSAFE_URL_BYTES_TO_REMOVE
:
url
=
url
.
replace
(
b
,
""
)
if
scheme
is
not
None
:
scheme
=
scheme
.
strip
(
_WHATWG_C0_CONTROL_OR_SPACE
)
for
b
in
_UNSAFE_URL_BYTES_TO_REMOVE
:
scheme
=
scheme
.
replace
(
b
,
""
)
allow_fragments
=
bool
(
allow_fragments
)
netloc
=
query
=
fragment
=
None
i
=
url
.
find
(
':'
)
if
i
>
0
and
url
[
0
].
isascii
()
and
url
[
0
].
isalpha
():
for
c
in
url
[:
i
]:
if
c
not
in
scheme_chars
:
break
else
:
scheme
,
url
=
url
[:
i
].
lower
(),
url
[
i
+
1
:]
if
url
[:
2
]
==
'//'
:
netloc
,
url
=
_splitnetloc
(
url
,
2
)
if
((
'['
in
netloc
and
']'
not
in
netloc
)
or
(
']'
in
netloc
and
'['
not
in
netloc
)):
raise
ValueError
(
"Invalid IPv6 URL"
)
if
'['
in
netloc
and
']'
in
netloc
:
_check_bracketed_netloc
(
netloc
)
if
allow_fragments
and
'#'
in
url
:
url
,
fragment
=
url
.
split
(
'#'
,
1
)
if
'?'
in
url
:
url
,
query
=
url
.
split
(
'?'
,
1
)
_checknetloc
(
netloc
)
return
(
scheme
,
netloc
,
url
,
query
,
fragment
)
def
urlunparse
(
components
,
*
,
keep_empty
=
_UNSPECIFIED
):
"""Put a parsed URL back together again. This may result in a
slightly different, but equivalent URL, if the URL that was parsed
originally had redundant delimiters, e.g. a ? with an empty query
(the draft states that these are equivalent) and keep_empty is false
or components is the result of the urlparse() call with
missing_as_none=False."""
scheme
,
netloc
,
url
,
params
,
query
,
fragment
,
_coerce_result
=
(
_coerce_args
(
*
components
))
if
keep_empty
is
_UNSPECIFIED
:
keep_empty
=
getattr
(
components
,
'_keep_empty'
,
_MISSING_AS_NONE_DEFAULT
)
elif
keep_empty
and
not
getattr
(
components
,
'_keep_empty'
,
True
):
raise
ValueError
(
'Cannot distinguish between empty and not defined '
'URI components in the result of parsing URL with '
'missing_as_none=False'
)
if
not
keep_empty
:
if
not
netloc
:
if
scheme
and
scheme
in
uses_netloc
and
(
not
url
or
url
[:
1
]
==
'/'
):
netloc
=
''
else
:
netloc
=
None
if
not
scheme
:
scheme
=
None
if
not
params
:
params
=
None
if
not
query
:
query
=
None
if
not
fragment
:
fragment
=
None
if
params
is
not
None
:
url
=
"%s;%s"
%
(
url
,
params
)
return
_coerce_result
(
_urlunsplit
(
scheme
,
netloc
,
url
,
query
,
fragment
))
def
urlunsplit
(
components
,
*
,
keep_empty
=
_UNSPECIFIED
):
"""Combine the elements of a tuple as returned by urlsplit() into a
complete URL as a string. The data argument can be any five-item iterable.
This may result in a slightly different, but equivalent URL, if the URL that
was parsed originally had unnecessary delimiters (for example, a ? with an
empty query; the RFC states that these are equivalent) and keep_empty
is false or components is the result of the urlsplit() call with
missing_as_none=False."""
scheme
,
netloc
,
url
,
query
,
fragment
,
_coerce_result
=
(
_coerce_args
(
*
components
))
if
keep_empty
is
_UNSPECIFIED
:
keep_empty
=
getattr
(
components
,
'_keep_empty'
,
_MISSING_AS_NONE_DEFAULT
)
elif
keep_empty
and
not
getattr
(
components
,
'_keep_empty'
,
True
):
raise
ValueError
(
'Cannot distinguish between empty and not defined '
'URI components in the result of parsing URL with '
'missing_as_none=False'
)
if
not
keep_empty
:
if
not
netloc
:
if
scheme
and
scheme
in
uses_netloc
and
(
not
url
or
url
[:
1
]
==
'/'
):
netloc
=
''
else
:
netloc
=
None
if
not
scheme
:
scheme
=
None
if
not
query
:
query
=
None
if
not
fragment
:
fragment
=
None
return
_coerce_result
(
_urlunsplit
(
scheme
,
netloc
,
url
,
query
,
fragment
))
def
_urlunsplit
(
scheme
,
netloc
,
url
,
query
,
fragment
):
if
netloc
is
not
None
:
if
url
and
url
[:
1
]
!=
'/'
:
url
=
'/'
+
url
url
=
'//'
+
netloc
+
url
elif
url
[:
2
]
==
'//'
:
url
=
'//'
+
url
if
scheme
:
url
=
scheme
+
':'
+
url
if
query
is
not
None
:
url
=
url
+
'?'
+
query
if
fragment
is
not
None
:
url
=
url
+
'#'
+
fragment
return
url
def
urljoin
(
base
,
url
,
allow_fragments
=
True
):
"""Join a base URL and a possibly relative URL to form an absolute
interpretation of the latter."""
if
not
base
:
return
url
if
not
url
:
return
base
base
,
url
,
_coerce_result
=
_coerce_args
(
base
,
url
)
bscheme
,
bnetloc
,
bpath
,
bquery
,
bfragment
=
\
_urlsplit
(
base
,
None
,
allow_fragments
)
scheme
,
netloc
,
path
,
query
,
fragment
=
\
_urlsplit
(
url
,
None
,
allow_fragments
)
if
scheme
is
None
:
scheme
=
bscheme
if
scheme
!=
bscheme
or
(
scheme
and
scheme
not
in
uses_relative
):
return
_coerce_result
(
url
)
if
not
scheme
or
scheme
in
uses_netloc
:
if
netloc
:
return
_coerce_result
(
_urlunsplit
(
scheme
,
netloc
,
path
,
query
,
fragment
))
netloc
=
bnetloc
if
not
path
:
path
=
bpath
if
query
is
None
:
query
=
bquery
if
fragment
is
None
:
fragment
=
bfragment
return
_coerce_result
(
_urlunsplit
(
scheme
,
netloc
,
path
,
query
,
fragment
))
base_parts
=
bpath
.
split
(
'/'
)
if
base_parts
[
-
1
]
!=
''
:
# the last item is not a directory, so will not be taken into account
# in resolving the relative path
del
base_parts
[
-
1
]
# for rfc3986, ignore all base path should the first character be root.
if
path
[:
1
]
==
'/'
:
segments
=
path
.
split
(
'/'
)
else
:
segments
=
base_parts
+
path
.
split
(
'/'
)
# filter out elements that would cause redundant slashes on re-joining
# the resolved_path
segments
[
1
:
-
1
]
=
filter
(
None
,
segments
[
1
:
-
1
])
resolved_path
=
[]
for
seg
in
segments
:
if
seg
==
'..'
:
try
:
resolved_path
.
pop
()
except
IndexError
:
# ignore any .. segments that would otherwise cause an IndexError
# when popped from resolved_path if resolving for rfc3986
pass
elif
seg
==
'.'
:
continue
else
:
resolved_path
.
append
(
seg
)
if
segments
[
-
1
]
in
(
'.'
,
'..'
):
# do some post-processing here. if the last segment was a relative dir,
# then we need to append the trailing '/'
resolved_path
.
append
(
''
)
return
_coerce_result
(
_urlunsplit
(
scheme
,
netloc
,
'/'
.
join
(
resolved_path
)
or
'/'
,
query
,
fragment
))
def
urldefrag
(
url
,
*
,
missing_as_none
=
_MISSING_AS_NONE_DEFAULT
):
"""Removes any existing fragment from URL.
Returns a tuple of the defragmented URL and the fragment. If
the URL contained no fragments, the second element is the
empty string or None if missing_as_none is True.
"""
url
,
_coerce_result
=
_coerce_args
(
url
)
if
'#'
in
url
:
s
,
n
,
p
,
q
,
frag
=
_urlsplit
(
url
)
defrag
=
_urlunsplit
(
s
,
n
,
p
,
q
,
None
)
else
:
frag
=
None
defrag
=
url
if
not
missing_as_none
and
frag
is
None
:
frag
=
''
result
=
_coerce_result
(
DefragResult
(
defrag
,
frag
))
result
.
_keep_empty
=
missing_as_none
return
result
_hexdig
=
'0123456789ABCDEFabcdef'
_hextobyte
=
None
def
unquote_to_bytes
(
string
):
"""unquote_to_bytes('abc%20def') -> b'abc def'."""
return
bytes
(
_unquote_impl
(
string
))
def
_unquote_impl
(
string
:
bytes
|
bytearray
|
str
)
->
bytes
|
bytearray
:
# Note: strings are encoded as UTF-8. This is only an issue if it contains
# unescaped non-ASCII characters, which URIs should not.
if
not
string
:
# Is it a string-like object?
string
.
split
return
b''
if
isinstance
(
string
,
str
):
string
=
string
.
encode
(
'utf-8'
)
bits
=
string
.
split
(
b'%'
)
if
len
(
bits
)
==
1
:
return
string
res
=
bytearray
(
bits
[
0
])
append
=
res
.
extend
# Delay the initialization of the table to not waste memory
# if the function is never called
global
_hextobyte
if
_hextobyte
is
None
:
_hextobyte
=
{(
a
+
b
).
encode
():
bytes
.
fromhex
(
a
+
b
)
for
a
in
_hexdig
for
b
in
_hexdig
}
for
item
in
bits
[
1
:]:
try
:
append
(
_hextobyte
[
item
[:
2
]])
append
(
item
[
2
:])
except
KeyError
:
append
(
b'%'
)
append
(
item
)
return
res
_asciire
=
re
.
compile
(
'([
\x00
-
\x7f
]+)'
)
def
_generate_unquoted_parts
(
string
,
encoding
,
errors
):
previous_match_end
=
0
for
ascii_match
in
_asciire
.
finditer
(
string
):
start
,
end
=
ascii_match
.
span
()
yield
string
[
previous_match_end
:
start
]
# Non-ASCII
# The ascii_match[1] group == string[start:end].
yield
_unquote_impl
(
ascii_match
[
1
]).
decode
(
encoding
,
errors
)
previous_match_end
=
end
yield
string
[
previous_match_end
:]
# Non-ASCII tail
def
unquote
(
string
,
encoding
=
'utf-8'
,
errors
=
'replace'
):
"""Replace %xx escapes by their single-character equivalent. The optional
encoding and errors parameters specify how to decode percent-encoded
sequences into Unicode characters, as accepted by the bytes.decode()
method.
By default, percent-encoded sequences are decoded with UTF-8, and invalid
sequences are replaced by a placeholder character.
unquote('abc%20def') -> 'abc def'.
"""
if
isinstance
(
string
,
bytes
):
return
_unquote_impl
(
string
).
decode
(
encoding
,
errors
)
if
'%'
not
in
string
:
# Is it a string-like object?
string
.
split
return
string
if
encoding
is
None
:
encoding
=
'utf-8'
if
errors
is
None
:
errors
=
'replace'
return
''
.
join
(
_generate_unquoted_parts
(
string
,
encoding
,
errors
))
def
parse_qs
(
qs
,
keep_blank_values
=
False
,
strict_parsing
=
False
,
encoding
=
'utf-8'
,
errors
=
'replace'
,
max_num_fields
=
None
,
separator
=
'&'
):
"""Parse a query given as a string argument.
Arguments:
qs: percent-encoded query string to be parsed
keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank strings.
A true value indicates that blanks should be retained as
blank strings. The default false value indicates that
blank values are to be ignored and treated as if they were
not included.
strict_parsing: flag indicating what to do with parsing errors.
If false (the default), errors are silently ignored.
If true, errors raise a ValueError exception.
encoding and errors: specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method.
max_num_fields: int. If set, then throws a ValueError if there
are more than n fields read by parse_qsl().
separator: str. The symbol to use for separating the query arguments.
Defaults to &.
Returns a dictionary.
"""
parsed_result
=
{}
pairs
=
parse_qsl
(
qs
,
keep_blank_values
,
strict_parsing
,
encoding
=
encoding
,
errors
=
errors
,
max_num_fields
=
max_num_fields
,
separator
=
separator
,
_stacklevel
=
2
)
for
name
,
value
in
pairs
:
if
name
in
parsed_result
:
parsed_result
[
name
].
append
(
value
)
else
:
parsed_result
[
name
]
=
[
value
]
return
parsed_result
def
parse_qsl
(
qs
,
keep_blank_values
=
False
,
strict_parsing
=
False
,
encoding
=
'utf-8'
,
errors
=
'replace'
,
max_num_fields
=
None
,
separator
=
'&'
,
*
,
_stacklevel
=
1
):
"""Parse a query given as a string argument.
Arguments:
qs: percent-encoded query string to be parsed
keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank strings.
A true value indicates that blanks should be retained as blank
strings. The default false value indicates that blank values
are to be ignored and treated as if they were not included.
strict_parsing: flag indicating what to do with parsing errors. If
false (the default), errors are silently ignored. If true,
errors raise a ValueError exception.
encoding and errors: specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method.
max_num_fields: int. If set, then throws a ValueError
if there are more than n fields read by parse_qsl().
separator: str. The symbol to use for separating the query arguments.
Defaults to &.
Returns a list, as G-d intended.
"""
if
not
separator
or
not
isinstance
(
separator
, (
str
,
bytes
)):
raise
ValueError
(
"Separator must be of type string or bytes."
)
if
isinstance
(
qs
,
str
):
if
not
isinstance
(
separator
,
str
):
separator
=
str
(
separator
,
'ascii'
)
eq
=
'='
def
_unquote
(
s
):
return
unquote_plus
(
s
,
encoding
=
encoding
,
errors
=
errors
)
elif
qs
is
None
:
return
[]
else
:
try
:
# Use memoryview() to reject integers and iterables,
# acceptable by the bytes constructor.
qs
=
bytes
(
memoryview
(
qs
))
except
TypeError
:
if
not
qs
:
warnings
.
warn
(
f"Accepting
{
type
(
qs
).
__name__
}
objects with "
f"false value in urllib.parse.parse_qsl() is "
f"deprecated as of 3.14"
,
DeprecationWarning
,
stacklevel
=
_stacklevel
+
1
)
return
[]
raise
if
isinstance
(
separator
,
str
):
separator
=
bytes
(
separator
,
'ascii'
)
eq
=
b'='
def
_unquote
(
s
):
return
unquote_to_bytes
(
s
.
replace
(
b'+'
,
b' '
))
if
not
qs
:
return
[]
# If max_num_fields is defined then check that the number of fields
# is less than max_num_fields. This prevents a memory exhaustion DOS
# attack via post bodies with many fields.
if
max_num_fields
is
not
None
:
num_fields
=
1
+
qs
.
count
(
separator
)
if
max_num_fields
<
num_fields
:
raise
ValueError
(
'Max number of fields exceeded'
)
r
=
[]
for
name_value
in
qs
.
split
(
separator
):
if
name_value
or
strict_parsing
:
name
,
has_eq
,
value
=
name_value
.
partition
(
eq
)
if
not
has_eq
and
strict_parsing
:
raise
ValueError
(
"bad query field: %r"
%
(
name_value
,))
if
value
or
keep_blank_values
:
name
=
_unquote
(
name
)
value
=
_unquote
(
value
)
r
.
append
((
name
,
value
))
return
r
def
unquote_plus
(
string
,
encoding
=
'utf-8'
,
errors
=
'replace'
):
"""Like unquote(), but also replace plus signs by spaces, as required for
unquoting HTML form values.
unquote_plus('%7e/abc+def') -> '~/abc def'
"""
string
=
string
.
replace
(
'+'
,
' '
)
return
unquote
(
string
,
encoding
,
errors
)
_ALWAYS_SAFE
=
frozenset
(
b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
b'abcdefghijklmnopqrstuvwxyz'
b'0123456789'
b'_.-~'
)
_ALWAYS_SAFE_BYTES
=
bytes
(
_ALWAYS_SAFE
)
class
_Quoter
(
dict
):
"""A mapping from bytes numbers (in range(0,256)) to strings.
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL