Ticket #2093: urlpath.2.diff

File urlpath.2.diff, 2.5 KB (added by oubiwann, 9 years ago)

updated bassed on comments/suggestions so far

  • twisted/python/urlpath.py

    old new  
    77import urlparse
    88import urllib
    99
     10class URIAuthority:
     11    """
     12    An abstraction of the "authority" section of a URI.
     13
     14    Term taken from RFC2396.
     15    """
     16    def __init__(self, user=None, password=None, host=None, port=0):
     17        self.user = user
     18        self.password = password
     19        self.host = host
     20        self.port = int(port)
     21        self.auth = self.unparse()
     22
     23    def fromString(self, auth):
     24        """
     25        Return a tuple representing the parts of the authority.
     26        """
     27        self.auth = auth
     28        auths = auth.split('@')
     29        if len(auths) == 2:
     30            userpass = auths.pop(0)
     31            userpass = userpass.split(':')
     32            self.user = userpass.pop(0)
     33            try:
     34                self.password = userpass.pop(0)
     35            except IndexError:
     36                self.password = ''
     37        else:
     38            self.user = self.password = ''
     39        hostport = auths[0].split(':')
     40        self.host = hostport.pop(0) or ''
     41        try:
     42            self.port = int(hostport.pop(0))
     43        except IndexError, ValueError:
     44            self.port = None
     45        return (self.user, self.password, self.host, self.port)
     46
     47    fromString = classmethod(fromString)
     48
     49    def unparse(self):
     50        """
     51        Return a string representing the URI authority
     52        """
     53        user = self.user or ''
     54        password = host = port = ''
     55        if self.password:
     56            password = ':%s' % self.password
     57        if self.port:
     58            port = ':%s' % self.port
     59        if self.user or password:
     60            host = '@%s' % self.host
     61        else:
     62            host = self.host
     63        return '%s%s%s%s' % (user, password, host, port)
     64
     65    def __str__(self):
     66        return self.unparse()
     67
     68    def __repr__(self):
     69        return ('URIAuthority(user=%r, password=%r, host=%r, port=%r)'
     70            % (self.user, self.password, self.host, self.port))
     71           
     72
    1073class URLPath:
    1174    def __init__(self, scheme='', netloc='localhost', path='',
    1275                 query='', fragment=''):
     
    1578        self.path = path or '/'
    1679        self.query = query
    1780        self.fragment = fragment
     81        auth = URIAuthority.fromString(netloc)
     82        self.user, self.password, self.host, self.port = auth
    1883
    1984    _qpathlist = None
    2085    _uqpathlist = None