Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
  • Jan 26 22:06
    github-actions[bot] commented #2706
  • Jan 26 22:05
    codecov[bot] commented #2706
  • Jan 26 22:05
    codecov[bot] commented #2706
  • Jan 26 22:03
    Cleptomania opened #2706
  • Jan 26 20:56
    felixdittrich92 commented #2632
  • Jan 26 19:10
    Kludex commented #2705
  • Jan 26 18:57
    Cleptomania closed #2705
  • Jan 26 18:57
    Cleptomania commented #2705
  • Jan 26 18:53
    Kludex commented #2705
  • Jan 26 18:53
    Kludex commented #2705
  • Jan 26 18:34
    Cleptomania edited #2705
  • Jan 26 18:34
    Cleptomania edited #2705
  • Jan 26 18:34
    Cleptomania edited #2705
  • Jan 26 18:34
    Cleptomania edited #2705
  • Jan 26 18:34
    Cleptomania labeled #2705
  • Jan 26 18:34
    Cleptomania opened #2705
  • Jan 26 18:29
    Kludex commented #2704
  • Jan 26 18:00
    github-actions[bot] commented #2704
  • Jan 26 17:58
    codecov[bot] commented #2704
  • Jan 26 17:57
    codecov[bot] commented #2704
Jan Szumiec
@ngilles so i get this stack trace which would be a result of pydantic's schema indexing scheme:
File "/Users/jps/.virtualenvs/backend/lib/python3.8/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/Users/jps/.virtualenvs/backend/lib/python3.8/site-packages/fastapi/applications.py", line 128, in openapi
    return JSONResponse(self.openapi())
  File "/Users/jps/.virtualenvs/backend/lib/python3.8/site-packages/fastapi/applications.py", line 106, in openapi
    self.openapi_schema = get_openapi(
  File "/Users/jps/.virtualenvs/backend/lib/python3.8/site-packages/fastapi/openapi/utils.py", line 343, in get_openapi
    definitions = get_model_definitions(
  File "/Users/jps/.virtualenvs/backend/lib/python3.8/site-packages/fastapi/utils.py", line 28, in get_model_definitions
    model_name = model_name_map[model]
KeyError: <class 'backend.refcheck.schemas.PersonalStep.Output'>
this happens very early on a call to the openapi.json endpoint
Jan Szumiec
ok - yeah this is a problem in pydantic. thanks for being my rubber duck
guys i am having a hard time understanding the auth2

I can successfully add new student data

@router.post("/",response_description="Student data added into the database")
async def add_student_data(student: StudentSchema= Depends(),file: UploadFile=File(None)):

I have made upload file as optional.

class StudentSchema(BaseModel):
    fullname:str = Field(...)
    email: EmailStr = Field(...)
    course_of_study: str = Field(...)
    year: int = Field(...,gt=0,lt=9)
    gpa: float = Field(..., le= 4.0)
    image: Optional[str]

For crud operation, I want to upload file if not added previously, replace new one if added or want to left blank"null"

class UpdateStudentModel(BaseModel):
    fullname: Optional[str]
    email: Optional[EmailStr]
    course_of_study : Optional[str]
    year : Optional[int]
    gpa: Optional[float]
    image: Optional[str]

In route

async def update_student_data(id:str,req:UpdateStudentModel=Depends(),file: UploadFile=File(None)):

Everytime it prompts error when i left blank (for file upload) during update

Did not find CR at end of boundary (40)

In swagger

  "detail": "There was an error parsing the body"
Erik Seglem
@marco714 You don't provide enough information to really help. You are missing large chunks of the code from https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/ and don't provide any information about the error you are seeing. How are you testing it? Are you passing the token as part of your authentication header?
Erik Seglem
@himalacharya Try file: Optional[UploadFile]=File(None)? If you aren't providing the file it probably isn't happy.
@eseglem Same error persists
Here is the part of code of update operation
async def update_student_data(id:str,req:UpdateStudentModel=Depends(),file: Optional[UploadFile]=File(None)):
    req={k:v for k ,v in req.dict().items() if v is not None}
1 reply
Erik Seglem
Do you have the stack trace for the error? Is it erroring in the print?
Ekundayo Abiona
router.add_api_route("/items", list_items, methods=["GET"])
@Kludex Thanks, wanted to use this majorly for code organisation, so I can have a file that majorly define routes, and then have another file for the functions
Erik Seglem

@ekundayo-ab Have you looked at https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/app for how they do it there? The api routes have just logic to deal with inputs, and some permissions. And then the meat of the logic is separate in crud. I like to have all the routes defined with the definition of the endpoint together, and then logic elsewhere. So you can end up with something like this:

@app.put("/items/{item_id}", response_model=ItemResponse)
async def update_item(item_id: int, item: Item = Body(..., embed=True)):
    return crud.item.update_item(id, item)

Its still just the routes, but it tells you input / output. So its a bit more friendly when reading the code.

1 reply
Ádám Lippai
Can I force FastAPI to use a ProcessPoolExecutor instead of the default ThreadPoolExecutor for sync request handlers? (I have issue with a module not releasing the GIL, locking up the server)
Lucas Emanuel
Hey guys, I'm implementing tests with pytest for my routes and I can't figure out why I'm receiving an error saying that I'm not sending the required field for that route
Here is the test
def test_create_area(client, fake_login_superuser):
    response = client.post(
            "descricao": "Agronomia"
    assert response.status_code == 200
The error I get is this
{'detail': [{'loc': ['body', 0], 'msg': 'Expecting value: line 1 column 1 (char 0)', 'type': 'value_error.jsondecode', 'ctx': {'msg': 'Expecting value', 'doc': 'descricao=Agronomia', 'pos': 0, 'lineno': 1, 'colno': 1}}]}
This is what my pydantic model looks like
class AreaCreate(BaseModel):
    descricao: str

    class Config:
        orm_mode = True
Oh, and this is the route
@r.post("/areas", response_model=Area, response_model_exclude_none=True)
async def area_create(
    request: Request,
    area: AreaCreate,
    Create a new area
    return await create_area(db, area)
Lucas Emanuel
I have no clue why the jsondecode error, since its a valid dict on data, aswell as that 'expecting value', I don't know what value that is
Louis Cha
Hi guys, I currently have my lambda handler set up using FastAPI middleware decorator and Mangum like the following:
from routers import router

app = FastAPI()


# Handler for api calls
async def api_process(request: Request, call_next):
        if path in endpoints_list:
            # ... validation logics here ...

            response = await call_next(request) # calls the endpoints with corresponding path

            # ... process the response ...

   except Exception as ex:
        # ... process exception ...

handler = Mangum(app)
And I have several endpoints which gets called from the above lambda function, do their job and return the response accordingly like this:
def sample_endpoint(request: Request):
       query_params= request.query_params
       body = request.body
       # ....
       return Response(
           status_code = 200,
   except Exception as ex:
        # ... process exception ...
Instead of accepting generic Request object and extract query_params and body data myself, I would like to use more explicit parameters such as item_id: int, customer_name: str, and so on for each endpoints. Since I am using middleware decorator for the lambda function to forward the request to path provided, I am not sure how to do it other than passing in the whole Request object from lambda function. Would this be possible?
Shiridi Sai Prasad
How do i retrieve multiple files from request form? I am uploading multiple files in a POST request. how do i save these files using request object?
Nihal Thukarama Rao
Hi , given a fastapi Response , how does one verify that a cookie has been set in it?
Valon Januzaj
@nihal-rao log the request and response

=== === ===
Hello Here!

a bit of topic question, but I still try it here:

in setup.py i neeed the keras-contrib@https://github.com/keras-team/keras-contrib.git as REQUIRES_INSTALL package.
Everyting works fine when installing with pip -r ..., BUT when tha package is built as wheel, then

ERROR: Could not find a version that satisfies the requirement keras-contrib (from superduperpack==0.3.5) (from versions: none)
ERROR: No matching distribution found for keras-contrib (from superduperpack==0.3.5)

Help appreciated!

Akhilesh Kumar
Hi everyone, how is everyone doing?
I have a question, it will be nice if some one can point me in the right direction.
How can share some global variable among different workers of the fastapi
I have lot of CPUs in my machine and I need multiple workers to utilize all the CPUs efficiently.
However when I am using multiple workers, I am not able to share the globals variables among different workers..
Thanks for your help.
@Max2ben_twitter redis?
Akhilesh Kumar
Thanks @madkote I have not tried redis but I can give it a try.
is there any other solution for sharing the variables?
Nicolas Gilles
redis will work, and as a bonus, even if you launch further instances (even on different machines)
@Max2ben_twitter google -> "python sharing the variables"
Nicolas Gilles
@Max2ben_twitter depends on what kind of global variable you're looking for.... a constant? or mutable?
Akhilesh Kumar
its a mutable
Nicolas Gilles
I'm not sure how workers are isolated ... I'm assuming different processes... so maybe the solution is shared memory or something like that, in which case, redis might actually be an easier solution
if they are just threads, well, an object and lock and you should be fine
Akhilesh Kumar
ok. Thanks @ngilles and @madkote
Workers are processes
Nicolas Gilles
though not sure how to mix that with the async nature actually :D
Alexandre Gerona
Anyone has an idea how to make mypy happy in this instance?
Marcelo Trylesinski
can I see the two classes involved on that union? @alecgerona
Valon Januzaj
@alecgerona I also had similar issues
What you have to do is to look at the infered return types, and then to do some checking or assertion ( not recommended) because it can cause problems in prod.
Do some "strict" type checking yourself and then mypy knows that it had passed that kind of check, and the error will dissapear

@eseglem thank you for replying to me
this is the error
?[33mWARNING?[0m: Detected file change in 'main.py'. Reloading...
email-validator not installed, email fields will be treated as str.
To install, run: pip install email-validator
Process SpawnProcess-5:
Traceback (most recent call last):
File "c:\users\rquitain\appdata\local\programs\python\python38\lib\multiprocessing\process.py", line 315, in _bootstrap
File "c:\users\rquitain\appdata\local\programs\python\python38\lib\multiprocessing\process.py", line 108, in run
self._target(self._args, *self._kwargs)
File "C:\Users\rquitain\AppData\Roaming\Python\Python38\site-packages\uvicorn\subprocess.py", line 61, in subprocess_started
File "C:\Users\rquitain\AppData\Roaming\Python\Python38\site-packages\uvicorn\main.py", line 407, in run
File "c:\users\rquitain\appdata\local\programs\python\python38\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "C:\Users\rquitain\AppData\Roaming\Python\Python38\site-packages\uvicorn\main.py", line 414, in serve
File "C:\Users\rquitain\AppData\Roaming\Python\Python38\site-packages\uvicorn\config.py", line 300, in load
self.loaded_app = import_from_string(self.app)
File "C:\Users\rquitain\AppData\Roaming\Python\Python38\site-packages\uvicorn\importer.py", line 23, in import_from_string
raise exc from None
File "C:\Users\rquitain\AppData\Roaming\Python\Python38\site-packages\uvicorn\importer.py", line 20, in import_from_string
module = importlib.import_module(module_str)
File "c:\users\rquitain\appdata\local\programs\python\python38\lib\importlib__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File ".\main.py", line 2, in <module>
from fastapi.responses import JSONResponses

ModuleNotFoundError: No module named 'fastapi.responses'

ran pip list and found these versions
(ConvergedApp) C:\Users\rquitain\Documents\GitHub\fbprophet-forecasting-api>pip list
uvicorn 0.12.1
fastapi 0.61.1

fbprophet 0.7.1

also yes im using the environment i made but installed there firstly fast api and ran pip list on that environment