Skip to content

Instantly share code, notes, and snippets.

@diogommartins
Created May 5, 2019 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diogommartins/dcd155b1102a6e5f10c647dc67207e51 to your computer and use it in GitHub Desktop.
Save diogommartins/dcd155b1102a6e5f10c647dc67207e51 to your computer and use it in GitHub Desktop.
import asyncio
from http import HTTPStatus
from aiohttp import web
REQUEST_COUNTER = 0
async def get_balance(request_id: int):
await asyncio.sleep(0.2)
print(f"{request_id}: get_balance done")
async def get_last_operation(request_id: int):
await asyncio.sleep(0.1)
print(f"{request_id}: get_last_operation done")
async def perform_debit(request_id: int):
await asyncio.sleep(0.1)
print(f"{request_id}: perform_debit done")
async def perform_credit(request_id: int):
await asyncio.sleep(0.2)
print(f"{request_id}: perform_credit done")
async def save_last_operation(request_id: int):
await asyncio.sleep(0.1)
print(f"{request_id}: save_last_operation done")
async def perform_transaction(request: web.Request) -> web.Response:
global REQUEST_COUNTER
request_id = REQUEST_COUNTER
REQUEST_COUNTER += 1
current_operation = await request.json()
last_operation = await get_last_operation(request_id)
if last_operation and last_operation == current_operation:
return web.Response(status=HTTPStatus.BAD_REQUEST)
await perform_debit(request_id)
await perform_credit(request_id)
await save_last_operation(request_id)
return web.Response(status=HTTPStatus.OK)
app = web.Application()
app.add_routes([web.post('/', perform_transaction)])
web.run_app(app, port=8000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment