1717
1818import httpx
1919import pyperf
20+ import threading
2021import uvicorn
2122from fastapi import FastAPI
2223from pydantic import BaseModel
@@ -42,6 +43,23 @@ async def get_item(item_id: int):
4243 "tags" : ["sample" , "item" , "fastapi" ]
4344 }
4445
46+ def setup_server ():
47+ with socket .socket (socket .AF_INET , socket .SOCK_STREAM ) as s :
48+ s .bind ((HOST , 0 ))
49+ s .listen (1 )
50+ port = s .getsockname ()[1 ]
51+
52+ config = uvicorn .Config (app , host = HOST , port = port , log_level = "error" )
53+ server = uvicorn .Server (config )
54+
55+ server_thread = threading .Thread (target = server .run , daemon = True )
56+ server_thread .start ()
57+
58+ while not server .started :
59+ pass
60+
61+ url = f"http://{ HOST } :{ port } "
62+ return url
4563
4664def bench_fastapi (loops , url ):
4765 async def run_benchmark ():
@@ -66,24 +84,7 @@ async def run_benchmark():
6684
6785
6886if __name__ == "__main__" :
69- import threading
70-
71- with socket .socket (socket .AF_INET , socket .SOCK_STREAM ) as s :
72- s .bind ((HOST , 0 ))
73- s .listen (1 )
74- port = s .getsockname ()[1 ]
75-
76- config = uvicorn .Config (app , host = HOST , port = port , log_level = "error" )
77- server = uvicorn .Server (config )
78-
79- server_thread = threading .Thread (target = server .run , daemon = True )
80- server_thread .start ()
81-
82- while not server .started :
83- pass
84-
85- url = f"http://{ HOST } :{ port } "
86-
87+ url = setup_server ()
8788 runner = pyperf .Runner ()
8889 runner .metadata ['description' ] = "Test the performance of HTTP requests with FastAPI"
8990 runner .bench_time_func ("fastapi_http" , bench_fastapi , url )
0 commit comments