Skip to content

Commit cfc6688

Browse files
Adding bsic tutes for FASTAPI
1 parent 339aaa9 commit cfc6688

16 files changed

+313
-0
lines changed

Body_multiple_parameter.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from typing import Optional
2+
from fastapi import FastAPI,Body
3+
from pydantic import BaseModel
4+
5+
app = FastAPI()
6+
7+
class Item(BaseModel):
8+
name:str
9+
description:Optional[str] = None
10+
price : float
11+
tax : Optional[float] = None
12+
13+
class User(BaseModel):
14+
usename : str
15+
fulll_name : Optional[str] = None
16+
17+
18+
@app.put('/items/{item_id}')
19+
async def update_item(item_id:int, item:Item ,user: User, importance:int = Body(...)):
20+
results = {"item_id" : item_id,
21+
"item" : item,
22+
"user" : user,
23+
"importance" : importance}
24+
return results

Path_Parameter.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from typing import Optional
2+
from fastapi import FastAPI,Path,Query
3+
4+
app= FastAPI()
5+
6+
@app.get("/items/{item_id}")
7+
async def read_items(item_id:int = Path(...,title="title",ge=1, le=100), q: Optional[str] = Query(None, alias="item-query")):
8+
results = {"item_id": item_id}
9+
if q:
10+
results.update({"q": q})
11+
return results

Query_Parameter.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from fastapi import FastAPI,Query
2+
from typing import Optional
3+
from typing import List
4+
5+
app = FastAPI()
6+
7+
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
8+
@app.get("/items/")
9+
async def read_item(skip : int = 0, limit:int = 10):
10+
return fake_items_db[skip:skip+limit]
11+
12+
13+
@app.get("/users/{user_id}/items/{item_id}")
14+
async def read_user_item(user_id: int, item_id: str, q: Optional[str] = None, short: bool = False):
15+
item = {"item_id": item_id, "owner_id": user_id}
16+
print(item)
17+
if q:
18+
item.update({"q": q})
19+
if short:
20+
item.update(
21+
{"description": "This is an amazing item that has a long description"}
22+
)
23+
print(item)
24+
return item
25+
26+
@app.get("/item_validation/")
27+
async def read_items1(q:Optional[str] = Query("fixedquery",max_length=50)):
28+
results = {"test" : "a"}
29+
if q:
30+
results.update({"test1":q})
31+
return results
32+
33+
@app.get("/item_list/")
34+
async def list_parameter(q:List[str]=Query(None)):
35+
query_items = {"q": q}
36+
print(query_items)
37+
return query_items

Request_Body.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from typing import Optional
2+
from fastapi import FastAPI
3+
from pydantic import BaseModel
4+
5+
class Item(BaseModel):
6+
name:str
7+
description: Optional[str] = None
8+
price: float
9+
tax: Optional[float]
10+
11+
app = FastAPI()
12+
13+
@app.post("/items/")
14+
async def create_item(item:Item):
15+
item_dict = item.dict()
16+
if item.tax:
17+
price_with_tax = item.price + item.tax
18+
item_dict.update({"price_with_tax" : price_with_tax})
19+
return item_dict
20+
21+
@app.put("/items/{item_id}")
22+
async def create_item1(item_id: int, item: Item, q: Optional[str] = None):
23+
result = {"item_id": item_id, **item.dict()}
24+
if q:
25+
result.update({"q": q})
26+
return result

async_practice/FastAPI_async_await.py

Whitespace-only changes.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import asyncio
2+
import time
3+
4+
async def sleep():
5+
print(f'Time: {time.time() - start:.2f}')
6+
time.sleep(1)
7+
8+
9+
async def sum(name, numbers):
10+
total = 0
11+
for number in numbers:
12+
print(f'Task {name}: Computing {total}+{number}')
13+
await sleep()
14+
total += number
15+
print(f'Task {name}: Sum = {total}\n')
16+
17+
start = time.time()
18+
loop= asyncio.get_event_loop()
19+
tasks = [loop.create_task(sum("A", [1, 2])),
20+
loop.create_task(sum("B", [1, 2, 3, 4]))]
21+
loop.run_until_complete(asyncio.wait(tasks))
22+
loop.close()
23+
24+
end = time.time()
25+
print(f'Time: {end-start:.2f} sec')
26+
27+
28+
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import asyncio
2+
import time
3+
"""
4+
sleep function in normal and wrong are the "same". They "sleep" without allowing others to use the resources. Whereas this allows access to the resources when it is asleep.
5+
In case 2(wrong) we added async to the normal function. However the event loop will run it without interruption. Why? Because we didn't tell where the loop is allowed to interrupt your function to run another task.
6+
7+
In case 3 we told the event loop exactly where to interrupt the function to run another task. Where exactly?
8+
"""
9+
async def sleep():
10+
print(f'Time: {time.time() - start:.2f}')
11+
await asyncio.sleep(1)
12+
13+
async def sum(name, numbers):
14+
total = 0
15+
for number in numbers:
16+
print(f'Task {name}: Computing {total}+{number}')
17+
await sleep()
18+
total += number
19+
print(f'Task {name}: Sum = {total}\n')
20+
21+
start = time.time()
22+
23+
loop = asyncio.get_event_loop()
24+
tasks = [
25+
loop.create_task(sum("A", [1, 2])),
26+
loop.create_task(sum("B", [1, 2, 3])),
27+
]
28+
loop.run_until_complete(asyncio.wait(tasks))
29+
loop.close()
30+
31+
end = time.time()
32+
print(f'Time: {end-start:.2f} sec')

async_practice/factorial_async.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import asyncio
2+
3+
async def factorial(n):
4+
f = 1
5+
for i in range(2, n + 1):
6+
print(f"Computing factorial({n}), currently i={i}...")
7+
await asyncio.sleep(1)
8+
f *= i
9+
return f
10+
11+
async def main():
12+
L = await asyncio.gather(factorial(2), factorial(3), factorial(4))
13+
print(L) # [2, 6, 24]
14+
15+
16+
loop = asyncio.get_event_loop()
17+
loop.run_until_complete(main())
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import time
2+
3+
4+
"""
5+
This is normal sysn excecution.
6+
Examples from : https://stackoverflow.com/questions/50757497/simplest-async-await-example-possible-in-python
7+
8+
"""
9+
10+
def sleep():
11+
print(f'Time: {time.time() - start:.2f}')
12+
time.sleep(1)
13+
14+
def sum(name, numbers):
15+
total = 0
16+
for number in numbers:
17+
print(f'Task {name}: Computing {total}+{number}')
18+
sleep()
19+
total += number
20+
print(f'Task {name}: Sum = {total}\n')
21+
22+
start = time.time()
23+
task = [
24+
sum("A", [1, 2]),
25+
sum("B", [1, 2, 3]),
26+
]
27+
end = time.time()
28+
print(f'Time: {end-start:.2f} sec')

async_practice/simple_example.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
https://stackoverflow.com/a/50758540/7786625
3+
4+
why do you need asyncio, not just plain code?
5+
Answer is - asyncio allows you to get performance benefit when you parallelize I/O blocking operations (like reading/writing to network).
6+
7+
8+
example that uses asyncio.sleep to imitate I/O blocking operation and asyncio.gather that shows how you can run multiple blocking operations concurrently:
9+
"""
10+
11+
import asyncio
12+
import time
13+
14+
15+
async def io_related(name):
16+
print(f'{name} started')
17+
await asyncio.sleep(1)
18+
# time.sleep(1)
19+
print(f'{name} finished')
20+
21+
22+
async def main():
23+
await asyncio.gather(
24+
io_related('first'),
25+
io_related('second'),
26+
io_related('Third'),
27+
io_related('Four'),
28+
io_related('Five'),
29+
io_related('Six'),
30+
io_related('Seven'),
31+
io_related('Eight'),
32+
io_related('Nine'),
33+
34+
)
35+
36+
37+
if __name__ == '__main__':
38+
loop = asyncio.get_event_loop()
39+
start = time.time()
40+
loop.run_until_complete(main())
41+
print(f'{time.time()-start} second.')

0 commit comments

Comments
 (0)