Browse Source

framework designing

chenhaiyang 4 years ago
parent
commit
bc610d45db

+ 0 - 0
app/api/routers/__init__.py


+ 41 - 0
app/api/routers/items.py

@@ -0,0 +1,41 @@
+# -*- coding: utf-8 -*-
+
+from datetime import datetime, time, timedelta
+from typing import Optional
+from uuid import UUID
+
+from fastapi import APIRouter, HTTPException, Path, Query, Body
+
+router = APIRouter()
+
+
+@router.get('/{item_id}')
+async def read_items(
+    item_id: int = Path(..., title='The ID of the item to get'),
+    q: Optional[str] = Query(None, alias='item-query'),
+):
+    results = {'item_id': item_id}
+    if q:
+        results.update({'q': q})
+    return results
+
+
+@router.put('/{item_id}')
+async def update_item(
+        item_id: UUID,
+        start_datetime: Optional[datetime] = Body(None),
+        end_datetime: Optional[datetime] = Body(None),
+        repeat_at: Optional[time] = Body(None),
+        process_after: Optional[timedelta] = Body(None),
+):
+    start_process = start_datetime + process_after
+    duration = end_datetime - start_process
+    return {
+        "item_id": item_id,
+        "start_datetime": start_datetime,
+        "end_datetime": end_datetime,
+        "repeat_at": repeat_at,
+        "process_after": process_after,
+        "start_process": start_process,
+        "duration": duration,
+    }

+ 17 - 0
app/api/routers/targets.py

@@ -0,0 +1,17 @@
+# -*- coding: utf-8 -*-
+
+from fastapi import APIRouter, HTTPException, Path, Query
+
+from app.models.targets import TargetReadjustInResponse
+
+router = APIRouter()
+
+
+@router.get('/readjust', response_model=TargetReadjustInResponse)
+async def readjust_target(
+        project_id: str = Query(..., max_length=50, regex='^Pj'),
+        space_id: str = Query(..., max_length=50, regex='^Sp'),
+        wechat_timestamp: str = Query(None, min_length=8, max_length=8),
+):
+    # TODO
+    return

+ 27 - 0
app/api/routers/users.py

@@ -0,0 +1,27 @@
+# -*- coding: utf-8 -*-
+
+from typing import Optional
+
+from fastapi import APIRouter, Depends
+
+router = APIRouter()
+
+
+async def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 100):
+    return {"q": q, "skip": skip, "limit": limit}
+
+
+@router.get('/users', tags=['users'])
+async def read_users(commons: dict = Depends(common_parameters)):
+    # return [{'username': 'Foo'}, {'username': 'Bar'}]
+    return commons
+
+
+@router.get('/user/me', tags=['users'])
+async def read_user_me():
+    return {'username': 'fake current user'}
+
+
+@router.get('/users/{username}', tags=['users'])
+async def read_user(username: str):
+    return {'username': username}

+ 0 - 0
app/controllers/__init__.py


+ 3 - 0
app/controllers/targets.py

@@ -0,0 +1,3 @@
+# -*- coding: utf-8 -*-
+
+

+ 0 - 0
app/core/__init__.py


+ 0 - 0
app/core/config.py


+ 0 - 0
app/core/events.py


+ 0 - 0
app/core/logging.py


+ 0 - 0
app/db/__init__.py


+ 21 - 0
app/main.py

@@ -0,0 +1,21 @@
+# -*- coding: utf-8 -*-
+
+from fastapi import Depends, FastAPI, Header, HTTPException
+
+from .api.routers import items, users
+
+app = FastAPI()
+
+
+async def get_token_header(x_token: str = Header(...)):
+    if x_token != 'fake-super-secret-token':
+        raise HTTPException(status_code=400, detail='X-Token header invalid')
+
+app.include_router(users.router)
+app.include_router(
+    items.router,
+    prefix='/items',
+    tags=['items'],
+    dependencies=[Depends(get_token_header)],
+    responses={404: {'description': 'Not found'}},
+)

+ 11 - 0
app/models/targets.py

@@ -0,0 +1,11 @@
+# -*- coding: utf-8 -*-
+
+from pydantic import BaseModel
+
+
+class TargetReadjustInResponse(BaseModel):
+    result: str = 'success'
+    projectId: str
+    roomId: str
+    flag: int
+    time: str

+ 0 - 0
app/resources/__init__.py


+ 47 - 0
app/services/temperature.py

@@ -0,0 +1,47 @@
+# -*- coding: utf-8 -*-
+
+from typing import Tuple
+import asyncio
+
+import httpx
+import pandas as pd
+
+from fastapi import Depends
+
+from app.utils.date import get_time_str
+
+TRANSFER_SERVER = 'http://api.sagacloud.cn/duoduo-service/transfer'
+DATA_PLATFORM = 'http://api.sagacloud.cn/'
+
+
+async def get_season_type(project_id: str, date: str = Depends(get_time_str)) -> str:
+    url = f'{TRANSFER_SERVER}/environment/getSeasonType'
+    params = {
+        'projectId': project_id,
+        'date': date,
+    }
+    with httpx.Client() as client:
+        r = client.get(url, params=params)
+        print(client.close())
+    print(client.close())
+    raw_info = r.json()
+
+    return raw_info.get('data')
+
+
+async def get_env_info(project_id: str, space_id: str) -> Tuple[str, pd.DataFrame, dict]:
+    url = f'{TRANSFER_SERVER}/environment/databyroom'
+    start_time = get_time_str(100 * 60, flag='ago')
+    end_time = get_time_str()
+    params = {
+        'projectId': project_id,
+        'spaceId': space_id,
+        'statTime': start_time,
+        'endTime': end_time,
+    }
+    with httpx.Client() as client:
+        pass
+
+
+if __name__ == '__main__':
+    asyncio.run(get_season_type('Pj1101020002'))

+ 0 - 0
app/utils/__init__.py


+ 26 - 0
app/utils/date.py

@@ -0,0 +1,26 @@
+# -*- coding: utf-8 -*-
+
+import arrow
+
+
+def get_time_str(delta: int = 0, flag: str = 'now') -> str:
+    """
+    Return two beijing time strings.
+    :param delta: time delta(seconds)
+    :param flag:
+    :return: two '%Y%m%d%H%M%S' format strings
+    """
+    utc = arrow.utcnow()
+    local = utc.to('Asia/Shanghai')
+    _FMT = '%Y%m%d%H%M%S'
+    if flag == 'ago':
+        delta = -delta
+        t = local.shift(seconds=delta)
+    elif flag == 'later':
+        t = local.shift(seconds=delta)
+    else:
+        t = local
+
+    time_str = t.format('%Y%m%d%H%M%S')
+
+    return time_str