English 中文(简体)
FastAPI 国家物体没有属性执行
原标题:FastAPI State object has no attribute implementation
I m getting error State object has no attribute implementation with FastAPI test code. My source: # tests/example_test.py import pytest from httpx import AsyncClient from webserver import app @pytest.mark.anyio async def test_get_value(): async with AsyncClient(app=app) as client: response = await client.get( /api/get_value ) assert response.status_code == 200 assert response.json() == { value : 0, } # webserver.py from fastapi import FastAPI from fastapi import Request from httpx import AsyncClient from contextlib import asynccontextmanager from implementation import Implementation @asynccontextmanager async def lifespan(app: FastAPI): async with AsyncClient(app=app) as client: implementation = Implementation() yield { implementation : implementation} implementation.shutdown() app = FastAPI(lifespan=lifespan) @app.post( /api/increment ) async def api_increment( request: Request, ): implementation: Implementation = request.state.implementation implementation.increment() return {} @app.get( /api/get_value ) async def api_get_value( request: Request, ): implementation: Implementation = request.state.implementation value = implementation.get_value() return { value : value, } # implementation.py class Implementation(): def __init__(self) -> None: self.current_value = 0 self._initialized = True print(f Implementation starts ) def shutdown(self) -> None: A function which must be called to cleanup resources before exit self._initialized = False print(f Implementation stops ) def increment(self) -> None: In reality this would do something like read/write to a file, db etc self.current_value += 1 def get_value(self) -> None: return self.current_value How to fix? FYI: This synchronous test works: from fastapi.testclient import TestClient def test_get_value_synchronous(): with TestClient(app) as client: response = client.get( /api/get_value ) assert response.status_code == 200 assert response.json() == { value : 0, }
问题回答
When you use AsyncClient it doesn t run lifespan function of your app. You should run it manually (async with app.router.lifespan_context(app):): @pytest.mark.anyio async def test_get_value(): async with AsyncClient(app=app) as client: async with app.router.lifespan_context(app): response = await client.get( /api/get_value ) assert response.status_code == 200 assert response.json() == { value : 0, } You can also use asgi-lifespan library: https://pypi.org/project/asgi-lifespan/




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签