函數一個用法
阿新 • • 發佈:2019-01-12
date interact HERE exist base **kwargs handle rip mysq
‘‘‘
handle all the database interactions
‘‘‘
import json, time, os
from conf import settings
def file_db_handle(conn_params):
‘‘‘
parse the db file path
:param conn_params: the db connection params set in settings
:return:
‘‘‘
print(‘file db:‘, conn_params)
# db_path =‘%s/%s‘ %(conn_params[‘path‘],conn_params[‘name‘])
return file_execute #3返回給外部程序,一個函數名。外部程序就可以進行調用,這個函數
def db_handler(): #1外部程序最先調用這個
‘‘‘
connect to db
:param conn_parms: the db connection params set in settings
:return:a
‘‘‘
conn_params = settings.DATABASE
if conn_params[‘engine‘] == ‘file_storage‘:
return file_db_handle(conn_params) #2返回值是另一個函數的執行結果
elif conn_params[‘engine‘] == ‘mysql‘:
pass # todo
def file_execute(sql, **kwargs):
"""
對sql語句進行解析並執行
:param sql: eg. select * from accounts where account=1344
:param kwargs:
:return:
"""
conn_params = settings.DATABASE
db_path = ‘%s/%s‘ % (conn_params[‘path‘], conn_params[‘name‘])
print(sql, db_path)
sql_list = sql.split("where")
print(sql_list)
if sql_list[0].startswith("select") and len(sql_list) > 1: # has where clause
column, val = sql_list[1].strip().split("=")
if column == ‘account‘:
account_file = "%s/%s.json" % (db_path, val)
print(account_file)
if os.path.isfile(account_file):
with open(account_file, ‘r‘) as f:
account_data = json.load(f)
return account_data
else:
exit("\033[31;1mAccount [%s] does not exist!\033[0m" % val)
elif sql_list[0].startswith("update") and len(sql_list) > 1: # has where clause
column, val = sql_list[1].strip().split("=")
if column == ‘account‘:
account_file = "%s/%s.json" % (db_path, val)
# print(account_file)
if os.path.isfile(account_file):
account_data = kwargs.get("account_data")
with open(account_file, ‘w‘) as f:
acc_data = json.dump(account_data, f)
return True
函數一個用法