Created
November 7, 2014 16:27
-
-
Save wenshin/d62da6efafa727ffbf3e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def gen_user_psw(auth): | |
| from urllib import quote | |
| returned = '' | |
| if auth: | |
| # urllib.quote 转义 @:/ 等特殊字符 | |
| # 第二个参数表示转义任何字符,默认会不转义 / 字符 | |
| user = quote(auth['username'], '') | |
| psw = quote(auth['password'], '') | |
| returned = '%s:%s@' % (user, psw) | |
| return returned | |
| def gen_mongo_uri(auth, host_list, db_name=None, options=None): | |
| ''' | |
| :param options: this is a dict of params, will encoded by urlib.urlencode | |
| Learn Mongo URI options see | |
| 'http://docs.mongodb.org/manual/reference/connection-string | |
| /#connection-string-options' | |
| ''' | |
| if host_list and not (isinstance(host_list, list) or isinstance(host_list, tuple)): | |
| raise TypeError('host_list must be a dict or tuple. [%s]' % host_list) | |
| if options and not isinstance(options, dict): | |
| raise TypeError('options must be a dict. [%s]' % options) | |
| usr_psw = gen_user_psw(auth) | |
| # 默认连接127.0.0.1:27017 | |
| host_list = ','.join(host_list) if host_list else '127.0.0.1' | |
| # 如果 db_name 不存在且 options 存在的话,需要在host_list后面加一个 / | |
| host_list = host_list + '/' if not db_name and options else host_list | |
| from urllib import urlencode | |
| db_name = '/' + db_name if db_name else '' | |
| options = '?' + urlencode(options) if options else '' | |
| return 'mongodb://{0}{1}{2}{3}'.format( | |
| usr_psw, host_list, db_name, options) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment