Почему добавление пользовательской схемы openapi в FastAPI приводит к тому, что авторизация не работает?Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Почему добавление пользовательской схемы openapi в FastAPI приводит к тому, что авторизация не работает?

Сообщение Anonymous »

У меня есть приложение FastAPI, работающее в main.py:

Код: Выделить всё

app = FastAPI()

app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

sub_app1 = FastAPI()
sub_app1.include_router(auth.router)
и в routers/auth.py у меня есть:

Код: Выделить всё

@router.post("/complete", status_code=status.HTTP_201_CREATED)
async def complete_registration_create_user(db: db_dependency, create_user_request: CreateUserRequest):
"""Compeletes the registration when user submits password."""
hashed_password = bcrypt_context.hash(create_user_request.password)
create_user_model = Users(
email=create_user_request.email,
hashed_password=hashed_password,
phone=create_user_request.phone,
)

# Note: In a organisation all staff members should be approved by Owner.

try:
db.add(create_user_model)
await db.commit()
except IntegrityError as er:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"User {create_user_request.email} already exists. Choose a different email or try resetting the password."
)
await db.refresh(create_user_model)
return {"user": create_user_request.email}

@router.post("/token", response_model=Token)
async def user_login_for_access_token(form_data: Annotated[OAuth2EmailRequestForm, Depends()],
db: db_dependency):
"""Login user for an access token"""
user = await authenticate_user(form_data.email, form_data.password, db)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate user."
)

tenant_identifier = form_data.identifier

token = create_access_token(
user.email,
user.id,
tenant_identifier,
timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
)

return {'access_token': token, 'token_type': 'bearer'}

все вышеперечисленное работает, но как только я добавлю обновление ниже, чтобы указать openschema в main.py:

Код: Выделить всё

def custom_openapi():
if sub_app1.openapi_schema:
return sub_app1.openapi_schema

openapi_schema = get_openapi(
title=" Authorisation API",
version="0.0.1",
description="API on this docs deals with all user and company registration.",
routes=sub_app1.routes,
)
sub_app1.openapi_schema = openapi_schema
return sub_app1.openapi_schema

sub_app1.openapi = custom_openapi
конечные точки аутентификации начинаются, что приводит к ошибке «Не найдено», т.е.

Код: Выделить всё

INFO:     127.0.0.1:43756 - "POST /register/token?email=user2%40example.com&identifier=sada&password=string HTTP/1.1" 404 Not Found
INFO:     127.0.0.1:44748 - "POST /register/complete HTTP/1.1" 404 Not Found
Что можно попробовать дальше?

Подробнее здесь: https://stackoverflow.com/questions/789 ... n-not-to-w
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»