Created
March 3, 2023 07:42
-
-
Save liviaerxin/21b4bcf042520675a187ed853aa64eb1 to your computer and use it in GitHub Desktop.
Limit only 1 request in a endpoint at a time #python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#main.py | |
from fastapi import FastAPI | |
import asyncio | |
app = FastAPI() | |
lock = asyncio.Lock() | |
counter = 0 | |
@app.post('/limit') | |
async def func(): | |
global counter | |
async with lock: | |
print("Hello") | |
counter = counter + 1 | |
await asyncio.sleep(2) | |
print("bye") | |
await asyncio.sleep(2) | |
return {"counter": counter} | |
""" | |
Make 2 requests at a time, output from server: | |
INFO: 127.0.0.1:60228 - "POST /limit HTTP/1.1" 200 OK | |
Hello | |
bye | |
INFO: 127.0.0.1:51010 - "POST /limit HTTP/1.1" 200 OK | |
Hello | |
bye | |
INFO: 127.0.0.1:51022 - "POST /limit HTTP/1.1" 200 OK | |
Request 1: | |
❯ curl -X 'POST' \ | |
'http://127.0.0.1:8000/limit' \ | |
-H 'accept: application/json' \ | |
-d '' | |
{"counter":1}% | |
Request 2: | |
❯ curl -X 'POST' \ | |
'http://127.0.0.1:8000/limit' \ | |
-H 'accept: application/json' \ | |
-d '' | |
{"counter":2}% | |
""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#main.py | |
from fastapi import FastAPI | |
import asyncio | |
app = FastAPI() | |
lock = asyncio.Lock() | |
counter = 0 | |
@app.post('/limit') | |
async def func(): | |
global counter | |
print("Hello") | |
counter = counter + 1 | |
await asyncio.sleep(2) | |
print("bye") | |
await asyncio.sleep(2) | |
return {"counter": counter} | |
""" | |
Make 2 requests at a time, output from server: | |
Hello | |
Hello | |
bye | |
bye | |
INFO: 127.0.0.1:45160 - "POST /limit HTTP/1.1" 200 OK | |
INFO: 127.0.0.1:45172 - "POST /limit HTTP/1.1" 200 OK | |
Request 1: | |
❯ curl -X 'POST' \ | |
'http://127.0.0.1:8000/limit' \ | |
-H 'accept: application/json' \ | |
-d '' | |
{"counter":2}% | |
Request 2: | |
❯ curl -X 'POST' \ | |
'http://127.0.0.1:8000/limit' \ | |
-H 'accept: application/json' \ | |
-d '' | |
{"counter":2}% | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment