/
shortcuts.py
69 lines (40 loc) · 1.3 KB
/
shortcuts.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
# shortcuts.py - sqlalchemy and pandas convenience short-cut functions
import functools
import io
import operator
import warnings
import sqlalchemy as sa
from . import ENGINE
__all__ = ['count', 'select', 'text',
'pd_read_sql',
'pd_read_json_lines']
PANDAS = None
count = sa.func.count
select = functools.partial(sa.select, bind=ENGINE)
text = functools.partial(sa.text, bind=ENGINE)
def _import_pandas():
global PANDAS
try:
import pandas as PANDAS
except ImportError as e:
warnings.warn(f'failed to import pandas: {e}')
def pd_read_sql(sql=None, *args, con=ENGINE, **kwargs):
_import_pandas()
if PANDAS is None:
return None
if sql is None:
from . import queries
sql = queries.get_query(bind=con)
return PANDAS.read_sql_query(sql, *args, con=con, **kwargs)
def pd_read_json_lines(bind=ENGINE, **kwargs):
_import_pandas()
if PANDAS is None:
return None
from . import queries
with io.StringIO() as buf:
queries.write_json_lines(buf, bind=bind)
buf.seek(0)
df = PANDAS.read_json(buf, orient='record', lines=True, **kwargs)
index = df['languoid'].map(operator.itemgetter('id')).rename('id')
df.set_index(index, inplace=True, verify_integrity=True)
return df