Это код ниже. Я хочу проверить запрос, который имеет часть своего пути, префиксированным внешними средствами. Это промежуточное программное обеспечение удаляет его перед обслуживанием запроса. < /P>
app = FastAPI(
title="title",
description="description",
version="1.0.0",
contact={"name": "Me"},
)
# Middleware to remove ingress_path from incoming requests which is required for various environments
# where an additional path is added to the URL before the actual path.
# This middleware is only applied if the environment variable INGRESS_PATH_TO_REMOVE_FROM_INCOMING_REQUESTS is set.
# Further down in the code, the remove_path is used to construct the URL for the Swagger UI.
ingress_path = os.getenv(
"INGRESS_PATH_TO_REMOVE_FROM_INCOMING_REQUESTS",
"",
)
if ingress_path != "":
@app.middleware("http")
async def modify_request_response_middleware(request: Request, call_next):
# Intercept and modify the incoming request
if ingress_path in request.url.path:
logging.debug(
f"Removing ingress path '{ingress_path}' from the Request URL: '{request.url.path}'"
)
new_path = str(request.url.path).replace(ingress_path, "")
logging.debug(f"Modified URL: '{new_path}'")
request.scope["path"] = new_path
# Process the modified request
response = await call_next(request)
return response
< /code>
test: (mock_dependencies просто издевается над некоторыми ненужными вещами для целей этого теста) < /p>
import os
import pytest
from unittest.mock import patch, AsyncMock, MagicMock
from fastapi import FastAPI
from fastapi.testclient import TestClient
from api import app
@pytest.fixture
def app_with_ingress_path(mock_dependencies):
"""Create FastAPI app with ingress path middleware"""
os.environ['INGRESS_PATH_TO_REMOVE_FROM_INCOMING_REQUESTS'] = '/api/v1'
return app
def test_middleware_removes_ingress_path_from_url(app_with_ingress_path):
"""Test that middleware removes ingress path from request URL"""
# Use the app_with_ingress_path fixture directly
# Mock a simple endpoint for testing
@app_with_ingress_path.get("/test")
async def test_endpoint(): # noqa: F811
return {"message": "test"}
client = TestClient(app_with_ingress_path)
# Request should be processed after middleware removes /api/v1 prefix
response = client.get("/api/v1/test")
assert response.status_code == 200
< /code>
Утверждение не сбои: < /p>
> assert response.status_code == 200
E assert 404 == 200
E + where 404 = .status_code
Это код ниже. Я хочу проверить запрос, который имеет часть своего пути, префиксированным внешними средствами. Это промежуточное программное обеспечение удаляет его перед обслуживанием запроса. < /P> [code]app = FastAPI( title="title", description="description", version="1.0.0", contact={"name": "Me"}, )
# Middleware to remove ingress_path from incoming requests which is required for various environments # where an additional path is added to the URL before the actual path. # This middleware is only applied if the environment variable INGRESS_PATH_TO_REMOVE_FROM_INCOMING_REQUESTS is set. # Further down in the code, the remove_path is used to construct the URL for the Swagger UI. ingress_path = os.getenv( "INGRESS_PATH_TO_REMOVE_FROM_INCOMING_REQUESTS", "", )
if ingress_path != "":
@app.middleware("http") async def modify_request_response_middleware(request: Request, call_next): # Intercept and modify the incoming request if ingress_path in request.url.path: logging.debug( f"Removing ingress path '{ingress_path}' from the Request URL: '{request.url.path}'" ) new_path = str(request.url.path).replace(ingress_path, "") logging.debug(f"Modified URL: '{new_path}'") request.scope["path"] = new_path # Process the modified request response = await call_next(request)
return response < /code> test: (mock_dependencies просто издевается над некоторыми ненужными вещами для целей этого теста) < /p> import os import pytest from unittest.mock import patch, AsyncMock, MagicMock from fastapi import FastAPI from fastapi.testclient import TestClient from api import app
def test_middleware_removes_ingress_path_from_url(app_with_ingress_path): """Test that middleware removes ingress path from request URL""" # Use the app_with_ingress_path fixture directly
# Mock a simple endpoint for testing @app_with_ingress_path.get("/test") async def test_endpoint(): # noqa: F811 return {"message": "test"}
client = TestClient(app_with_ingress_path) # Request should be processed after middleware removes /api/v1 prefix response = client.get("/api/v1/test") assert response.status_code == 200 < /code> Утверждение не сбои: < /p> > assert response.status_code == 200 E assert 404 == 200 E + where 404 = .status_code [/code] Я не знаю, как заставить это работать.
У меня есть глобальное промежуточное программное обеспечение, обрабатывающее исключения, создаваемые приложением. Он работает так, как и предполагалось, за исключением сбоев операций на уровне БД. Когда у меня возникает проблема, о которой сообщает...
I have a global middleware handling the exceptions thrown by the application. It works as supposed to except for operations failing at the DB level. When I have a problem that Entity Framework reports (due to flawed config in Context definition or...
У меня есть промежуточное программное обеспечение, которое устанавливает код состояния ответа, тип контента и содержимое (с помощью SendFileAsync), но файл журнала содержит отладочное сообщение от Microsoft.AspNetCore.Hosting.Diagnostics, в котором...
У меня есть промежуточное программное обеспечение, которое устанавливает код состояния ответа, тип контента и содержимое (с помощью SendFileAsync), но файл журнала содержит отладочное сообщение от Microsoft.AspNetCore.Hosting.Diagnostics, в котором...
Я смотрел учебник по ядру Asp .net, и мне было интересно, в чем разница между фильтрами и промежуточным программным обеспечением, и после некоторых исследований я нашел ответ на свой вопрос о том, что конвейер промежуточного программного обеспечения...