-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_connect.py
51 lines (40 loc) · 1.44 KB
/
db_connect.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
import pandas as pd
from sqlalchemy import create_engine
import configparser
def get_db_credentials(file: str = 'db_access.cfg') -> dict:
"""
This function receives a filename as a string, corresponding with
a config file with the credentials of the PADRE database.
The function looks for the file and extracts the credentials.
Returns the credentials inside a dictionary with the keys:
- user
- password
- host
- port
- db
"""
config = configparser.ConfigParser()
config.read(file)
cred_dict = {}
credentials_ = ['user', 'password', 'host', 'port', 'db']
for cred in credentials_:
val = config.get('credentials', cred)
cred_dict[cred] = val
return cred_dict
def extraction_query(query_: str, credentials_: dict) -> pd.DataFrame:
"""
This function receives an SQL query as a string and the database
credentials stored in a dictionary.
The query must be written, so it returns a table, which will be
returned by the function as a Pandas DataFrame.
"""
user = credentials_['user']
password = credentials_['password']
host = credentials_['host']
port = credentials_['port']
db = credentials_['db']
engine = f'mysql+pymysql://{user}:{password}@{host}:{port}/{db}'
sqlengine = create_engine(engine)
with sqlengine.connect() as dbConnection:
applications_ = pd.read_sql(query_, dbConnection)
return applications_