Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • 14:25
    brnosouza commented #3594
  • 14:25
    thunderamur commented #3018
  • 14:23
    thunderamur commented #3018
  • 14:22
    github-actions[bot] commented #3950
  • 14:22
    github-actions[bot] commented #3950
  • 14:21
    github-actions[bot] commented #3950
  • 14:19
    tiangolo synchronize #3950
  • 14:19

    tiangolo on https-guide

    👷 Trigger CI (compare)

  • 14:15
    github-actions[bot] commented #3950
  • 14:15
    github-actions[bot] commented #3950
  • 14:13
    github-actions[bot] commented #3950
  • 14:10
    tiangolo auto_merge_enabled #3950
  • 14:09
    tiangolo opened #3950
  • 14:09

    tiangolo on https-guide

    📝 Upgrade HTTPS guide with mor… (compare)

  • 13:11
    griseau closed #3912
  • 11:38
    theo-brown opened #3949
  • 11:38
    havardthom commented #1359
  • 09:54
    synodriver commented #3128
  • 09:53
    synodriver commented #3128
  • 09:51
    synodriver commented #3128
Marcelo Trylesinski
@Kludex
have u created a new env? maybe it's taking time to resolve them
5 replies
Thomas Griseau
@griseau

Hello guys,
I'm working with FastAPI and I'm facing issue when retrieving records from a foreign key. I have two models :

class AnalysisOutput(BaseCommon):
    id = Column(Integer, primary_key=True, index=True, nullable=False)
    analysis_row_uuid = Column(UUID(as_uuid=True), index=True, unique=True, nullable=False, default=uuid.uuid4)
    legal_name = Column(String, nullable=False)
    user_assigned = Column(Integer, ForeignKey("users.id"), nullable=True)

    refined_supplier = relationship(
        "RefinedSupplier", cascade="all,delete", back_populates="analysis_output", uselist=False
    )
    user = relationship("User", back_populates="analysis_output")

class User(BaseCommon):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True, nullable=False)
    email = Column(String, unique=True, index=True, nullable=False)
    username = Column(String, unique=True, nullable=False)
    creation_datetime = Column(DateTime, nullable=False)

    analysis_output = relationship("AnalysisOutput", back_populates="user")
    refined_supplier = relationship("RefinedSupplier", cascade="all,delete", back_populates="user")
    refined_supplier_index = relationship("RefiningUserIndex", cascade="all,delete", back_populates="user")

When I try to retrieve records from AnalysisOutput linked to User I have the following error :

pydantic.error_wrappers.ValidationError: 6 validation errors for AnalysisOutput
response -> 0 -> user_assigned -> email
  field required (type=value_error.missing)
response -> 0 -> user_assigned -> username
  field required (type=value_error.missing)
response -> 0 -> user_assigned -> id
  field required (type=value_error.missing)
response -> 1 -> user_assigned -> email
  field required (type=value_error.missing)
response -> 1 -> user_assigned -> username
  field required (type=value_error.missing)
response -> 1 -> user_assigned -> id
  field required (type=value_error.missing)

If I only retrieve the id of the foreign key it works well. User is also linked to another table called RefinedSupplier, and it works like a charm.
Any help on the subject would be appreciated, thanks :)

Alex Alexapolskiy
@metawake
Hi guys. Is TestClient capable of accepting pytest fixtures that are defined before TestClient was created? Or TestClient accepts mocks only via app.dependency_overrides attribute?
1 reply
Dirk Brand
@dirkbrnd
Hi all, I want to do something a bit weird. I want to have a "version" header that allows the user to indicate a version of an endpoint to consume. Say the endpoint is /users, I want to have two different versions of /users. My idea was to internally make the endpoints /users/v1/ and /users/v2/, then when someone calls /users I have middleware to check the header and append the correct suffix to the request (i.e. modify the path). Is that sensible? I can't seem to get it to work.
I don't want to publically add the version to the URL, I only want to do it via header.
Robert Hafner
@tedivm
I've run into an issue around redirect. My FastAPI container is HTTP, but there's an HTTPS termination setup. When FastAPI responds with a redirect (specifically in the case where it's trying to normalize slashes in the path) it's returning http instead of https like I would prefer. Is there a good way to handle that?
2 replies
Nick
@n1ckdm
when using OAuth2PasswordBearer is it possible to have a token URL point to an external endpoint?
1 reply
image.png
image.png
e.g. I have two fastAPI services running in docker containers, one is a "user_manager" responsible for issuing tokens and the other is trying to use that service to Authenticate a user by first retrieving a token. It works, but doesn't work in the OpenAPI docs:
1 reply
Кто Я
@faq616_twitter

Guys can you help pls. i have weird issue when trying upload file from react app here is my handler and request from react. server throw 400 bad request without details. When i send request from postman or swagger everything ok, but from react cause error

@router.post("/upload-photo/{contractor_id}", response_model=MsgSchema)
async def upload_contractor_photo(
        contractor_id: int,
        photo: UploadFile = File(...),
        current_user: User = Depends(get_current_active_user),
):
    """
    Upload contractor photo.\n
    allowed formats jpg, png\n
    max file size: 2mb
    """
    print("DO NOTHING")
    return {"msg": photoUploaded}
updatePhoto: async function (photo, contractorId) {
        const formData = new FormData();
        formData.append("photo", photo, photo.name);
        console.log(photo);

        const response = await fetch(
            ${config.api.url}/api/${config.api.version}/contractors/upload-photo/${contractorId},
            {
                method: "POST",
                headers: {
                    "Access-Control-Allow-Origin": "*",
                    Authorization: "Bearer " + token,
                    "Content-Type": "multipart/form-data",
                },
                body: formData,
            }
        );
        response.json().then(function (responseData) {
            console.log(responseData);
        });
    },

error

 INFO:     ******:0 - "POST /api/v1/contractors/upload-photo/1 HTTP/1.1" 400 Bad Request

heroku[router]: sock=backend at=error code=H18 desc="Server Request Interrupted" method=POST path="/api/v1/contractors/upload-photo/1" host=****.herokuapp.com request_id=98cb4d01-6163-4b44-a2bf-d9ae0b9a73cd fwd="*****" dyno=web.1 connect=0ms service=63ms status=503 bytes=273 protocol=https
Ulan Seitkaliyev
@Inverseit
Guys, why fastapi don't see my post request body: fastapi.exceptions.RequestValidationError: 2 validation errors for Request body -> username field required (type=value_error.missing) body -> password field required (type=value_error.missing)
Even if the request.json() is is {'username': 'The is username', 'password': '123'}
Marcelo Trylesinski
@Kludex
can we see the way you're calling it?
hichhiker
@hichhiker:matrix.org
[m]
Hey, when setting up authentication, is it possible to turn it on by default for all endpoints or do I have to add a dependency on every single endpoint? (I bet you this one of the most common noob questions :-D )
hichhiker
@hichhiker:matrix.org
[m]
nvm, figured it out
3 replies
JamieYong
@JamieYong

Hello, friends.
I wanted to ask you a question.
The bottom is my websocket code.

@router.websocket("/ws/{room_id}/")
async def websocket_endpoint(websocket: WebSocket, room_id: str, apptoken: str, response: Response):
    pass # secret code

When you use the code below, the websocket doesn't work on https.
Is there anyone who can tell me the reason?

Klement Alexander
@AlexanderKlement

Hey,
i have a question, and i hope someone knows this:

I have a really simple relationship in fastapi:
workloads = relationship("Workload", back_populates="job")

everything works fine, unless the workload is empty, then my pydantic scheme returns:
field required (type=value_error.missing)

i know why, because the schema is
workload: List[workload_schema.Workload]

it would work if was this way
workload: Optional[List[workload_schema.Workload]]

but i wanted sqlalchemy to return an empty list instead of None. Is this possible?
Thanky you in advance

Alex Grönholm
@agronholm
@AlexanderKlement getting back None does seem counterintuitive
Klement Alexander
@AlexanderKlement
@agronholm Yes, i felt the same. Am i doing something wrong, or is this the default behaviour?
Alex Grönholm
@agronholm
gut says no, but I'm not sure – I'll check when I have the time
José Manteigueiro
@jmanteigueiro

Hey there,

I have a class instance (lets call it Values), that opens a websocket connection and has a field (lets call it lastValue) that should have the last value fetched by the WS connection (N fetches per second). How can I have this running on the background without interfering with the rest of FastAPI functioning, so that when I use a route (lets say /fetchLastValue) it returns Values.lastValue?

Can I achieve this with FastAPI or do I need to use Celery?

Alex Grönholm
@agronholm
I think it should be possible
fbpyr
@fbpyr:tchncs.de
[m]
@jmanteigueiro: for sure no celery needed. we use something similar over here, fastapi async and websocket connection to inform about updates - have not seen any interferences there. 😌
when I started to explore that I found the fastapi docs on ws chat example very useful:
https://fastapi.tiangolo.com/zh/advanced/websockets/
1 reply
linrongbin16
@linrongbin16
Hi, on local development environment, firefox could pass CORS, but chrome/edge cannot pass. Does anyone has the same issue?
web app host on localhost:8084, fastapi on localhost:8081
fbpyr
@fbpyr:tchncs.de
[m]
@jmanteigueiro: ah I see. right, our use case is not intensive at all. 🙂
1 reply
Klement Alexander
@AlexanderKlement
@linrongbin16 Maybe you have some settings in firefox to not mind cors. I would invest the time and install https://fastapi.tiangolo.com/tutorial/cors/#use-corsmiddleware .
@agronholm Thank you, would really appreciate a solutions. Otherwise i'll have to work with Optionals
@linrongbin16 I had a few connection issues, which chrome identified as CORS errors, where in reality i had a crash on the backend, and therefore no data was delivered
hichhiker
@hichhiker:matrix.org
[m]
Can FastAPI annotations be done in class code?
Ryan
@r-kells

Quick question about FastAPI's docs, which are amazing.

Im curious how this templating of code block works in markdown?
Ex. {!../../../docs_src/additional_responses/tutorial001.py!}

hichhiker
@hichhiker:matrix.org
[m]
Ok, so if I have a dependencies=[x] option on the FastAPI() - is there a way to exclude a specific endpoint?
Dan Diephouse
@dandiep
I'm pretty new to FastAPI and Uvicorn (and am not a super guru in Python either), and have a hit a point where I'm stuck. I'm hitting one of my APIs, and the response is just "Internal Server Error". There is nothing in the console logs from uvicorn. Furthermore, I tried wrapping my API code in try/except and I was not able to catch an exception. Any ideas on how I can coax some logs out to actually see what the problem is?
I'm able to successfully invoke the same code from a Jupyter notebook, so it has to be some weird configuration error.
hichhiker
@hichhiker:matrix.org
[m]
FWIW, any time I hit "Internal Server Error" I see traces in the log - perhaps your log levels are too restrictive
most of the times it was because the data did not fit into the output model
(like some non-optional fields was null or not set)
Dan Diephouse
@dandiep
Logs are set to debug. I have been digging deeper... looks like maybe there is some circular dependency issue with dependency-injector
Ak4zh
@Ak4zh_gitlab
Does Deta supports fastapi background tasks?
I know the 10 seconds limit
4 replies
Theo Brown
@theo-brown
What's the correct way of passing a set/array as a parameter in a GET request?
3 replies
graingert
@graingert:matrix.org
[m]
you can also do a=1,2,3 or a=1&a=2&a=3 which html forms produce
1 reply
Adrian Garcia Badaracco
@adriangb
The former will give you a single string that you have to split. I believe the latter is technically undefined and depends on the web framework.
graingert
@graingert:matrix.org
[m]
An execution times out after 10s. Contact us for an increase (up to 20 seconds).
Websockets and long-running processes do not work on Micros. (examples: socket.io or Discord bots won't work)
Ah
Dan Diephouse
@dandiep

I'm trying to understand the proper way to manage sessions in something that is beyond just a toy app with FastAPI, SQLModel, SQL Alchemy and Dependency Injector. I am able to use a @contextmanager sucessfully for the simple case where it all happens in the endpoint definition, but I don't want my business logic tied into my API definitions - I want to keep clean separation. So what I'm trying to do is something more like this:

@router.get('/myapi')
@inject
def myapi(
    my_service1: MyService1 = Depends(Provide[Container.my_service1]),
    my_service2: MyService2 =  Depends(Provide[Container.my_service2]),
) -> str:
    my_service1.foo()
    my_service2.foobar()

Where both foo() and foobar() happen in the same session and everything commits after the whole API invocation is done. Thoughts on how I should manage this?

Should I store the session in the request state and fetch it that way? I thought I read somewhere that is not recommended with the @contextmanager approach though.
Dan Diephouse
@dandiep
ok, it appears I need to be using scoped_session. Just a question of how to do that AND use SQLModel.
Theo Brown
@theo-brown
how do I correctly parse a request that has parameters a=1,2,3 in fastapi?
Kostas Papadopoulos
@kostaspapad
Can you recommend a good folder project structure for a mid sized project?
NSVR
@SAIVENKATARAJU
Hi I am new to restapi and trying o build rest services using fast api. my question is there is any way to share variable between two routers. here, I want pipe_document whenever i hit find answer
@data.post("/readfileandstore/")
async def preprocess_file(file:UploadFile = File(...)):

     if 'txt' in file.filename:
          pipe_document=storefiledata.store_txt_data(file)



@data.post("/findanswer")
async def find_answer(data:dict):
     answers=[]
     question = data['question']
     logging.info(question)
     prediction_document = pipe_document.run(query=question, top_k_retriever=128, top_k_reader=2)
     answers.append(post_processing(prediction_document))

     return answers