-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
97 lines (66 loc) · 2.25 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import uvicorn
import aiohttp
import asyncio
from fastapi import FastAPI
from tortoise import fields
from tortoise.models import Model
from tortoise.contrib.fastapi import register_tortoise
from tortoise.contrib.pydantic import pydantic_model_creator
app = FastAPI()
session = None
@app.on_event('startup')
async def startup_event():
global session
session = aiohttp.ClientSession()
@app.on_event('shutdown')
async def shutdown_event():
await session.close()
class City(Model):
id = fields.IntField(pk=True)
name = fields.CharField(50, unique=True)
timezone = fields.CharField(50)
def current_time(self) -> str:
return ''
@classmethod
async def get_current_time(cls, obj, current_session):
async with current_session.get(f'http://worldclockapi.com/api/json/{obj.timezone}/now') as response:
result = await response.json()
current_time = result['currentDateTime']
obj.current_time = current_time
class PydanticMeta:
computed = ('current_time',)
City_Pydantic = pydantic_model_creator(City, name='City')
CityIn_Pydantic = pydantic_model_creator(City, name='CityIn', exclude_readonly=True)
@app.get('/')
def index():
return {'key': 'value'}
@app.get('/cities')
async def get_cities():
cities = await City_Pydantic.from_queryset(City.all())
global session
tasks = []
for city in cities:
task = asyncio.create_task(City.get_current_time(city, session))
tasks.append(task)
await asyncio.gather(*tasks)
return cities
@app.get('/cities/{city_id')
async def get_city(city_id: int):
return await City_Pydantic.from_queryset_single(City.get(id=city_id))
@app.post('/cities')
async def create_city(city: CityIn_Pydantic):
city_obj = await City.create(**city.dict(exclude_unset=True))
return await City_Pydantic.from_tortoise_orm(city_obj)
@app.delete('/cities/{city_id}')
async def delete_city(city_id: int):
await City.filter(id=city_id).delete()
return {'msg': 'Success'}
register_tortoise(
app,
db_url='sqlite://db.sqlite3',
modules={'models': ['main']},
generate_schemas=True,
add_exception_handlers=True
)
if __name__ == '__main__':
uvicorn.run('main:app', host='0.0.0.0', port=8000, reload=True)