-
Notifications
You must be signed in to change notification settings - Fork 157
/
Copy pathfurl.py
1895 lines (1540 loc) Β· 62.3 KB
/
furl.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
# -*- coding: utf-8 -*-
#
# furl - URL manipulation made simple.
#
# Ansgar Grunseid
# grunseid.com
# grunseid@gmail.com
#
# License: Build Amazing Things (Unlicense)
#
import re
import abc
import warnings
from copy import deepcopy
from posixpath import normpath
import six
from six.moves import urllib
from six.moves.urllib.parse import quote, unquote
try:
from icecream import ic
except ImportError: # Graceful fallback if IceCream isn't installed.
ic = lambda *a: None if not a else (a[0] if len(a) == 1 else a) # noqa
from .omdict1D import omdict1D
from .compat import string_types, UnicodeMixin
from .common import (
callable_attr, is_iterable_but_not_string, absent as _absent)
# Map of common protocols, as suggested by the common protocols included in
# urllib/parse.py, to their default ports. Protocol scheme strings are
# lowercase.
#
# TODO(Ans): Is there a public map of schemes to their default ports? If not,
# create one? Best I (Ansgar) could find is
#
# https://gist.github.com/mahmoud/2fe281a8daaff26cfe9c15d2c5bf5c8b
#
DEFAULT_PORTS = {
'acap': 674,
'afp': 548,
'dict': 2628,
'dns': 53,
'ftp': 21,
'git': 9418,
'gopher': 70,
'hdl': 2641,
'http': 80,
'https': 443,
'imap': 143,
'ipp': 631,
'ipps': 631,
'irc': 194,
'ircs': 6697,
'ldap': 389,
'ldaps': 636,
'mms': 1755,
'msrp': 2855,
'mtqp': 1038,
'nfs': 111,
'nntp': 119,
'nntps': 563,
'pop': 110,
'prospero': 1525,
'redis': 6379,
'rsync': 873,
'rtsp': 554,
'rtsps': 322,
'rtspu': 5005,
'sftp': 22,
'sip': 5060,
'sips': 5061,
'smb': 445,
'snews': 563,
'snmp': 161,
'ssh': 22,
'svn': 3690,
'telnet': 23,
'tftp': 69,
'ventrilo': 3784,
'vnc': 5900,
'wais': 210,
'ws': 80,
'wss': 443,
'xmpp': 5222,
}
def lget(lst, index, default=None):
try:
return lst[index]
except IndexError:
return default
def attemptstr(o):
try:
return str(o)
except Exception:
return o
def utf8(o, default=_absent):
try:
return o.encode('utf8')
except Exception:
return o if default is _absent else default
def non_string_iterable(o):
return callable_attr(o, '__iter__') and not isinstance(o, string_types)
# TODO(grun): Support IDNA2008 via the third party idna module. See
# https://github.com/gruns/furl/issues/73#issuecomment-226549755.
def idna_encode(o):
if callable_attr(o, 'encode'):
return str(o.encode('idna').decode('utf8'))
return o
def idna_decode(o):
if callable_attr(utf8(o), 'decode'):
return utf8(o).decode('idna')
return o
def is_valid_port(port):
port = str(port)
if not port.isdigit() or not 0 < int(port) <= 65535:
return False
return True
def static_vars(**kwargs):
def decorator(func):
for key, value in six.iteritems(kwargs):
setattr(func, key, value)
return func
return decorator
def create_quote_fn(safe_charset, quote_plus):
def quote_fn(s, dont_quote):
if dont_quote is True:
safe = safe_charset
elif dont_quote is False:
safe = ''
else: # <dont_quote> is expected to be a string.
safe = dont_quote
# Prune duplicates and characters not in <safe_charset>.
safe = ''.join(set(safe) & set(safe_charset)) # E.g. '?^#?' -> '?'.
quoted = quote(s, safe)
if quote_plus:
quoted = quoted.replace('%20', '+')
return quoted
return quote_fn
#
# TODO(grun): Update some of the regex functions below to reflect the fact that
# the valid encoding of Path segments differs slightly from the valid encoding
# of Fragment Path segments. Similarly, the valid encodings of Query keys and
# values differ slightly from the valid encodings of Fragment Query keys and
# values.
#
# For example, '?' and '#' don't need to be encoded in Fragment Path segments
# but they must be encoded in Path segments. Similarly, '#' doesn't need to be
# encoded in Fragment Query keys and values, but must be encoded in Query keys
# and values.
#
# Perhaps merge them with URLPath, FragmentPath, URLQuery, and
# FragmentQuery when those new classes are created (see the TODO
# currently at the top of the source, 02/03/2012).
#
# RFC 3986 (https://www.ietf.org/rfc/rfc3986.txt)
#
# unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
#
# pct-encoded = "%" HEXDIG HEXDIG
#
# sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
# / "*" / "+" / "," / ";" / "="
#
# pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
#
# === Path ===
# segment = *pchar
#
# === Query ===
# query = *( pchar / "/" / "?" )
#
# === Scheme ===
# scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
#
PERCENT_REGEX = r'\%[a-fA-F\d][a-fA-F\d]'
INVALID_HOST_CHARS = '!@#$%^&\'\"*()+=:;/'
@static_vars(regex=re.compile(
r'^([\w%s]|(%s))*$' % (re.escape('-.~:@!$&\'()*+,;='), PERCENT_REGEX)))
def is_valid_encoded_path_segment(segment):
return is_valid_encoded_path_segment.regex.match(segment) is not None
@static_vars(regex=re.compile(
r'^([\w%s]|(%s))*$' % (re.escape('-.~:@!$&\'()*+,;/?'), PERCENT_REGEX)))
def is_valid_encoded_query_key(key):
return is_valid_encoded_query_key.regex.match(key) is not None
@static_vars(regex=re.compile(
r'^([\w%s]|(%s))*$' % (re.escape('-.~:@!$&\'()*+,;/?='), PERCENT_REGEX)))
def is_valid_encoded_query_value(value):
return is_valid_encoded_query_value.regex.match(value) is not None
@static_vars(regex=re.compile(r'[a-zA-Z][a-zA-Z\-\.\+]*'))
def is_valid_scheme(scheme):
return is_valid_scheme.regex.match(scheme) is not None
@static_vars(regex=re.compile('[%s]' % re.escape(INVALID_HOST_CHARS)))
def is_valid_host(hostname):
toks = hostname.split('.')
if toks[-1] == '': # Trailing '.' in a fully qualified domain name.
toks.pop()
for tok in toks:
if is_valid_host.regex.search(tok) is not None:
return False
return '' not in toks # Adjacent periods aren't allowed.
def get_scheme(url):
if url.startswith(':'):
return ''
# Avoid incorrect scheme extraction with url.find(':') when other URL
# components, like the path, query, fragment, etc, may have a colon in
# them. For example, the URL 'a?query:', whose query has a ':' in it.
no_fragment = url.split('#', 1)[0]
no_query = no_fragment.split('?', 1)[0]
no_path_or_netloc = no_query.split('/', 1)[0]
scheme = url[:max(0, no_path_or_netloc.find(':'))] or None
if scheme is not None and not is_valid_scheme(scheme):
return None
return scheme
def strip_scheme(url):
scheme = get_scheme(url) or ''
url = url[len(scheme):]
if url.startswith(':'):
url = url[1:]
return url
def set_scheme(url, scheme):
after_scheme = strip_scheme(url)
if scheme is None:
return after_scheme
else:
return '%s:%s' % (scheme, after_scheme)
# 'netloc' in Python parlance, 'authority' in RFC 3986 parlance.
def has_netloc(url):
scheme = get_scheme(url)
return url.startswith('//' if scheme is None else scheme + '://')
def urlsplit(url):
"""
Parameters:
url: URL string to split.
Returns: urlparse.SplitResult tuple subclass, just like
urlparse.urlsplit() returns, with fields (scheme, netloc, path,
query, fragment, username, password, hostname, port). See
http://docs.python.org/library/urlparse.html#urlparse.urlsplit
for more details on urlsplit().
"""
original_scheme = get_scheme(url)
# urlsplit() parses URLs differently depending on whether or not the URL's
# scheme is in any of
#
# urllib.parse.uses_fragment
# urllib.parse.uses_netloc
# urllib.parse.uses_params
# urllib.parse.uses_query
# urllib.parse.uses_relative
#
# For consistent URL parsing, switch the URL's scheme to 'http', a scheme
# in all of the aforementioned uses_* lists, and afterwards revert to the
# original scheme (which may or may not be in some, or all, of the the
# uses_* lists).
if original_scheme is not None:
url = set_scheme(url, 'http')
scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url)
# Detect and preserve the '//' before the netloc, if present. E.g. preserve
# URLs like 'http:', 'http://', and '///sup' correctly.
after_scheme = strip_scheme(url)
if after_scheme.startswith('//'):
netloc = netloc or ''
else:
netloc = None
scheme = original_scheme
return urllib.parse.SplitResult(scheme, netloc, path, query, fragment)
def urljoin(base, url):
"""
Parameters:
base: Base URL to join with <url>.
url: Relative or absolute URL to join with <base>.
Returns: The resultant URL from joining <base> and <url>.
"""
base_scheme = get_scheme(base) if has_netloc(base) else None
url_scheme = get_scheme(url) if has_netloc(url) else None
if base_scheme is not None:
# For consistent URL joining, switch the base URL's scheme to
# 'http'. urllib.parse.urljoin() behaves differently depending on the
# scheme. E.g.
#
# >>> urllib.parse.urljoin('http://google.com/', 'hi')
# 'http://google.com/hi'
#
# vs
#
# >>> urllib.parse.urljoin('asdf://google.com/', 'hi')
# 'hi'
root = set_scheme(base, 'http')
else:
root = base
joined = urllib.parse.urljoin(root, url)
new_scheme = url_scheme if url_scheme is not None else base_scheme
if new_scheme is not None and has_netloc(joined):
joined = set_scheme(joined, new_scheme)
return joined
def join_path_segments(*args):
"""
Join multiple lists of path segments together, intelligently
handling path segments borders to preserve intended slashes of the
final constructed path.
This function is not encoding aware. It doesn't test for, or change,
the encoding of path segments it is passed.
Examples:
join_path_segments(['a'], ['b']) == ['a','b']
join_path_segments(['a',''], ['b']) == ['a','b']
join_path_segments(['a'], ['','b']) == ['a','b']
join_path_segments(['a',''], ['','b']) == ['a','','b']
join_path_segments(['a','b'], ['c','d']) == ['a','b','c','d']
Returns: A list containing the joined path segments.
"""
finals = []
for segments in args:
if not segments or segments == ['']:
continue
elif not finals:
finals.extend(segments)
else:
# Example #1: ['a',''] + ['b'] == ['a','b']
# Example #2: ['a',''] + ['','b'] == ['a','','b']
if finals[-1] == '' and (segments[0] != '' or len(segments) > 1):
finals.pop(-1)
# Example: ['a'] + ['','b'] == ['a','b']
elif finals[-1] != '' and segments[0] == '' and len(segments) > 1:
segments = segments[1:]
finals.extend(segments)
return finals
def remove_path_segments(segments, remove):
"""
Removes the path segments of <remove> from the end of the path
segments <segments>.
Examples:
# ('/a/b/c', 'b/c') -> '/a/'
remove_path_segments(['','a','b','c'], ['b','c']) == ['','a','']
# ('/a/b/c', '/b/c') -> '/a'
remove_path_segments(['','a','b','c'], ['','b','c']) == ['','a']
Returns: The list of all remaining path segments after the segments
in <remove> have been removed from the end of <segments>. If no
segments from <remove> were removed from <segments>, <segments> is
returned unmodified.
"""
# [''] means a '/', which is properly represented by ['', ''].
if segments == ['']:
segments.append('')
if remove == ['']:
remove.append('')
ret = None
if remove == segments:
ret = []
elif len(remove) > len(segments):
ret = segments
else:
toremove = list(remove)
if len(remove) > 1 and remove[0] == '':
toremove.pop(0)
if toremove and toremove == segments[-1 * len(toremove):]:
ret = segments[:len(segments) - len(toremove)]
if remove[0] != '' and ret:
ret.append('')
else:
ret = segments
return ret
def quacks_like_a_path_with_segments(obj):
return (
hasattr(obj, 'segments') and
is_iterable_but_not_string(obj.segments))
class Path(object):
"""
Represents a path comprised of zero or more path segments.
http://tools.ietf.org/html/rfc3986#section-3.3
Path parameters aren't supported.
Attributes:
_force_absolute: Function whos boolean return value specifies
whether self.isabsolute should be forced to True or not. If
_force_absolute(self) returns True, isabsolute is read only and
raises an AttributeError if assigned to. If
_force_absolute(self) returns False, isabsolute is mutable and
can be set to True or False. URL paths use _force_absolute and
return True if the netloc is non-empty (not equal to
''). Fragment paths are never read-only and their
_force_absolute(self) always returns False.
segments: List of zero or more path segments comprising this
path. If the path string has a trailing '/', the last segment
will be '' and self.isdir will be True and self.isfile will be
False. An empty segment list represents an empty path, not '/'
(though they have the same meaning).
isabsolute: Boolean whether or not this is an absolute path or
not. An absolute path starts with a '/'. self.isabsolute is
False if the path is empty (self.segments == [] and str(path) ==
'').
strict: Boolean whether or not UserWarnings should be raised if
improperly encoded path strings are provided to methods that
take such strings, like load(), add(), set(), remove(), etc.
"""
# From RFC 3986:
# segment = *pchar
# pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
# unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
# sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
# / "*" / "+" / "," / ";" / "="
SAFE_SEGMENT_CHARS = ":@-._~!$&'()*+,;="
def __init__(self, path='', force_absolute=lambda _: False, strict=False):
self.segments = []
self.strict = strict
self._isabsolute = False
self._force_absolute = force_absolute
self.load(path)
def load(self, path):
"""
Load <path>, replacing any existing path. <path> can either be
a Path instance, a list of segments, a path string to adopt.
Returns: <self>.
"""
if not path:
segments = []
elif quacks_like_a_path_with_segments(path): # Path interface.
segments = path.segments
elif is_iterable_but_not_string(path): # List interface.
segments = path
else: # String interface.
segments = self._segments_from_path(path)
if self._force_absolute(self):
self._isabsolute = True if segments else False
else:
self._isabsolute = (segments and segments[0] == '')
if self.isabsolute and len(segments) > 1 and segments[0] == '':
segments.pop(0)
self.segments = segments
return self
def add(self, path):
"""
Add <path> to the existing path. <path> can either be a Path instance,
a list of segments, or a path string to append to the existing path.
Returns: <self>.
"""
if quacks_like_a_path_with_segments(path): # Path interface.
newsegments = path.segments
elif is_iterable_but_not_string(path): # List interface.
newsegments = path
else: # String interface.
newsegments = self._segments_from_path(path)
# Preserve the opening '/' if one exists already (self.segments
# == ['']).
if self.segments == [''] and newsegments and newsegments[0] != '':
newsegments.insert(0, '')
segments = self.segments
if self.isabsolute and self.segments and self.segments[0] != '':
segments.insert(0, '')
self.load(join_path_segments(segments, newsegments))
return self
def set(self, path):
self.load(path)
return self
def remove(self, path):
if path is True:
self.load('')
else:
if is_iterable_but_not_string(path): # List interface.
segments = path
else: # String interface.
segments = self._segments_from_path(path)
base = ([''] if self.isabsolute else []) + self.segments
self.load(remove_path_segments(base, segments))
return self
def normalize(self):
"""
Normalize the path. Turn '//a/./b/../c//' into '/a/c/'.
Returns: <self>.
"""
if str(self):
normalized = normpath(str(self)) + ('/' * self.isdir)
if normalized.startswith('//'): # http://bugs.python.org/636648
normalized = '/' + normalized.lstrip('/')
self.load(normalized)
return self
def asdict(self):
return {
'encoded': str(self),
'isdir': self.isdir,
'isfile': self.isfile,
'segments': self.segments,
'isabsolute': self.isabsolute,
}
@property
def isabsolute(self):
if self._force_absolute(self):
return True
return self._isabsolute
@isabsolute.setter
def isabsolute(self, isabsolute):
"""
Raises: AttributeError if _force_absolute(self) returns True.
"""
if self._force_absolute(self):
s = ('Path.isabsolute is True and read-only for URLs with a netloc'
' (a username, password, host, and/or port). A URL path must '
"start with a '/' to separate itself from a netloc.")
raise AttributeError(s)
self._isabsolute = isabsolute
@property
def isdir(self):
"""
Returns: True if the path ends on a directory, False
otherwise. If True, the last segment is '', representing the
trailing '/' of the path.
"""
return (self.segments == [] or
(self.segments and self.segments[-1] == ''))
@property
def isfile(self):
"""
Returns: True if the path ends on a file, False otherwise. If
True, the last segment is not '', representing some file as the
last segment of the path.
"""
return not self.isdir
def __truediv__(self, path):
copy = deepcopy(self)
return copy.add(path)
def __eq__(self, other):
return str(self) == str(other)
def __ne__(self, other):
return not self == other
def __bool__(self):
return len(self.segments) > 0
__nonzero__ = __bool__
def __str__(self):
segments = list(self.segments)
if self.isabsolute:
if not segments:
segments = ['', '']
else:
segments.insert(0, '')
return self._path_from_segments(segments)
def __repr__(self):
return "%s('%s')" % (self.__class__.__name__, str(self))
def _segments_from_path(self, path):
"""
Returns: The list of path segments from the path string <path>.
Raises: UserWarning if <path> is an improperly encoded path
string and self.strict is True.
TODO(grun): Accept both list values and string values and
refactor the list vs string interface testing to this common
method.
"""
segments = []
for segment in path.split('/'):
if not is_valid_encoded_path_segment(segment):
segment = quote(utf8(segment))
if self.strict:
s = ("Improperly encoded path string received: '%s'. "
"Proceeding, but did you mean '%s'?" %
(path, self._path_from_segments(segments)))
warnings.warn(s, UserWarning)
segments.append(utf8(segment))
del segment
# In Python 3, utf8() returns Bytes objects that must be decoded into
# strings before they can be passed to unquote(). In Python 2, utf8()
# returns strings that can be passed directly to urllib.unquote().
segments = [
segment.decode('utf8')
if isinstance(segment, bytes) and not isinstance(segment, str)
else segment for segment in segments]
return [unquote(segment) for segment in segments]
def _path_from_segments(self, segments):
"""
Combine the provided path segments <segments> into a path string. Path
segments in <segments> will be quoted.
Returns: A path string with quoted path segments.
"""
segments = [
quote(utf8(attemptstr(segment)), self.SAFE_SEGMENT_CHARS)
for segment in segments]
return '/'.join(segments)
@six.add_metaclass(abc.ABCMeta)
class PathCompositionInterface(object):
"""
Abstract class interface for a parent class that contains a Path.
"""
def __init__(self, strict=False):
"""
Params:
force_absolute: See Path._force_absolute.
Assignments to <self> in __init__() must be added to
__setattr__() below.
"""
self._path = Path(force_absolute=self._force_absolute, strict=strict)
@property
def path(self):
return self._path
@property
def pathstr(self):
"""This method is deprecated. Use str(furl.path) instead."""
s = ('furl.pathstr is deprecated. Use str(furl.path) instead. There '
'should be one, and preferably only one, obvious way to serialize'
' a Path object to a string.')
warnings.warn(s, DeprecationWarning)
return str(self._path)
@abc.abstractmethod
def _force_absolute(self, path):
"""
Subclass me.
"""
pass
def __setattr__(self, attr, value):
"""
Returns: True if this attribute is handled and set here, False
otherwise.
"""
if attr == '_path':
self.__dict__[attr] = value
return True
elif attr == 'path':
self._path.load(value)
return True
return False
@six.add_metaclass(abc.ABCMeta)
class URLPathCompositionInterface(PathCompositionInterface):
"""
Abstract class interface for a parent class that contains a URL
Path.
A URL path's isabsolute attribute is absolute and read-only if a
netloc is defined. A path cannot start without '/' if there's a
netloc. For example, the URL 'http://google.coma/path' makes no
sense. It should be 'http://google.com/a/path'.
A URL path's isabsolute attribute is mutable if there's no
netloc. The scheme doesn't matter. For example, the isabsolute
attribute of the URL path in 'mailto:user@host.com', with scheme
'mailto' and path 'user@host.com', is mutable because there is no
netloc. See
http://en.wikipedia.org/wiki/URI_scheme#Examples
"""
def __init__(self, strict=False):
PathCompositionInterface.__init__(self, strict=strict)
def _force_absolute(self, path):
return bool(path) and self.netloc
@six.add_metaclass(abc.ABCMeta)
class FragmentPathCompositionInterface(PathCompositionInterface):
"""
Abstract class interface for a parent class that contains a Fragment
Path.
Fragment Paths they be set to absolute (self.isabsolute = True) or
not absolute (self.isabsolute = False).
"""
def __init__(self, strict=False):
PathCompositionInterface.__init__(self, strict=strict)
def _force_absolute(self, path):
return False
class Query(object):
"""
Represents a URL query comprised of zero or more unique parameters
and their respective values.
http://tools.ietf.org/html/rfc3986#section-3.4
All interaction with Query.params is done with unquoted strings. So
f.query.params['a'] = 'a%5E'
means the intended value for 'a' is 'a%5E', not 'a^'.
Query.params is implemented as an omdict1D object - a one
dimensional ordered multivalue dictionary. This provides support for
repeated URL parameters, like 'a=1&a=2'. omdict1D is a subclass of
omdict, an ordered multivalue dictionary. Documentation for omdict
can be found here
https://github.com/gruns/orderedmultidict
The one dimensional aspect of omdict1D means that a list of values
is interpreted as multiple values, not a single value which is
itself a list of values. This is a reasonable distinction to make
because URL query parameters are one dimensional: query parameter
values cannot themselves be composed of sub-values.
So what does this mean? This means we can safely interpret
f = furl('http://www.google.com')
f.query.params['arg'] = ['one', 'two', 'three']
as three different values for 'arg': 'one', 'two', and 'three',
instead of a single value which is itself some serialization of the
python list ['one', 'two', 'three']. Thus, the result of the above
will be
f.query.allitems() == [
('arg','one'), ('arg','two'), ('arg','three')]
and not
f.query.allitems() == [('arg', ['one', 'two', 'three'])]
The latter doesn't make sense because query parameter values cannot
be composed of sub-values. So finally
str(f.query) == 'arg=one&arg=two&arg=three'
Additionally, while the set of allowed characters in URL queries is
defined in RFC 3986 section 3.4, the format for encoding key=value
pairs within the query is not. In turn, the parsing of encoded
key=value query pairs differs between implementations.
As a compromise to support equal signs in both key=value pair
encoded queries, like
https://www.google.com?a=1&b=2
and non-key=value pair encoded queries, like
https://www.google.com?===3===
equal signs are percent encoded in key=value pairs where the key is
non-empty, e.g.
https://www.google.com?equal-sign=%3D
but not encoded in key=value pairs where the key is empty, e.g.
https://www.google.com?===equal=sign===
This presents a reasonable compromise to accurately reproduce
non-key=value queries with equal signs while also still percent
encoding equal signs in key=value pair encoded queries, as
expected. See
https://github.com/gruns/furl/issues/99
for more details.
Attributes:
params: Ordered multivalue dictionary of query parameter key:value
pairs. Parameters in self.params are maintained URL decoded,
e.g. 'a b' not 'a+b'.
strict: Boolean whether or not UserWarnings should be raised if
improperly encoded query strings are provided to methods that
take such strings, like load(), add(), set(), remove(), etc.
"""
# From RFC 3986:
# query = *( pchar / "/" / "?" )
# pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
# unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
# sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
# / "*" / "+" / "," / ";" / "="
SAFE_KEY_CHARS = "/?:@-._~!$'()*+,;"
SAFE_VALUE_CHARS = SAFE_KEY_CHARS + '='
def __init__(self, query='', strict=False):
self.strict = strict
self._params = omdict1D()
self.load(query)
def load(self, query):
items = self._items(query)
self.params.load(items)
return self
def add(self, args):
for param, value in self._items(args):
self.params.add(param, value)
return self
def set(self, mapping):
"""
Adopt all mappings in <mapping>, replacing any existing mappings
with the same key. If a key has multiple values in <mapping>,
they are all adopted.
Examples:
Query({1:1}).set([(1,None),(2,2)]).params.allitems()
== [(1,None),(2,2)]
Query({1:None,2:None}).set([(1,1),(2,2),(1,11)]).params.allitems()
== [(1,1),(2,2),(1,11)]
Query({1:None}).set([(1,[1,11,111])]).params.allitems()
== [(1,1),(1,11),(1,111)]
Returns: <self>.
"""
self.params.updateall(mapping)
return self
def remove(self, query):
if query is True:
self.load('')
return self
# Single key to remove.
items = [query]
# Dictionary or multivalue dictionary of items to remove.
if callable_attr(query, 'items'):
items = self._items(query)
# List of keys or items to remove.
elif non_string_iterable(query):
items = query
for item in items:
if non_string_iterable(item) and len(item) == 2:
key, value = item
self.params.popvalue(key, value, None)
else:
key = item
self.params.pop(key, None)
return self
@property
def params(self):
return self._params
@params.setter
def params(self, params):
items = self._items(params)
self._params.clear()
for key, value in items:
self._params.add(key, value)
def encode(self, delimiter='&', quote_plus=True, dont_quote='',
delimeter=_absent):
"""
Examples:
Query('a=a&b=#').encode() == 'a=a&b=%23'
Query('a=a&b=#').encode(';') == 'a=a;b=%23'
Query('a+b=c@d').encode(dont_quote='@') == 'a+b=c@d'
Query('a+b=c@d').encode(quote_plus=False) == 'a%20b=c%40d'
Until furl v0.4.6, the 'delimiter' argument was incorrectly
spelled 'delimeter'. For backwards compatibility, accept both
the correct 'delimiter' and the old, misspelled 'delimeter'.
Keys and values are encoded application/x-www-form-urlencoded if
<quote_plus> is True, percent-encoded otherwise.
<dont_quote> exempts valid query characters from being
percent-encoded, either in their entirety with dont_quote=True,
or selectively with dont_quote=<string>, like
dont_quote='/?@_'. Invalid query characters -- those not in
self.SAFE_KEY_CHARS, like '#' and '^' -- are always encoded,
even if included in <dont_quote>. For example:
Query('#=^').encode(dont_quote='#^') == '%23=%5E'.