标签: fastapi

如何解决fastapi中没有属性“routes”的问题?

我按照https://fastapi.tiangolo.com/tutorial/bigger-applications/资源来设计我的应用程序

.....game/urls.py....

from fastapi import APIRouter
router = APIRouter()
@router.post("/", response_model=schemas.GameOut, tags=["games"])
def create_game(game: schemas.GameIn, db: Session = Depends(get_db)):
    return Crud.create(db,game,model)

...main.py...

from game import urls as game_urls
app.include_router(game_urls,prefix="/games")
Run Code Online (Sandbox Code Playgroud)

正确导入所有内容。当我运行 uvicorn main:app --reload 时,它显示“NO attribures 'routes'”错误,我无法找到,我在这里犯的错误是什么。任何人都可以帮助我吗?

fastapi

2
推荐指数
1
解决办法
3319
查看次数

FastAPI Gunicorn 添加日志记录时间戳

我正在使用 docker 运行 FastAPI https://fastapi.tiangolo.com/deployment/

tiangolo/uvicorn-gunicorn-fastapi:python3.7
Run Code Online (Sandbox Code Playgroud)

start.sh 看起来像:

exec gunicorn -k uvicorn.workers.UvicornWorker -c "$GUNICORN_CONF" "$APP_MODULE"
Run Code Online (Sandbox Code Playgroud)

我的 docker 日志看起来没有时间戳:

INFO:     123.123.123.123:48736 - "GET /wp-login.php HTTP/1.0" 404 Not Found
INFO:     123.123.123.123:48808 - "GET /robots.txt HTTP/1.0" 404 Not Found
INFO:     123.123.123.123:48810 - "GET / HTTP/1.0" 200 OK
Run Code Online (Sandbox Code Playgroud)

似乎在gunicorn_conf.py它使用

use_loglevel = os.getenv("LOG_LEVEL", "info")
Run Code Online (Sandbox Code Playgroud)

如何轻松优雅地修改带有时间戳的 INFO 和 ERROR 记录器格式?

logging gunicorn docker fastapi

2
推荐指数
1
解决办法
6496
查看次数

fastapi 自定义响应类作为默认响应类

我正在尝试使用自定义响应类作为默认响应

from fastapi.responses import Response
from bson.json_util import dumps

class MongoResponse(Response):
    def __init__(self, content, *args, **kwargs):
        super().__init__(
            content=dumps(content),
            media_type="application/json",
            *args,
            **kwargs,
        )
Run Code Online (Sandbox Code Playgroud)

当我明确使用响应类时,这工作得很好。

@app.get("/")
async def getDoc():
    foo = client.get_database('foo')
    result = await foo.bar.find_one({'author': 'fool'})
    return MongoResponse(result)
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试将其作为参数传递给 FastAPI 构造函数时,仅在从请求处理程序返回数据时似乎不会使用它。

app = FastAPI(default_response_class=MongoResponse)

@app.get("/")
async def getDoc():
    foo = client.get_database('foo')
    result = await foo.bar.find_one({'author': 'fool'})
    return result
Run Code Online (Sandbox Code Playgroud)

当我查看下面的堆栈跟踪时,它似乎仍在使用正常的默认响应,即json response

ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/home/blue/podman/test/.venv/lib/python3.6/site-packages/uvicorn/protocols/http/httptools_impl.py", line 390, in run_asgi
    result …
Run Code Online (Sandbox Code Playgroud)

python python-3.x fastapi

2
推荐指数
1
解决办法
8598
查看次数

在本地主机中获取 FastApi 的 JavaScript

你如何使用我用FastAPI制作的Api,从我的本地主机,从外部html,例如,这是我的简单测试实现:

主要.py:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def main():
    return {"message": "Hello World"}
Run Code Online (Sandbox Code Playgroud)

索引.html:

<html>
<head>
    <title>Item Details</title>
</head>
<body>
    <script>
        //var url = 'http://localhost:8000';
        fetch('http://127.0.0.1:8000/')
        .then(res => res.json())
        .then(data => {console.log(data)})
    </script>
    <h1></h1>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

但返回导航器(Safari)是:

[错误] Access-Control-Allow-Origin 不允许 Origin null。[错误]由于访问控制检查,Fetch API 无法加载http://127.0.0.1:8000/ 。[错误] 无法加载资源:Access-Control-Allow-Origin 不允许 Origin null。(127.0.0.1,第 0 行)[错误] 未处理的承诺拒绝:类型错误:Access-Control-Allow-Origin 不允许 Origin null。(匿名函数)promiseReactionJob

javascript python fastapi

2
推荐指数
1
解决办法
1万
查看次数

如何连接 Vue.js 作为前端和 Fastapi 作为后端

我正在 Jobs Portal 上构建一个项目,我需要 Vue 作为前端,Fastapi 作为后端(添加、删除更新)。我想知道我是否可以将这两者都连接起来。

vue.js fastapi

2
推荐指数
1
解决办法
6131
查看次数

FastAPI docker-compose 找不到文件错误

我必须运行一个由full-stack-fastapi-postgresql生成的项目,并且我陷入了启动应用程序的第一步:docker-compose up -d抛出 FileNotFoundError。
我很确定这不是一个难题或问题,只是我错过了一些东西,但我不知道为什么。查看命令运行版本,我很确定我的错误就在这里。

版本:

Docker version 19.03.13, build 4484c46
docker-compose version 1.27.4, build unknown
Poetry version 1.1.4

运行的命令:

pip install cookiecutter

openssl rand -hex 32在上面的部分中,我启动了下载并响应 writed 等所有要求(我刚刚输入“测试”作为名称,以及每个询问的密码的结果)

$ cookiecutter https://github.com/tiangolo/full-stack-fastapi-postgresql
You've downloaded /Users/jojomoon/.cookiecutters/full-stack-fastapi-postgresql before. Is it okay to delete and re-download it? [yes]: yes
project_name [Base Project]: Test
project_slug [test]: 
domain_main [test.com]: 
domain_staging [stag.test.com]: 
docker_swarm_stack_name_main [test-com]: 
docker_swarm_stack_name_staging [stag-test-com]: 
secret_key [changethis]: 1280bf10bc3ebdf435834b2fc98e098144700bd27dfc43f62c2dcdd52741a5ac
first_superuser [admin@test.com]: 
first_superuser_password [changethis]: 81ec188f2f509483aeb7d877376220e81b5e4e1694fc4b1ee11028c923e340e8
backend_cors_origins [["http://localhost", "http://localhost:4200", "http://localhost:3000", "http://localhost:8080", "https://localhost", "https://localhost:4200", …
Run Code Online (Sandbox Code Playgroud)

python docker docker-compose cookiecutter fastapi

2
推荐指数
1
解决办法
2272
查看次数

使用 FastAPI 从 get 请求添加更多数据

我开始在 python 和 sqlalchemy 中使用 FastAPI 构建一个 api:这是模型的一部分:

class Game(Base):
    __tablename__ = "games"

    id = Column(Integer, primary_key=True, index=True)
    league_id = Column(Integer)
    radiant_score = Column(Integer)
    dire_score = Column(Integer)
    duration = Column(Integer)
    is_valid = Column(Boolean, default=True)

    playerstats = relationship("PlayerStat", back_populates="match")


class PlayerStat(Base):
    __tablename__ = "playerstats"

    match_id = Column(Integer, ForeignKey("games.id"), primary_key=True)
    slot = Column(Integer, primary_key=True)
    hero_id = Column(Integer, ForeignKey("heros.id"))
    num_kills = Column(Integer, default=None)
    isRadiant = Column(Boolean, default=None)

    match = relationship("Game", back_populates="playerstats")
    heros = relationship("Hero", back_populates="playerstats")
Run Code Online (Sandbox Code Playgroud)

之后,我为 pydantic 创建模式/模型(请原谅长部分):

    class PlayerStatBase(BaseModel):
    slot: int
    hero_id: …
Run Code Online (Sandbox Code Playgroud)

database api sqlalchemy python-3.x fastapi

2
推荐指数
1
解决办法
1875
查看次数

如何在 FastAPI POST 请求中同时添加文件和 JSON 正文?

具体来说,我希望以下示例能够正常工作:

from typing import List
from pydantic import BaseModel
from fastapi import FastAPI, UploadFile, File


app = FastAPI()


class DataConfiguration(BaseModel):
    textColumnNames: List[str]
    idColumn: str


@app.post("/data")
async def data(dataConfiguration: DataConfiguration,
               csvFile: UploadFile = File(...)):
    pass
    # read requested id and text columns from csvFile
Run Code Online (Sandbox Code Playgroud)

如果这不是 POST 请求的正确方法,请告诉我如何从 FastAPI 中上传的 CSV 文件中选择所需的列。

python http http-post pydantic fastapi

2
推荐指数
3
解决办法
1659
查看次数

如何在调试模式下运行fastapi项目在vscode中自动重新加载

从 fastapi python 开始。

这就是我如何连接我的服务器

class Server:
    def __init__(self):
        self.app = FastAPI()

    def runServer(self, host: str, port: int,is_dev:bool):
        uvicorn.run(self.app, host=host, port=port,debug=is_dev)


if __name__ == "__main__":
    server = Server()
    # read the environment variables
    host: str = os.environ['host']
    port: int = int(os.environ['port'])
    is_dev: bool = bool(os.environ['dev'])

    server.runServer(host, port, is_dev)
Run Code Online (Sandbox Code Playgroud)

如果我进行任何更改,这会启动服务器,但不会在自动重新加载模式下运行。

即使我试过

uvicorn.run(self.app, host=host, port=port, reload=is_dev)
Run Code Online (Sandbox Code Playgroud)

我想重新加载不是一种选择,从而导致服务器中断。

我尝试--reload在launch.json中传递args但仍然无法正常工作

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: …
Run Code Online (Sandbox Code Playgroud)

python debugging visual-studio-code fastapi

2
推荐指数
1
解决办法
2053
查看次数

FastAPI (Python) 为什么我收到“不支持的升级请求”。使用 POST 请求?

我在 Flask 和 FastAPI 上有类似的应用程序。当我使用 Flask 执行此 curl 请求时,没问题:

没有 TLS:

curl -X POST -H "Content-Type: application/json" -d '{"method": "account.auth"}' http://X.X.X.X:5050/

{"error":0,"result":{"token":"XXX"}}
Run Code Online (Sandbox Code Playgroud)

使用 TLS:

curl -X POST -H "Content-Type: application/json" -d '{"method": "account.auth"}' https://example.com:8443/api/

{"error":0,"result":{"token":"XXX"}}
Run Code Online (Sandbox Code Playgroud)

!!!但是使用 FastAPI 我得到了另一个结果:

没有 TLS:

curl -X POST -H "Content-Type: application/json" -d '{"method": "account.auth"}' http://X.X.X.X:5050/

{"error":0,"result":{"token":"XXX"}}
Run Code Online (Sandbox Code Playgroud)

使用 TLS:

curl -X POST -H "Content-Type: application/json" -d '{"method": "account.auth"}' https://example.com:8443/api/

Unsupported upgrade request.
Run Code Online (Sandbox Code Playgroud)

如何解决“不支持的升级请求”问题?还有,这是什么?Flask 正常使用它。

python fastapi

2
推荐指数
2
解决办法
1253
查看次数