Eine Abhängigkeit durch abhängig () und ein Schema beziehenPython

Python-Programme
Anonymous
 Eine Abhängigkeit durch abhängig () und ein Schema beziehen

Post by Anonymous »

Ich habe eine Situation, in der ich den aktiven Benutzer gegen einen der Werte genehmigen möchte (

Code: Select all

Organization
) In einer Fastapi -Route. Wenn ein Objekt eines bestimmten Typs eingereicht wird, einer der Schlüssel (

Code: Select all

organization_id
) sollte vorhanden sein und der Benutzer sollte überprüft werden, ob er Zugriff auf die Organisation hat.

Code: Select all

def get_organization_from_body(organization_id: str = Body(None),
user: User = Depends(get_authenticated_user),
organization_service: OrganizationService = Depends(get_organization_service),
) -> Organization:
if not organization_id:
raise HTTPException(status_code=400, detail='Missing organization_id.')

organization = organization_service.get_organization_for_user(organization_id, user)

if not organization:
raise HTTPException(status_code=403, detail='Organization authorization failed.')

return organization
Dies funktioniert einwandfrei, und wenn der API -Endpunkt in der Anforderung eine Organisation über eine organisation_id -Staste erwartet

Code: Select all

@router.post('', response_model=Bundle)
async def create_bundle([...]
organization: Organization = Depends(get_organization_from_body),
) -> Model:

... Und wenn der Benutzer keinen Zugriff auf die Organisation hat, wird eine 403 -Ausnahme erhöht. Mein erster Versuch war also eine JSON -Anfrage als: < /p>

Code: Select all

{
'name': generated_name,
'organization_id': created_organization['id_key']
}
< /code>
und Hinzufügen meines eingehenden pydantischen Modells: < /p>
@router.post('', response_model=Bundle)
async def create_bundle(bundle: BundleCreate,
organization: Organization = Depends(get_organization_from_body),
[...]
) -> BundleModel:
[...]
return bundle
< /code>
Das Ergebnis ist dasselbe, ob das pydantische Modell /Schema organisation_id < /code> als Feld enthält oder nicht: < /p>
class BundleBase(BaseModel):
name: str

class Config:
orm_mode = True

class BundleCreate(BundleBase):
organization_id: str
client_id: Optional[str]
.. aber wenn ich meine Get_organization_from_body Abhängigkeit einführe, sieht Fastapi, dass ich eine andere Abhängigkeit habe, die sich auf ein Körperfeld bezieht, und die Beschreibung des Bündels. organisation_id ist Teil des Bundle Beschreibung, es sollte dort leben. Wenn möglich).

Code: Select all

{'detail': [{'loc': ['body', 'bundle'], 'msg': 'field required', 'type': 'value_error.missing'}]}
und zu Recht, wenn ich den Namen in einem Bundle Taste stattdessen bewegte:

Code: Select all

{
'bundle': {
'name': generated_name,
},
'organization_id': created_organization['id_key']
}
...My Test Pässe und die Anfrage ist erfolgreich. mein Ausgangsformat näher.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post