2022年9月9日 星期五

FAST API

# uvicorn main:app --reload --host 0.0.0.0


import os

from typing import List

import logging


from fastapi import FastAPI, HTTPException

from fastapi.middleware.cors import CORSMiddleware

from pydantic import BaseModel


import httpx

import uvicorn

import webbrowser


if not os.path.exists("./logs/"):

    os.makedirs("./logs/")


logging.basicConfig(

    level=logging.INFO,

    format="%(asctime)s [%(levelname)s] %(message)s",

    handlers=[

        logging.FileHandler("./logs/debug.log"),

        logging.StreamHandler()

    ]

)


app = FastAPI(title="fastapi title")

app.add_middleware(

    CORSMiddleware,

    allow_origins="*",

    allow_credentials=True,

    allow_methods=["*"],

    allow_headers=["*"],

)


@app.get("/")

def root():

    return {"name": "fastapi root"}


async def demo(url: str):

    try:

        async with httpx.AsyncClient() as client:

            r = await client.post(url)

            print(r.status_code)

            print(r.text)

            return r.text

    except Exception as e:

        print(e)

        raise HTTPException(status_code=404, detail=f"failed to connect url {url}")


class Item(BaseModel):

    id: int

    value: float


class Items(BaseModel):

    items: List[Item]


@app.put("/put_items")

def put_items(items: Items):

    logging.info(f"items")

    logging.info(f"{items}")

    return {"message": f"received items count {len(items.items)}"}


if __name__ == "__main__":

    webbrowser.open('http://127.0.0.1:22909/docs', new=2)

    uvicorn.run("a:app", host="127.0.0.1", port=22909, log_level="info", reload=True, debug=True)


沒有留言:

張貼留言

2023 Promox on Morefine N6000 16GB 512GB

2023 Promox on Morefine N6000 16GB 512GB Software Etcher 100MB (not but can be rufus-4.3.exe 1.4MB) Proxmox VE 7.4 ISO Installer (1st ISO re...