Здесь я собираюсь объяснить структуру кода:
< р>
Код: Выделить всё
(root)/database/db.py:
from sqlalchemy.pool import NullPool
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import sessionmaker
import asyncio
from sqlalchemy.pool import QueuePool
engine = create_async_engine('sqlite+aiosqlite:///main.sqlite3')
def async_session():
session_factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession, future=True )
return session_factory()
db = SQLAlchemy(session_options={"class_": AsyncSession})
Код: Выделить всё
(root)/database/actions.py:
from database.db import db, async_session
from database.models import ApiKey
from sqlalchemy import select
# A function to get a customer using thier API key.
async def get_customer(api_key):
async with async_session() as session:
async with session.begin():
result = await session.execute(select(ApiKey).where(ApiKey.api_key == api_key))
key = result.scalars().first()
if key:
return {'id': key.id, 'api_key': key.api_key, 'owner_name': key.owner_name}
else:
return None
# A function to get all customers ( for admin usage )
async def get_all_customers():
async with async_session() as session:
async with session.begin():
result = await session.execute(select(ApiKey))
return result.scalars().all()
Код: Выделить всё
(root)/app.py:
from database.actions import get_all_customers,get_customer
from database.db import db, engine
import asyncio
app = Flask(app_name)
db.init_app(app)
# Flask route to get a customer
u/app.route('/api/customers', methods=['GET'])
async def customer_get():
api_key = request.args.get('api-key')
try:
if api_key:
result = await get_customer(api_key)
if result:
return jsonify(result)
else:
return {}
else:
result = await get_all_customers()
if result:
return jsonify(result)
except Exception as e:
print(e)
# Flask route that conduct requests/io and take about 10 to 20 seconds to complete.
u/app.route('/api/call', methods=['GET'])
async def call():
api_key = request.args.get('api-key')
try:
if api_key:
result = await heavy_call(api_key)
if result:
return jsonify(result)
else:
return {}
except Exception as e:
print(e)
Пытался выполнять асинхронные вызовы БД и делать это быстро, даже если сзади идет тяжелая обработка. Но оказывается, что для выполнения он ждет завершения других вызовов.
Подробнее здесь: https://stackoverflow.com/questions/781 ... to-execute