Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • 06:10
    github-actions[bot] commented #2058
  • 06:08
    codecov[bot] commented #2058
  • 06:08
    codecov[bot] commented #2058
  • 06:06
    codecov[bot] commented #2058
  • 06:06
    codecov[bot] commented #2058
  • 06:06
    tokusumi synchronize #2058
  • 06:05
    github-actions[bot] commented #2058
  • 06:02
    codecov[bot] commented #2058
  • 06:02
    codecov[bot] commented #2058
  • 06:01
    codecov[bot] commented #2058
  • 06:01
    codecov[bot] commented #2058
  • 06:00
    tokusumi synchronize #2058
  • Jan 16 19:54
    gocreating opened #2662
  • Jan 16 19:54
    gocreating labeled #2662
  • Jan 16 16:24
    matan1008 edited #2637
  • Jan 16 16:13
    WilliamDEdwards commented #2599
  • Jan 16 15:13
    acnebs commented #1079
  • Jan 16 15:09
    acnebs commented #1079
  • Jan 16 14:52
    perezzini commented #657
  • Jan 16 14:51
    perezzini commented #657
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)):

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

@router.put("/{id}")
async def update_student_data(id:str,req:UpdateStudentModel=Depends(),file: UploadFile=File(None)):
    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}")
async def update_student_data(id:str,req:UpdateStudentModel=Depends(),file: Optional[UploadFile]=File(None)):
    print(file)
    req={k:v for k ,v in req.dict().items() if v is not None}
1 reply
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.

1 reply
Á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?
Shiridi Sai Prasad
@saiprasadufl_gitlab
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
@madkote

=== === ===
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
@Max2ben_twitter
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.
RES
@madkote
@Max2ben_twitter redis?
Akhilesh Kumar
@Max2ben_twitter
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
@madkote
@Max2ben_twitter google -> "python sharing the variables"
Nicolas Gilles
@ngilles
@Max2ben_twitter depends on what kind of global variable you're looking for.... a constant? or mutable?
Akhilesh Kumar
@Max2ben_twitter
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
@Max2ben_twitter
ok. Thanks @ngilles and @madkote
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
?[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
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
config.load()
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

Ak4zh
@Ak4zh
Can anyone help me deploy https://github.com/long2ice/fastapi-admin frontend and backend on a single heroku app.
Valon Januzaj
@vjanz
@ruselljane please format your snipet..