r/FastAPI • • Nov 05 '24

Question contextvars are not well-behaved in FastAPI dependencies. Am I doing something wrong?

10 Upvotes

Here's a minimal example:

import contextvars
import fastapi
import uvicorn

app = fastapi.FastAPI()

context_key = contextvars.ContextVar("key", default="default")

def save_key(key: str):
    try:
        token = context_key.set(key)
        yield key
    finally:
        context_key.reset(token)

@app.get("/", dependencies=[fastapi.Depends(save_key)])
async def with_depends():
    return context_key.get()

uvicorn.run(app)

Accessing this as http://localhost:8000/?key=1 results in HTTP 500. The error is:

  File "/home/user/Scratch/fastapi/app.py", line 15, in save_key
    context_key.reset(token)
ValueError: <Token var=<ContextVar name='key' default='default' at 0x73b33f9befc0> at 0x73b33f60d480> was created in a different Context

I'm not entirely sure I understand how this happens. Is there a way to make it work? Or does FastAPI provide some other context that works?


r/FastAPI • • Nov 04 '24

Question App freezes up for 1 request after an endpoint processes some data using multiprocessing.

11 Upvotes

I have a FastAPI endpoint in which I need to do some multiprocessing and return the result of the multiprocessing. I can't do this as a background task/celery task.
I've managed to get the endpoint's functionality working using this wrapper on top of concurrent.Futures.ProcessPoolExecutor:

from concurrent.futures import ProcessPoolExecutor, Future, as_completed
from typing import Callable, Iterable



class PersistentProcessPool:

    def __init__(self, max_workers: int|None=None):
        if max_workers is not None:
            self._pool: ProcessPoolExecutor = ProcessPoolExecutor(max_workers=max_workers)
        else:
            self._pool = ProcessPoolExecutor()
        self._accept_tasks: bool = True

    def add_single_task(self, task: Callable, *args, **kwargs) -> Future:
        if not self._accept_tasks:
            raise ValueError("can not accept tasks as '_accept_tasks' is False")
        return self._pool.submit(task, *args, **kwargs)

    def add_multiple_tasks(self, task: Callable, *args) -> Iterable[Future]:
        if not self._accept_tasks:
            raise ValueError("can not accept tasks as '_accept_tasks' is False")
        return self._pool.map(task, *args)

    def shutdown(self) -> None:
        if self._accept_tasks is False:
            raise ValueError('pool has already been shut down')
        self._pool.shutdown()
        self._accept_tasks = False

    def __del__(self) -> None:
        self.shutdown()

The issue I face is, The next request made doesn't return at all, and when I try to add some print logging, it looks like the app didn't receive the request. However, all requests after it work properly.
How do I stop this from happening?


r/FastAPI • • Nov 03 '24

Question Dependency overrides for unit tests with FastAPI?

8 Upvotes

Hi there, I'm struggling to override my Settings when running tests with pytest.

I'm using Pydantic settings and have a get_settings method:

from pydantic_settings import BaseSettings
class Settings(BaseSettings):
  # ...

  model_config = SettingsConfigDict(env_file=BASE_DIR / ".env")


@lru_cache
def get_settings() -> Settings:
    return Settings()

Then, I have a conftest.py file at the root of my projet, to create a client as a fixture:

@pytest.fixture(scope="module")
def client() -> TestClient:
    """Custom client with specific settings for testing"""

    def get_settings_override() -> Settings:
        new_fields = dict(DEBUG=False, USE_LOGFIRE=False)
        return get_settings().model_copy(update=new_fields)

    app.dependency_overrides[get_settings] = get_settings_override
    return TestClient(app, raise_server_exceptions=False)

However, I soon as I run a test, I can see that the dependency overrides has no effect:

from fastapi.testclient import TestClient

def test_div_by_zero(client: TestClient):
    route = "/debug/div-by-zero"

    DEBUG = get_settings().DEBUG  # expected to be False, is True actually

    @app.get(route)
    def _():
        return 1 / 0

    response = client.get(route)

What I am doing wrong?

At first, I thought it could be related to caching, but removing @lru_cache does not change anything.

Besides, I think this whole system of overriding a little clunky. Is there any cleaner alternative? Like having another .env.test file that could be loaded for my unit tests?

Thanks.


r/FastAPI • • Nov 01 '24

Question Recommendation on FastAPI DB Admin tools? (starlette-admin, sqladmin, ...)

14 Upvotes

Hi there! Coming from the Django world, I was looking for an equivalent to the built-in Django admin tool. I noticed there are many of them and I'm not sure how to choose right now. I noticed there is starlette-admin, sqladmin, fastadmin, etc.

My main priority is to have a reliable tool for production. For example, if I try to delete an object, I expect this tool to be able to detect all objects that would be deleted due to a CASCADE mechanism, and notice me before.

Note that I'm using SQLModel (SQLAlchemy 2) with PostgreSQL or SQLite.

And maybe, I was wondering if some of you decided to NOT use admin tools like this, and decided to rely on lower level DB admin tools instead, like pgAdmin? The obvious con's here is that you lose data validation layer, but in some cases it may be what you want.

For such a tool, my requirements would be 1) free to use, 2) work with both PostgreSQL and SQlite and 3) a ready to use docker image

Thanks for your guidance!


r/FastAPI • • Oct 30 '24

Tutorial Video: Cadwyn for API Versioning (including deep dive FastAPI demo)

Thumbnail
youtu.be
13 Upvotes

r/FastAPI • • Oct 30 '24

Question Where to learn advanced FastAPI?

60 Upvotes

Hello, I'm a frontend dev who is willing to become a full stack developer, I've seen 2 udemy courses for FastAPI, read most of the documentaion, and used it to build a mid sized project.

I always find that there is some important advanced concept that I dont know in backend in general and in FastAPI specifically.

Is there someplace I should go first to learn backend advanced concepts and techniques preferably in FastAPI you guys would recommend

Thanks a lot in advance


r/FastAPI • • Oct 29 '24

Question Working with yield and except in dependency

4 Upvotes

I have some code on FastAPI 0.109.2 that I need to upgrade to 0.115.4. But when I do that I get an error that says: RuntimeError: generator didn't stop. I am pretty new to FastAPI; so, I was having a hard time finding a solution for this.

Stack trace:

[2024-10-30 00:28:47 +0000] [25] [ERROR] Exception in ASGI application
Traceback (most recent call last):
File "/usr/local/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi
result = await app(  # type: ignore[func-returns-value]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__
return await self.app(scope, receive, send)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/fastapi/applications.py", line 1054, in __call__
await super().__call__(scope, receive, send)
File "/usr/local/lib/python3.11/site-packages/starlette/applications.py", line 113, in __call__
await self.middleware_stack(scope, receive, send)
File "/usr/local/lib/python3.11/site-packages/starlette/middleware/errors.py", line 187, in __call__
raise exc
File "/usr/local/lib/python3.11/site-packages/starlette/middleware/errors.py", line 165, in __call__
await self.app(scope, receive, _send)
File "/usr/local/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 62, in __call__
await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
File "/usr/local/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app
raise exc
File "/usr/local/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app
await app(scope, receive, sender)
File "/usr/local/lib/python3.11/site-packages/starlette/routing.py", line 715, in __call__
await self.middleware_stack(scope, receive, send)
File "/usr/local/lib/python3.11/site-packages/starlette/routing.py", line 735, in app
await route.handle(scope, receive, send)
File "/usr/local/lib/python3.11/site-packages/starlette/routing.py", line 288, in handle
await self.app(scope, receive, send)
File "/usr/local/lib/python3.11/site-packages/starlette/routing.py", line 76, in app
await wrap_app_handling_exceptions(app, request)(scope, receive, send)
File "/usr/local/lib/python3.11/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app
raise exc
File "/usr/local/lib/python3.11/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app
await app(scope, receive, sender)
File "/usr/local/lib/python3.11/site-packages/starlette/routing.py", line 73, in app
response = await f(request)
^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/fastapi/routing.py", line 290, in app
async with AsyncExitStack() as async_exit_stack:
File "/usr/local/lib/python3.11/contextlib.py", line 745, in __aexit__
raise exc_details[1]
File "/usr/local/lib/python3.11/contextlib.py", line 728, in __aexit__
cb_suppress = await cb(*exc_details)
^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/contextlib.py", line 217, in __aexit__
await anext(self.gen)
File "/usr/local/lib/python3.11/site-packages/fastapi/concurrency.py", line 37, in contextmanager_in_threadpool
await anyio.to_thread.run_sync(
File "/usr/local/lib/python3.11/site-packages/anyio/to_thread.py", line 56, in run_sync
return await get_async_backend().run_sync_in_worker_thread(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/anyio/_backends/_asyncio.py", line 2441, in run_sync_in_worker_thread
return await future
^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/anyio/_backends/_asyncio.py", line 943, in run
result = context.run(func, *args)
^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/contextlib.py", line 149, in __exit__
raise RuntimeError("generator didn't stop")
RuntimeError: generator didn't stop

my endpoint looks something like this:

@router.get('/{activity_id}')
async def get_activity_detail(param_1: int,
                              response: Response,
                              creds: Creds = Depends(),
                              db:SQLServer = Depends(get_db):

# Does something

My get_db function looks like this:

def get_db() -> Generator:  # coverage: omit
    try:
        db = SessionLocal()
        yield db
    except Exception as e:
        print(f'Error : raised from {inspect.stack()[0][3]} - {str(e)}')
        raise
    finally:
        db.close()
        print(f'Closing the database connection')

r/FastAPI • • Oct 29 '24

Question Can't make gzipping work

4 Upvotes

I use SQLAlchemy and Pydantic.

buildings variable is SQLAlchemy mode, but in the response it gets parsed to Pydantic.

from fastapi.middleware.gzip import GZipMiddleware
app = FastAPI()
app.add_middleware(GZipMiddleware, minimum_size=0)

(at)router.get("/buildings", response_model=List[InlBuildingDTO], tags=["buildings"], summary="Get all the buildings.")

async def read_buildings(db: AsyncSession = Depends(get_db)):
try:
buildings = await get_buildings_latest_comment(db)
return buildings
except Exception as e:
logger.error(f"Error occurred while fetching buildings/properties: {e}")
raise HTTPException(status_code=500, detail="Internal server error")

In the request I set:
headers = {
'authorization': 'Bearer ey',
'Accept-Encoding': 'gzip, deflate, br'
}

Still, it doesn't return gzipped data, just returns plain json. Any idea?


r/FastAPI • • Oct 28 '24

Hosting and deployment What's a cheap way to deploy a fastapi app for computer vision?

19 Upvotes

I hage completed my first project, hosting my react frontend on netlify, but i need a place to host my fastapi.

It can get pretty cpu intensive, as I'm using yoloV11 and template matching to perform computer vision tasks on a user submitted image, peocessing it and generating a solution with beam search (it's a slider puzzle solver website).

As I'm still a student, i am hoping to be able to deploy it at a cheaper price, how should i go about it?


r/FastAPI • • Oct 25 '24

Question CPU-Bound Tasks Endpoints in FastAPI

23 Upvotes

Hello everyone,

I've been exploring FastAPI and have become curious about blocking operations. I'd like to get feedback on my understanding and learn more about handling these situations.

If I have an endpoint that processes a large image, it will block my FastAPI server, meaning no other requests will be able to reach it. I can't effectively use async-await because the operation is tightly coupled to the CPU - we can't simply wait for it, and thus it will block the server's event loop.

We can offload this operation to another thread to keep our event loop running. However, what happens if I get two simultaneous requests for this CPU-bound endpoint? As far as I understand, the Global Interpreter Lock (GIL) allows only one thread to work at a time on the Python interpreter.

In this situation, will my server still be available for other requests while these two threads run to completion? Or will my server be blocked? I tested this on an actual FastAPI server and noticed that I could still reach the server. Why is this possible?

Additionally, I know that instead of threads we can use processes. Should we prefer processes over threads in this scenario?

All of this is purely for learning purposes, and I'm really excited about this topic. I would greatly appreciate feedback from experts.


r/FastAPI • • Oct 25 '24

Hosting and deployment Pydantic Logfire is amazing

94 Upvotes

I'm absolutely not affiliated with them, but wanted to share a real enthusiasm about this project, because I think they deserve to reach their audience.

I always thought it was a pain in the ass when deploying a project to production to use multiple tools with dedicated roles for monitoring. I've always wanted an all-in-one observability platform which is easy to use.

Here is what I'm thinking of:

  • Made with python in mind (native integrations with FastAPI, SQLALchemy, Celery, and many others).
  • With these examples in mind, I can replace at least 5 tools with a single one:

    • Sentry (error management)
    • New Relic (perf)
    • logDNA (logs)
    • Celery flower (background task results)
    • Even local packages like debug toolbars can be replaced (I used to use them to see details of my database queries) and then have the same tools in local and remote environment.
  • I'm not used to see such top-notch design quality in Python world (no offense..)
  • UI is deadly easy, 4 tabs: live view, dashboard with KPIs, logs exploration, and alert settings. No options everywhere, submenus, hiden checkboxes, etc. I don't feel I need to be a devops engineer to monitore my app.
  • It works already well while being very young (some feature are missing, but not that much)
  • More than decent free plan (let's hope it won't change over time)
  • They are fast to answer on issues on Github
  • I tend to trust a team that built (the amazing) Pydantic and know open source, more than other ones.

I wish this team and this project the best!


r/FastAPI • • Oct 24 '24

Question How to stop an API while it's running?

4 Upvotes

How do I cancel an api call while it is functioning in backend?


r/FastAPI • • Oct 22 '24

Hosting and deployment Deploy FastAPI application with SQLite on Fly.io

Thumbnail
vnotes.pages.dev
8 Upvotes

r/FastAPI • • Oct 21 '24

Question Do you store text (descriptions of endpoints etc) alongside code or in separate files? Looking for best practice 🙂

5 Upvotes

H


r/FastAPI • • Oct 21 '24

Question CORS Origin Request blocked - 504 Error

3 Upvotes

I'm using a fastapi backend with a react front end and when I run the application in my front end, I'm receiving a 504 Error in the console, despite the backend running through without an issue. What could be the cause of this?


r/FastAPI • • Oct 21 '24

Hosting and deployment What do you use to host FastAPI?

37 Upvotes

I found that using vercel you can start for free ! before I was using digital ocean which was easy too to set up but started at 5$/month


r/FastAPI • • Oct 19 '24

Question Best MPA framework for fastapi

6 Upvotes

Hello guys i will soon start on a project. Before I say anything I must admit I am not that experienced in this field which is why i am here. In this project I am going to use FastAPI as for backend. I currently set-up the a few required endpoints. And now I need to start the front-end but still can't decide the framework. One thing is for sure I need MPA. Because in this website there will a a few different applications and loading all of them at the same time doesnt sound good to me.

I first thought of using jinja but it is not really good for mid-sized project which is like my project. I will need component system. So i though about using Nuxt js or Next js or React but every of them seem more convinient with SPA which doesnt fit to me. I've never done a website with SSR or MPA (I just used jinja once). So please englighten me. What should I learn? Is Next js literally good for MPA? I wasnt able to find many resources about MPA on Next js. To be honest I dont even know what makes it MPA or SPA. Since it seems like we use the same codes. If you recommend me something like Next js please tell me how can I accomplish a MPA or SSR website. I really am confused.


r/FastAPI • • Oct 19 '24

Other Share your FastAPI Projects!

46 Upvotes

Hey guys!

Recently I did a post asking about projects best practices and there was a few people sharing their own projects and I thought that was really nice! I really enjoy and also benefit from seeing other people projects ideas, code style, project file structure, etc.

So I thought about making this post so you can share you projects and maybe even get some feedback (if you're open to it).

Unfortunately I'm really new to FastAPI and still on the studying phase, but hope to share something with you guys soon!


r/FastAPI • • Oct 18 '24

Hosting and deployment which tech-stack to use?

19 Upvotes

So I have gotten a project where I have to make a web-based inventory management system for a small manufacturing company, I’m putting it in a simple way but the project will be on the lines of Inventory Management. Some of the features will be - users should be able to generate reports, they should have an invoicing system, they can check the inventory etc., basically an ERP system but a very simpler and toned-down version, tailored to the client’s needs. Should I go ahead with flask for the backend and js for front-end, or go with a modern approach with FastAPI and React. Again emphasising on the fact that the website does not have to be fancy, but it should do the job.


r/FastAPI • • Oct 17 '24

Question Looking for project's best practices

50 Upvotes

Hey guys! I'm new to FastAPI and I'm really liking it.

There's just one thing, I can't seem to find a consensus on best practices on the projects I find on Github, specially on the project structure. And most of the projects are a bit old and probably outdated.

Would really appreciate some guiding on this, and I wouldn't mind some projects links, resources, etc.

Thanks! =)

Edit: just to make it clear, the docs are great and I love them! It's more on the projects file structure side.


r/FastAPI • • Oct 17 '24

Hosting and deployment How do I deploy my FastAPI Web App on Plesk

5 Upvotes

So I am kind of a beginner, I have made an online shop using FastAPI, mongodb atlas for the database and simple html templates and js. Now I only have the option to deploy it on plesk, how do I do this. I am unable to find any support regarding this online.


r/FastAPI • • Oct 15 '24

Question Create HTML page with actual values that resembles public PDF template

9 Upvotes

I want to create a populated HTML version of the following template available here:

https://database.ich.org/sites/default/files/ICH_M11_Template_Step2_2022_0904.pdf

I'm creating an API endpoint with Python FastAPI framework to serve an HTML page which is equal to the PDF template and it's populated with values that I obtain elsewhere in JSON/dict format.

In section 0.3 of the PDF template file, there's a guide on how to replace the text in the PDF with other values (some should not appear in the populated version of the output, some should be replaced and some should be chosen among alternatives, ...) .

How can I do that? I suppose I should be using some kind of templating system such as Jinja (https://jinja.palletsprojects.com/en/3.1.x/), but my doubts are mostly:

how to quickly have a clean HTML representation of the PDF file

how to handle table of content and section numbering

how to handle text that should be replaced

Thank you for any pointer.


r/FastAPI • • Oct 13 '24

Question Not able to access FastAPI service hosted in my laptop from my mobile

2 Upvotes

I have hosted a FastAPI server in my laptop in http mode.

The hostname I used in the configuration is: 0.0.0.0 and the port is 8000.

My laptop and my mobile are connected to my WiFi router.

I try to access the service from my mobile's browser with the below address:

http://192.168.1.25:8000 (192.168.1.25 is my laptop IP address in the local network)

The browser says that 'The site can't be reached'.

Not sure what could be the issue. Can I have some suggestions pls.


r/FastAPI • • Oct 13 '24

feedback request I've built real-time chess with FastAPI

93 Upvotes

Hi r/FastAPI,

I was looking for a fun weekend hacking project and decided to build a chess game with FastAPI.
The project was a lot of fun to build, especially the game communication logic.

Sharing here for anyone interested:

Live demo:
NOTE: You need another player online. If the wait is too long and you just want to play alone like a psycho explore the game, you could open two browser windows, or use two machines / devices.

https://chess.olzhasar.com/

Source code:

https://github.com/olzhasar/pyws-chess

Cheers