forked from coleifer/peewee
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_url.py
69 lines (59 loc) · 2.03 KB
/
db_url.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
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
from peewee import *
from playhouse.sqlite_ext import SqliteExtDatabase
try:
from playhouse.apsw_ext import APSWDatabase
except ImportError:
APSWDatabase = None
try:
from playhouse.berkeleydb import BerkeleyDatabase
except ImportError:
BerkeleyDatabase = None
try:
from playhouse.postgres_ext import PostgresqlExtDatabase
except ImportError:
PostgresqlExtDatabase = None
schemes = {
'apsw': APSWDatabase,
'berkeleydb': BerkeleyDatabase,
'mysql': MySQLDatabase,
'postgres': PostgresqlDatabase,
'postgresql': PostgresqlDatabase,
'postgresext': PostgresqlExtDatabase,
'postgresqlext': PostgresqlExtDatabase,
'sqlite': SqliteDatabase,
'sqliteext': SqliteExtDatabase,
}
def parseresult_to_dict(parsed):
connect_kwargs = {'database': parsed.path[1:]}
if parsed.username:
connect_kwargs['user'] = parsed.username
if parsed.password:
connect_kwargs['password'] = parsed.password
if parsed.hostname:
connect_kwargs['host'] = parsed.hostname
if parsed.port:
connect_kwargs['port'] = parsed.port
# Adjust parameters for MySQL.
if parsed.scheme == 'mysql' and 'password' in connect_kwargs:
connect_kwargs['passwd'] = connect_kwargs.pop('password')
return connect_kwargs
def parse(url):
parsed = urlparse(url)
return parseresult_to_dict(parsed)
def connect(url, **connect_params):
parsed = urlparse(url)
connect_kwargs = parseresult_to_dict(parsed)
connect_kwargs.update(connect_params)
database_class = schemes.get(parsed.scheme)
if database_class is None:
if database_class in schemes:
raise RuntimeError('Attempted to use "%s" but a required library '
'could not be imported.' % parsed.scheme)
else:
raise RuntimeError('Unrecognized or unsupported scheme: "%s".' %
parsed.scheme)
return database_class(**connect_kwargs)