Example #1
0
#!usr/bin/env python
# -*- coding:utf-8 _*-
from app.core.utils import return_msg
from app.core.utils import SERVER_STATUS

from app.db.dao.user_dao import UserDAO
from app.db.schema import User as SchemaUser
from fastapi import Request

from app.api.route import get_router

user_router = get_router()


@user_router.post("/user/")
async def create_user(user: SchemaUser,
                      request: Request):  #,db: Session = Depends(check_db)
    #获取全局app的参数
    #print(request.app.config)
    user_id = await UserDAO.create(**user.dict())
    return return_msg(status=SERVER_STATUS.OK, data={"user_id": user_id})


@user_router.get("/user/{id}")
async def get_user(id: int):
    #用db执行
    #query = ModelUser.insert().values(first_name=SchemaUser.first_name)
    #last_record_id = await app.db.execute(query)
    user = await UserDAO.get(id)
    return return_msg(status=SERVER_STATUS.OK, data=SchemaUser(**user).dict())
Example #2
0
import json

from pydantic import BaseModel

from app.api.route import get_router
from app.task.work import celery

task_router = get_router()

class Item(BaseModel):
    name: str

#from app.celery.tasks import hello_world

@task_router.post("/task_hello_world/")
async def create_item(item: Item):
    task_name = "hello.task"
    task = celery.send_task(task_name, args=[item.name])
    return dict(id=task.id, url='localhost:9003/check_task/{}'.format(task.id))


@task_router.get("/check_task/{id}")
def check_task(id: str):
    ins = celery.control.inspect()
    task = celery.AsyncResult(id)
    if task.state == 'SUCCESS':
        response = {
            'status': task.state,
            'result': task.result,
            'task_id': id
        }
Example #3
0
from typing import Optional
from app.core.utils import return_msg
from app.core.utils import SERVER_STATUS

from app.api.route import get_router
test_router = get_router()

#https://fastapi.tiangolo.com/async/
#对于接口是否需要async 定义的理解
#对于调用方法提供需要await调用,则需要用async
#对于直接返回结果的,也需要用async
#对于需要长时间其他操作的,不用async
#如果不确定,不用async
from fastapi_cache.decorator import cache


@test_router.get('/hello')
@cache(expire=60)
async def hello():
    '''
    just for test
    :return:
    '''
    # 测试数据
    data = {
        'code': "200",
        'data': "test success",
    }
    #a=1/0
    return return_msg(status=SERVER_STATUS.OK, data=data, msg="")
Example #4
0
            function sendMessage(event) {
                var input = document.getElementById("messageText")
                ws.send(input.value)
                input.value = ''
                event.preventDefault()
            }
        </script>
    </body>
</html>
"""

from app.api.route import get_router

from fastapi.responses import HTMLResponse

socker_router = get_router()


@socker_router.get("/socket")
#在浏览器中打开测试
# http://127.0.0.1:8091/socket
async def get():
    return HTMLResponse(html)


# @socker_router.websocket("/ws/{client_id}")
# async def websocket_endpoint(websocket: WebSocket, client_id: int):
#     await manager.connect(websocket)
#     try:
#         while True:
#             data = await websocket.receive_text()
Example #5
0
from app.api.route import get_router
from fastapi import FastAPI, File, UploadFile
from typing import List

files_router = get_router()

path = r'F:\02_data\test'


@files_router.post("/uploadfile/")
async def upload_file(file: UploadFile = File(...)):
    contents = await file.read()

    tmp_pth = r'%s/%s' % (path, file.filename)

    # Open a file
    with open(tmp_pth, "wb+") as f:
        f.write(contents)
    return {"file_size": len(contents), "file_name": file.filename}


@files_router.post("/uploadfiles/")
async def upload_file(tempfiles: List[UploadFile] = File(...)):
    for tempfile in tempfiles:
        tmp_pth = r'%s/%s' % (path, tempfile.filename)
        print(tmp_pth)
        #f"/opt/{tempfile.filename}"
        with open(tmp_pth, 'wb') as f:
            for i in iter(lambda: tempfile.file.read(1024 * 1024 * 100), b''):
                f.write(i)
        f.close()