fastapi草稿

from fastapi import FastAPI, Query, Path, Body, Cookie, Header, Form, File, UploadFile, HTTPException
from pydantic import BaseModel, Field
from typing import List
from uuid import UUID
from datetime import datetime, time, timedelta
from starlette.responses import HTMLResponse
from fastapi.routing import APIRoute
from enum import Enum


app = FastAPI()


@app.get('/item/{item_id}', summary='查询item信息')
async def read_items(item_id: str):
    items = {'1': 'abc'}
    if item_id not in items:
        raise HTTPException(status_code=404, detail='not this item id', headers={'x-error': 'error'})
    return {'item': item_id}


@app.post('/files/')
async def create_file(file: UploadFile = File(...)):
    return {'filename': file.filename, 'content_type': file.content_type}


@app.get('/')
async def main():
    content = """
<body>
<form action="/files/" enctype="multipart/form-data" method="post">
<input name="files" type="file" multiple>
<input type="submit">
</form>
<form action="/uploadfiles/" enctype="multipart/form-data" method="post">
<input name="files" type="file" multiple>
<input type="submit">
</form>
</body>
    """
    return HTMLResponse(content=content)


@app.post('/login/')
async def login(*, username: str = Form(..., description='姓名'), password: str = Form(...)):
    return {'name': username, 'password': password}


@app.put('/item/test')
async def read_item(item_id: str, start_datetime: datetime = Body(None), end_time: time = Body(None),
                    process_after: timedelta = Body(None)):
    start_process = start_datetime + process_after   # 错误域名被锁住的过期时间可以用这个来做
    return {'item_id': item_id, 'start_datetime': start_datetime, 'start_process': start_process, 'end_time': end_time,'process_after': process_after}


class Image(BaseModel):
    url: str
    name: str


class ModelName(str, Enum):
    alexnet = 'alexnet'
    reset = 'reset'
    lenet = 'lenet'


@app.get('/model/{model_name}')
async def model(model_name: ModelName):
    return {'model name': model_name}


class Item(BaseModel):
    name: str
    describe: str = Field(None, title='this description of the item', max_length=300)
    price: float = Field(..., gt=0, description='the price must be greater than zero')
    tax: float = None
    tags: List[str] = []
    image: Image = None
    ## 怎么设置时间字段/ 外键/ id自增长


class User(BaseModel):
    username: str
    full_name: str = None


# 如果在 path中也声明了该参数,它将用作path参数。
# 如果参数是 单一类型(例如int,float,str,str,bool等),它将被解释为 query参数。
# 如果参数声明为Pydantic(即继承BaseModel的类)模型*的类型,则它将被解释为 请求体。


@app.post('/image/', response_model=Image)
async def create_image(*, images: Image):
    return images


@app.post('/cookie/')
async def create_image(*, ads_id: str = Header(None, convert_underscores=False),
                       x_token: List[str] = Header(None)):  # Header会将_转换为-, convert_underscores=False则不转换
    return {'ads_id': ads_id}


@app.get('/items')
async def read_root(q: List[str] = Query(None, alias='item-query', min_length=2, max_length=5, regex='^a.*',
                                         title='Query string', description='aaaaaaaaaaaaaaaaaaa',
                                         deprecated=True)):
    result = {'item': [{'item_id': 'Foo'}, {'item_id': 'bar'}]}
    if q:
        result.update({'q': q})
    return result


@app.get('/items/{item_id}')
async def read_item_as(item_id: int = Path(..., title='the id of the item to get', ge=1), abc: str = None):
    return {'item_id': item_id, 'q': abc}  # 参数只能写 ?q= 吗,怎么让前端随便写,后端也能读到所有参数


@app.put('/items/{item_id}')
def update_item(*, item_id: int = Path(..., ge=0, le=1000), item: Item = Body(..., embed=True), user: User, q: str = None,
                importance: int = Body(...)):  # 单个Body参数的时候,可以使用embed参数, 这样在预期的请求体格式就是{'item':{'name':'abc'}}
    result = {'item_id': item_id, 'user': user, 'importance': importance}
    if q:
        result.update({'q': q})
    if item:
        result.update({'item': item})
    return result


def use_route_name_as_operation_ids(app: FastAPI) -> None:
    for route in app.routes:
        if isinstance(route, APIRoute):
            route.operation_id = route.operation_id


use_route_name_as_operation_ids(app)


if __name__ == '__main__':
    import uvicorn
    uvicorn.run('main:app', reload=True)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值