Sobes.tech
Middle

4 app = FastAPI() 5 DB_DSN = "postgresql://test:test@localhost/testdb" 8 async def get_connection() -> asyncpg.Connection: 9 return await asyncpg.connect(DB_DSN) 12 @app.on_event("startup") 13 async def on_startup(): 14 conn = await get_connection() 15 await conn.execute(""" 16 CREATE TABLE IF NOT EXISTS "user" ( 17 id TEXT NOT NULL, 18 name TEXT NOT NULL, 19 balance DOUBLE PRECISION [phone] """) 22 await conn.close() 25 @app.post("/transfer") 26 async def transfer( 27 from_user: str = Body(), 28 to_user: str = Body(), 29 amount: float = Body(), 30 ): 31 conn = await get_connection() 32 33 row = await conn.fetchrow( 34 f'select id, balance from "user" where id = \'{from_user}\'' [phone] if row["balance"] < amount: 38 raise HTTPException(status_code=400, detail="Insufficient funds") 40 await conn.execute( 41 f'UPDATE "user" SET balance = balance - {amount} WHERE id = \'{from_user}\'' [phone] await conn.execute( 44 f'UPDATE "user" SET balance = balance + {amount} WHERE id = \'{to_user}\'' 45 )