class DbUrl(object):
def __init__(self, db_url):
split = urlparse.urlparse(db_url)
self.scheme = split.scheme
self.hostname = split.hostname
self.port = split.port
self.username = split.username
self.password = split.password
self.database = split.path.lstrip('/')
def __str__(self):
auth = ":".join(filter(None, (self.username, self.password)))
address = ":".join(filter(None, (self.hostname, str(self.port))))
netloc = "@".join(filter(None, (auth, address)))
return urlparse.urlunparse((self.scheme, netloc, self.database, '', '', ''))
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, ', '.join(
'%s=%r' % (attr_name, attr_value)
for attr_name, attr_value in self.__dict__.iteritems()))
def replace(self, **kwargs):
db_url = copy.copy(self)
for attr_name, attr_value in kwargs.iteritems():
assert attr_name in db_url.__dict__, 'Unknown attribute'
setattr(db_url, attr_name, attr_value)
return db_url
和用法:
>>> DbUrl('postgresql://username:password@127.0.0.1:5433/postgres').replace(password='****')
DbUrl(username='username', password='****', hostname='127.0.0.1', database='postgres', scheme='postgresql', port=5433)
>>> str(DbUrl('postgresql://username:password@127.0.0.1:5433/postgres').replace(password='****'))
'postgresql://username:****@127.0.0.1:5433/postgres'
>>> str(DbUrl('postgresql://username:password@127.0.0.1:5433/postgres').replace(password=None))
'postgresql://username@127.0.0.1:5433/postgres'
>>>