Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • 14:51
    JinKazuya commented #771
  • 14:38
    levchik commented #1204
  • 14:21
    vincentsarago commented #596
  • 10:45
    mariacamilagl synchronize #1220
  • 10:25
    nsidnev commented #1219
  • 08:29
    samuelcolvin commented #1226
  • 08:14
    nsidnev commented #1219
  • 06:03
    tiangolo commented #1221
  • 06:02
    nskalis commented #963
  • 05:55
    github-actions[bot] commented on d4f3ca1
  • 05:54
    tiangolo commented #841
  • 05:54

    tiangolo on 0.54.1

    (compare)

  • 05:53
    github-actions[bot] commented on d4f3ca1
  • 05:51

    tiangolo on master

    :memo: Update release notes :bookmark: Release 0.54.1 (compare)

  • 05:43
    github-actions[bot] commented on a46bbc5
  • 05:42

    tiangolo on handle-setup-dbs

    (compare)

  • 05:41

    tiangolo on master

    :white_check_mark: Update datab… (compare)

  • 05:41
    tiangolo closed #1226
  • 05:39
    codecov[bot] commented #1226
  • 05:39
    codecov[bot] commented #1226
janvdvegt
@janvdvegt

When running locally, my main.py containers:

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")

And in Docker I tried both the prebuilt images with the COPY command and the right ENV variables or the base Python image and then running the command myself but they both run into this issue

I'm not entirely sure how to debug this issue or what could cause it
David Asaf
@davideasaf

@zero-shubham Thanks for the response. I ended up falling into what your screenshots showed a bit after I posted that. I'm still trying to accomplish this type of workflow compared to Marshmallow: marshmallow-code/flask-marshmallow#136

I know the 2 libraries aren't meant to be interchangeable, but it would be awesome if I could achieve the above in Pydantic

vjanz
@vjanz
Hey guys,
I have models seperated for each module, but when I try to do some api operation which includeUser I get this error:
sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class User->user, expression 'Item' failed to locate a name ("name 'Item' is not defined"). If this is a class name, consider adding this relationship() to the <class 'orex.user.m
odels.User'> class after both dependent classes have been defined.

I am sure that I have updated this with relationship notation:
user.py

class User(Base):
 id = Column(GUID, primary_key=True, default=uuid.uuid4)

item = relationship("Item", back_populates="user")

item.py

class Item(Base):
 id = Column(GUID, primary_key=True, default=uuid.uuid4)

user = relationship("User",back_populates="item")
What's your opinion or fix on this?
Nikhil M Jain
@NikhilMJain
How to specify that a query param can only have values defined in a Enum? And any other value should result in a validation error.
Maurício Eduardo Loschi Batista
@eddloschi
@NikhilMJain I believe that this is what you're looking for: https://fastapi.tiangolo.com/tutorial/path-params/#working-with-python-enumerations
vjanz
@vjanz

By the way, for the issue that I have posted above, If I go to User and write

from item import Item

Then it would work, but that's not the way this should work :(

Nikhil M Jain
@NikhilMJain
@eddloschi Thank you.
Akshay Verma
@aeroaks
Hi All, I am excited by FastAPI and want to use it for our next project where the service acts as a sort of microservice fetching data and processing it and saving the output to another service. There will definitely be Pandas and Dataframe related processing which would be called by an API. How can I run this type of processing to gain most advantage out of the async capabilities of the framework? Typically the process would be running self-contained as in no mutliprocessing or distributed computing just within a single process inside a docker container. What would be the best strategy to handle such loads with FastAPI?
Andreas Jung
@zopyx
Is there some way in FastAPI to implemented Flask's https://pythonise.com/series/learning-flask/python-before-after-request functionality? Usecase is to check some application specific headers for each request and for injecting some headers to the response.
Tihomir Totev
@tihomirptotev
Hi, @zopyx! I think you can use the custom http middleware (https://fastapi.tiangolo.com/tutorial/middleware/).
matrixbot
@matrixbot
vauxia When creating a router.post function, for /parent/{parent_id}/child, is there a way to somehow access or include the parent_id in the contents of data_in: Child?
vauxia So like, if the Child class has a required parent_id field, is there a way to get at it from the path before validation kicks in?
David Asaf
@davideasaf
@zopyx checkout FastAPI middleware https://fastapi.tiangolo.com/tutorial/middleware/
Sharath MK
@Sharathmk99
image.png

Hi Team. I wanted to use one POST endpoint to accept json or file as request body based on content-type. I have below code,

 @router.post("/{project_id}/models/{model_id}/predict", responses={200: {"content": {"application/pdf": {}}}})
    def post(self, project_id: ProjectId, model_id: ModelId, predict_data: PredictInputData,
             files: List[UploadFile] = File(...)) -> PredictResponse:

But i get only one value in Request Body drop down.
Requesting to please help @tiangolo

Tosin Mash
@takwas
Hi.
How can I achieve this, please?
class beautifulwrapper:

    def __init__(self, colour):
        self.colour = colour

    def __call__(self, f):

        def route_func(*args, **kwargs):
            print(f'\nWrapping route colourfully...')

            f(*args, **kwargs)

        return route_fun


@router.get("/")
@beautifulwrapper('colours')
def route_func(request: Request):

    return {'message': 'Works!'}
I'd like to decorate my route function but when I make requests I encounter this:
    "detail": [
        {
            "loc": [
                "query",
                "args"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        },
        {
            "loc": [
                "query",
                "kwargs"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}
dbf
@fullonic_gitlab
@takwas , I'm just starting with FastAPI, I can 't figure out right now what might be your problem. However looking at your code, your are decorating your route with the class it self, without initialized it first. Also, look's like the pattern with FastAPI should be using the class Depends, right?
Maybe you can adapt as explained here:
https://fastapi.tiangolo.com/tutorial/dependencies/classes-as-dependencies/
Anthony Lukach
@alukach
Question about Pydantic + OpenAPI: I have some pydantic classes in a my_model file called Create and Output. In OpenAPI output, they are only labelled as Create or Output. Is there a way to override that name when defining the class (without actually renaming the class) so I can get something like MyModelCreate?
David De Sousa
@dedsm
hey guys, not precisely fastapi related, more an asyncio stuff
but I'm creating a task with loop.create_task inside the startup event, I want that if that task raises an exception, the server shuts down, can't seem to find a way yet.
any ideas?
dbf
@fullonic_gitlab
@alukach I didn't understand you well, do you want to rename the name that appears on the OpenAPI docs? If is that, you can do it using summary as explained here:
https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#summary-and-description
If you only want to rename the class it self, without change it's name, you can create a new variable pointing to the class, in you case:
MyModelCreate = Create
And now you use the MyModelCreate directly instead of the Create class.
vjanz
@vjanz
Not the right place to ask guys, but is there any way to validate IBAN, inside a pydantic model?
RES
@madkote
@dedsm you can kill the process (if exception is raised at any time). If you need exception on startup then it is simpler.
David De Sousa
@dedsm
yeah I ended up doing that, adding a done_callback to the app, it feels wrong
Anthony Lukach
@alukach

@fullonic_gitlab to clarify, I enjoy using a pattern like schemas.item.Create as it makes it easy to import just the schemas module into my endpoints.py file and then reference the appropriate schemas. However, when doing this, the schemas are represented in my OpenAPI docs as Create, which doesn't describe their purpose very well. I'd love to be able to keep the same class name and import paths, but have them rendered as ItemCreate (or something similar) in the OpenAPI docs. I was hoping there would be a way to direct the OpenAPI docs to label my schema class differently than its class name.

So, to address your question: renaming the class isn't what I had hoped for because it would mean I would have to restructure how I reference those schemas in my api handlers.

Markku Laine
@mplaine_twitter

I have the following models and endpoint, whose output is shown below:

# Models
class UserCreate(BaseModel):
    name: str

class User(UserCreate):
    id: str

# Endpoint
@events_router.post("/demo", response_model=User)
async def create_user(user_in: UserCreate):
    user = User(**user_in.dict(), id=str(uuid.uuid4()))
    return user

# Output
{
    "name": "John Doe",
    "id": "0f3468e8-22d1-472a-ba11-92e8ed8d2b76"
}

How can I change the order of output fields so that id comes before name? According to https://pydantic-docs.helpmanual.io/usage/models/#field-ordering , Pydantic preserves the order of fields, but how to control that when dealing with inherited models?

Maurício Eduardo Loschi Batista
@eddloschi
Anybody tested fastapi + sqlalchemy under high load? When I benchmarked my code using wrk, several exceptions were thrown. I suspect it could be concurrency problems caused by sqlalchemy, but could also be something wrong with my code
RES
@madkote
@dedsm difficult to give a hint without knowing exact issue. Note: please use @ to address message explicitly.
David De Sousa
@dedsm
@madkote it is solved, but it doesn't feel right, but that's precisely one of the main selling points of trio
Ralph Soika
@rsoika

When I try to install fastapi via pip from my requirements.txt file I see the following error:

$ pip install -r requirements.txt
Collecting spacy<3.0.0,>=2.2.0 (from -r requirements.txt (line 1))
Collecting fastapi<1.0.0,>=0.53.0 (from -r requirements.txt (line 2))
  Could not find a version that satisfies the requirement fastapi<1.0.0,>=0.53.0 (from -r requirements.txt (line 2)) (from versions: )
No matching distribution found for fastapi<1.0.0,>=0.53.0 (from -r requirements.txt (line 2))

What does this mean? Is my pip version (9.0.1) outdated?

Noah
@J0XX0
@rsoika Try running:
pip3 install --upgrade pip
pip3 install fastapi==0.54.0
Sebastián Ramírez
@tiangolo
New release! :tada: :rocket:
(by FastAPI bot)

0.54.1

dbf
@fullonic_gitlab
@alukach Hi, it's possible to have a self contained code example? So would be easier to reproduce your problem and see if I can help you.
Leif Linse
@Leffe108
Am I blind or where is the API docs of FastAPI? I for example want to know which arguments that "Depends" have and want a dry API docs for FastAPI and not the guide docs.
As of now I need to dig the source in github (or clone fastapi and grep trough the sources). But maybe that is how it is.
vjanz
@vjanz
Hello guys, is there a way to populate database with sqlalchemy, while making migration..
For ex: I have a table that must be populated through a CSVFile, and my goal is when I run the migrations ex :alembic upgrade head, to make the migrations, and also to popullate with data one of my tables, that I specified, or I wrote some logic to get populated from a csv?
Patrick Düggelin
@Patdue
@Patdue Simple solution below if anyone comes across a similar problem.
#!/usr/bin/env/python3
import asyncio
import threading
import time

from fastapi import FastAPI, HTTPException

app = FastAPI()

sync_lock = threading.Lock()
async_lock = asyncio.Lock()


@app.get("/wait")
def wait(seconds: int = 1):
    if sync_lock.locked():
        raise HTTPException(503)

    with sync_lock:
        time.sleep(seconds)


@app.get("/async_wait")
async def async_wait(seconds: int = 1):
    if async_lock.locked():
        raise HTTPException(503)

    async with async_lock:
        await asyncio.sleep(seconds)
Salent Olivick
@Chise1
How to add fastapi-tags to my own projects?
vjanz
@vjanz
What kind of tags?
JinKazuya
@JinKazuya
is there a workaround for the openAPI docs to show the proper field name of a schema and not the alias?
for response schemas
Awanish Kumar
@MrAwanishKumar
Hi,
Is there any documentation available for fastapi with mysql database all operation like Select, Insert, Update and Delete. I have gone through lots of web surfing but did not find the Update part. Does any one know, please share link.
Thanks
azizhish
@azizhish
Hi, any detailed guides on implementing OAuth2 in an API that I built. I went through the tutorial but something more robust. Junior dev here so I'm quite stupid lol