22import sys
33import multiprocessing
44import json
5- from contextlib import asynccontextmanager
6-
7- import asyncpg
8- import orjson
95
106os .environ ["TURBO_DISABLE_RATE_LIMITING" ] = "1"
117os .environ ["TURBO_DISABLE_CACHE" ] = "1"
128
13- from turboapi import TurboAPI , Request , Response , Path , Query , HTTPException
14- from turboapi .responses import PlainTextResponse , JSONResponse
15- from turboapi .middleware .gzip import GZipMiddleware
16- from turboapi .staticfiles import StaticFiles
17-
189# -- Dataset and constants --------------------------------------------------------
1910
2011CPU_COUNT = int (multiprocessing .cpu_count ())
3021except Exception :
3122 pass
3223
33- # -- Postgres DB ------------------------------------------------------------
3424
35- PG_POOL : asyncpg . Pool | None = None
25+ # -- APP -----------------------------------------------------------------------
3626
37- PG_QUERY = (
38- "SELECT id, name, category, price, quantity, active, tags, rating_score, rating_count "
39- "FROM items WHERE price BETWEEN $1 AND $2 LIMIT $3"
40- )
27+ from turboapi .request_handler import RequestBodyParser
4128
42- class NoResetConnection (asyncpg .Connection ):
43- __slots__ = ()
44- def get_reset_query (self ):
45- return ""
29+ original_parse_json_body = RequestBodyParser .parse_json_body
4630
47- @asynccontextmanager
48- async def lifespan (application : TurboAPI ):
49- global PG_POOL , NoResetConnection
50- DATABASE_URL = os .environ .get ("DATABASE_URL" )
51- if DATABASE_URL :
52- try :
53- if DATABASE_URL .startswith ("postgres://" ):
54- DATABASE_URL = "postgresql://" + DATABASE_URL [len ("postgres://" ):]
55- PG_POOL_MAX_SIZE = 2
56- DATABASE_MAX_CONN = os .environ .get ("DATABASE_MAX_CONN" , None )
57- if DATABASE_MAX_CONN :
58- pool_size = int (DATABASE_MAX_CONN ) * 0.92 / WRK_COUNT
59- PG_POOL_MAX_SIZE = int (pool_size + 0.95 )
60- PG_POOL = await asyncpg .create_pool (
61- dsn = DATABASE_URL ,
62- min_size = 1 ,
63- max_size = max (PG_POOL_MAX_SIZE , 2 ),
64- connection_class = NoResetConnection
65- )
66- except Exception :
67- PG_POOL = None
68- yield
69- if PG_POOL :
70- await PG_POOL .close ()
71- PG_POOL = None
31+ def fixed_parse_json_body (body , handler_signature ):
32+ return original_parse_json_body (body , handler_signature )
33+ '''
34+ if not body:
35+ return { }
36+ if body.startswith(b'{') or body.startswith(b'['):
37+ return original_parse_json_body(body, handler_signature)
38+ return { "_BODY_": body }
39+ '''
40+ RequestBodyParser .parse_json_body = staticmethod (fixed_parse_json_body )
7241
42+ from turboapi import TurboAPI , Request , Path , Query , File , UploadFile , HTTPException
43+ from turboapi .responses import PlainTextResponse , JSONResponse
44+ from turboapi .middleware import GZipMiddleware
45+ from turboapi .staticfiles import StaticFiles
7346
74- app = TurboAPI (lifespan = lifespan )
47+ app = TurboAPI ()
7548
7649app .add_middleware (GZipMiddleware , minimum_size = 1 , compresslevel = 5 )
7750
7851
7952# -- Routes ------------------------------------------------------------------
8053
8154@app .get ("/pipeline" )
82- async def pipeline ():
55+ def pipeline ():
8356 return PlainTextResponse (b"ok" )
8457
8558
86- @app .api_route ("/baseline11" , methods = ["GET" , "POST" ])
87- async def baseline11 (request : Request ):
88- total = 0
89- for v in request .query_params .values ():
59+ @app .get ("/baseline11" )
60+ def baseline11 (a : str = Query (), b : str = Query ()):
61+ try :
62+ return PlainTextResponse ( str ( int (a ) + int (b ) ) )
63+ except Exception :
64+ return PlainTextResponse ("-444" )
65+
66+
67+ @app .post ("/baseline11" )
68+ def baseline11 (a , b , _BODY_ ):
69+ try :
70+ return PlainTextResponse ( str ( int (a ) + int (b ) ) + f' body = { _BODY_ } ' )
71+ except Exception :
72+ return PlainTextResponse ("-555" )
73+
74+ '''
75+ try:
76+ a = int(a)
77+ b = int(b)
78+ except Exception:
9079 try:
91- total += int (v )
92- except ValueError :
93- pass
94- if request .method == "POST" :
95- body = await request .body ()
96- if body :
97- try :
98- total += int (body .strip ())
99- except ValueError :
100- pass
80+ return PlainTextResponse(f"a=<{a}> b=<{b}>")
81+ except Exception:
82+ return PlainTextResponse("-444")
83+ total = 0
84+ try:
85+ total = a + b
86+ except Exception:
87+ pass
88+ try:
89+ if request.method == "POST":
90+ body = request.body.read()
91+ if body:
92+ try:
93+ total += int(body.strip())
94+ except ValueError:
95+ pass
96+ except Exception:
97+ return PlainTextResponse("-1")
10198 return PlainTextResponse(str(total))
10299
103100
104- def json_common (request : Request , count : int , m_val : float ):
101+ def json_common(count: int, m_val: float):
105102 global DATASET_ITEMS
106103 if not DATASET_ITEMS:
107104 return PlainTextResponse("No dataset", 500)
@@ -115,64 +112,22 @@ def json_common(request: Request, count: int, m_val: float):
115112 items.append(item)
116113 return JSONResponse( { "items": items, "count": len(items) } )
117114 except Exception:
118- return JSONResponse ( { "items" : [ ], "count" : 0 } )
115+ return JSONResponse( { "items": [ ], "count": -1 } )
119116
120117
121118@app.get("/json/{count}")
122- async def json_endpoint (request : Request , count : int = Path (...), m : float = Query (...)):
123- return json_common (request , count , m )
119+ def json_endpoint(count: int, m: float):
120+ count = int(count)
121+ m = float(m)
122+ return json_common(count, m)
124123
125124
126125@app.get("/json-comp/{count}")
127- async def json_comp_endpoint (request : Request , count : int = Path (...), m : float = Query (...)):
128- return json_common (request , count , m )
129-
130-
131- @app .get ("/async-db" )
132- async def async_db_endpoint (request : Request , min_val : float = Query (..., alias = "min" ), max_val : float = Query (..., alias = "max" ), limit : int = Query (...)):
133- global PG_POOL
134- if not PG_POOL :
135- return JSONResponse ( { "items" : [ ], "count" : 0 } )
136- try :
137- db_conn = await PG_POOL .acquire ()
138- try :
139- rows = await db_conn .fetch (PG_QUERY , min_val , max_val , limit )
140- finally :
141- await PG_POOL .release (db_conn )
142- items = [
143- {
144- 'id' : row ['id' ],
145- 'name' : row ['name' ],
146- 'category' : row ['category' ],
147- 'price' : row ['price' ],
148- 'quantity' : row ['quantity' ],
149- 'active' : row ['active' ],
150- 'tags' : json .loads (row ['tags' ]) if isinstance (row ['tags' ], str ) else row ['tags' ],
151- 'rating' : {
152- 'score' : row ['rating_score' ],
153- 'count' : row ['rating_count' ],
154- }
155- }
156- for row in rows
157- ]
158- return JSONResponse ( { "items" : items , "count" : len (items ) } )
159- except Exception :
160- return JSONResponse ( { "items" : [ ], "count" : 0 } )
161-
162-
163- @app .post ("/upload" )
164- async def upload_endpoint (request : Request ):
165- size = 0
166- async for chunk in request .stream ():
167- size += len (chunk )
168- return PlainTextResponse (str (size ))
169-
170-
171- try :
172- app .mount ("/static" , StaticFiles (directory = "/data/static/" ), name = "static" )
173- except Exception :
174- pass
175-
126+ def json_comp_endpoint(count: int, m: float):
127+ count = int(count)
128+ m = float(m)
129+ return json_common(count, m)
130+ '''
176131
177132if __name__ == "__main__" :
178- app .run (host = "0.0.0.0" , port = 8080 , workers = WRK_COUNT )
133+ app .run (host = "0.0.0.0" , port = 8080 )
0 commit comments