Я собираюсь объяснить структуру кода здесь: < /p>
< P>
Код: Выделить всё
(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})
< /code>
(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()
< /code>
(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)
< /code>
Now I'm pretty sure I'm doing something wrong in here. I could really use your help guys thanks!
Tried to make async DB calls and make it quick even if heavy processing is in the back. But it turns out that it waits for other calls to finish in order to execute.
Подробнее здесь: https://stackoverflow.com/questions/781 ... to-execute