## Where communities thrive

• Join over 1.5M+ people
• Join over 100K+ communities
• Free without limits
##### Activity
• 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
@jasiek
@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
@jasiek
ok - yeah this is a problem in pydantic. thanks for being my rubber duck
marco714
@marco714
guys i am having a hard time understanding the auth2
Himal
@himalacharya

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)):

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

@router.put("/{id}")
print(file)

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
@eseglem
@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
@eseglem
@himalacharya Try file: Optional[UploadFile]=File(None)? If you aren't providing the file it probably isn't happy.
Himal
@himalacharya
@eseglem Same error persists
Here is the part of code of update operation
@router.put("/{id}")
print(file)
req={k:v for k ,v in req.dict().items() if v is not None}
Erik Seglem
@eseglem
Do you have the stack trace for the error? Is it erroring in the print?
Ekundayo Abiona
@ekundayo-ab
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
@eseglem

@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.

Ádám Lippai
@alippai
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
@kseikyo
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(
"/api/v1/areas",
data={
"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,
db=Depends(get_db),
):
"""
Create a new area
"""
return await create_area(db, area)
Lucas Emanuel
@kseikyo
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
@LouisJHC
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()

app.include_router(router)

# Handler for api calls
@app.middleware("http")
async def api_process(request: Request, call_next):
try:
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:
@router.get("/index")
def sample_endpoint(request: Request):
try:
query_params= request.query_params
body = request.body
# ....
return Response(
status_code = 200,
content=json.dumps(response_body)
)
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?
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
@nihal-rao
Hi , given a fastapi Response , how does one verify that a cookie has been set in it?
Valon Januzaj
@vjanz
@nihal-rao log the request and response
RES

=== === ===
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..
RES
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
@ngilles
redis will work, and as a bonus, even if you launch further instances (even on different machines)
RES
Nicolas Gilles
@ngilles
@Max2ben_twitter depends on what kind of global variable you're looking for.... a constant? or mutable?
Akhilesh Kumar
its a mutable
Nicolas Gilles
@ngilles
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
Workers are processes
Nicolas Gilles
@ngilles
though not sure how to mix that with the async nature actually :D
Alexandre Gerona
@alecgerona
Anyone has an idea how to make mypy happy in this instance?
Marcelo Trylesinski
@Kludex
can I see the two classes involved on that union? @alecgerona
Valon Januzaj
@vjanz
@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
ruselljane
@ruselljane

@eseglem thank you for replying to me
this is the error
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
self.run()
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
target(sockets=sockets)
File "C:\Users\rquitain\AppData\Roaming\Python\Python38\site-packages\uvicorn\main.py", line 407, in run
loop.run_until_complete(self.serve(sockets=sockets))
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
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