コード例 #1
0
def insert_data(data: list, errors: list, report_params: dict):
    conn_string = f'host={DB.get("host")} dbname= {DB.get("dbname")} user={DB.get("user")} password= {DB.get("password")}'

    with psycopg2.connect(conn_string) as conn:
        with conn.cursor() as cursor:

            if data:
                template = ','.join(['%s'] * len(data))
                insert_query = 'INSERT INTO {table} ("user", ts, context, ip) VALUES {template}'.format(
                    table=DB.get('report_table'), template=template)
                cursor.execute(insert_query, data)

            if errors:
                errors = [(report_params.get('api_report'),
                           report_params.get('api_date'), *err_item,
                           datetime.now()) for err_item in errors]
                template = ','.join(['%s'] * len(errors))
                insert_query = 'INSERT INTO {table} (api_report, api_date, row_text, error_text, ins_ts) VALUES {template}'.format(
                    table=DB.get('error_table'), template=template)
                cursor.execute(insert_query, errors)
コード例 #2
0
# coding=gbk
import databases
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from config import DB


DATABASE_URL = 'mysql://%s:%s@%s:%s/%s' % (DB.get('user'),
                                           DB.get('pass'),
                                           DB.get('host'),
                                           DB.get('port', '3306'),
                                           DB.get('db'))

ENGINE_DATABASE_URL = 'mysql+pymysql://%s:%s@%s:%s/%s' % (DB.get('user'),
                                                          DB.get('pass'),
                                                          DB.get('host'),
                                                          DB.get('port', '3306'),
                                                          DB.get('db'))

database = databases.Database(DATABASE_URL)

# 初始化数据库连接:
engine = create_engine(ENGINE_DATABASE_URL)

# SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
SessionLocal = sessionmaker(bind=engine)


async def get_db():
    db = SessionLocal()
    try: