How to Use Async SQLAlchemy in FastAPI

In this video, I'll demonstrate how to use async Sqlalchemy in FastAPI by converting an existing sync version of Sqlalchemy to Async.
Need one-on-one help with your project? I can help through my coaching program. Learn more here: prettyprinted.com/coaching
Get the code I wrote in this video here: prettyprinted.com/l/Xq1
Twitter: / pretty_printed
Github: github.com/prettyprinted

Пікірлер: 41

  • @gerardorosiles8918
    @gerardorosiles89182 ай бұрын

    Thanks for the explanation. Illustrating a more complex query and a full CRUD example would be great.

  • @cusematt23
    @cusematt234 ай бұрын

    This helped me a ton ... great stuff👍

  • @sinancetinkaya
    @sinancetinkaya Жыл бұрын

    Yesterday I was looking for this :)

  • @prettyprinted

    @prettyprinted

    Жыл бұрын

    Glad I could help. Thanks for watching.

  • @Iamjafex
    @Iamjafex11 ай бұрын

    Good overview! I agree with your distaste of the new sql alchemy approach. I've used pre 2.0 for a few years now and have found it very easy and comfortable, but I do see the benefit of this approach in verbosity. Hopefully it'll make stuff like joins and other weird query gimmicks easier than the old approach

  • @prettyprinted

    @prettyprinted

    11 ай бұрын

    Yeah I need to use it in a bigger project to get a good feel for how it works. Thanks for watching the video!

  • @tabancosmos2235
    @tabancosmos22359 ай бұрын

    Nice one. I am coming back to python after years of NodeJS and others lol!

  • @SsaliJonathan
    @SsaliJonathan Жыл бұрын

    Nice video Anthony

  • @prettyprinted

    @prettyprinted

    Жыл бұрын

    Thanks for watching!

  • @CodeTesting-pd1td
    @CodeTesting-pd1td10 ай бұрын

    Would you happen to know if using the @asynccontextmanager decorator from the built-in contextlib is of any use when creating AsyncSession objects? According to the SQLAlchemy documentation, it seems that the async_sessionmaker is already handling the teardown. I am having trouble deciding if I should use the asynccontextmanager or not.

  • @TheAremoh
    @TheAremoh Жыл бұрын

    Nice video.

  • @prettyprinted

    @prettyprinted

    Жыл бұрын

    Thanks for watching!

  • @mauricioyepes3394
    @mauricioyepes3394 Жыл бұрын

    Great video, thank you. What do you think about using asyncio? result = await asyncio.gather(*tasks) And tasks could be like: tasks = [get_users()] In that way you don't need to change the logic to access the DB, the responsibility for converting the get_users to async will be for asyncio. This may work for projects that already have a lot of logic using sync access to the DB so they don't need to refactor all the logic they have to access the DB.

  • @prettyprinted

    @prettyprinted

    Жыл бұрын

    At some point you'll need to have async access to the database otherwise you won't get all the benefits of async code. But if your DB access code where contained behind helper functions, it would be easier to convert the helper functions to async.

  • @danielfajt8090
    @danielfajt809011 ай бұрын

    Does this solution cover a rollback? get_db() -> AsyncSession, on which you will use transaction eventually. If you call flush() somewhere in the call stack and an exception is raised, this won't call a rollback, right? Thanks.

  • @ineps7603
    @ineps76034 ай бұрын

    in this approach will be one Session per request?

  • @tainebambrough6029
    @tainebambrough6029 Жыл бұрын

    Thank you for this !

  • @prettyprinted

    @prettyprinted

    Жыл бұрын

    You're welcome! Thanks for watching.

  • @jijojoseph8721
    @jijojoseph8721 Жыл бұрын

    can you help in how we can integrate alembic into this

  • @ReRubis
    @ReRubis6 ай бұрын

    Is putting base.metadata.create_all method in function returning session a good approach? Isn't it gonna run everytime you init session, which occurs on every endpoint? And it's run_sync. Doesn't seem efficient. I think it should be separated into a separate function and ran once on the app startup, no?

  • @user-uc2lm7pw9x
    @user-uc2lm7pw9x11 ай бұрын

    Great video, Actually, I have an question. when I use AsyncSession and call await db.execute(""" some procedures """) and that result of the procedure is multiple result sets. so how to get several sets?

  • @qqyyabs

    @qqyyabs

    9 ай бұрын

    use limit in statement

  • @random_act
    @random_act6 ай бұрын

    cool

  • @night23412
    @night23412 Жыл бұрын

    instead of doing results = await db.execute(select(User)) users = results.scalars().all() you can also do this if it makes it look any better users = await db.scalars(select(User)) users = users.all()

  • @salmanmushtaq7633
    @salmanmushtaq76339 ай бұрын

    Can we use same for production? Also what will be the driver for postgresql?

  • @qqyyabs

    @qqyyabs

    9 ай бұрын

    psycopg3 works pretty well

  • @moneeshkumar1838
    @moneeshkumar1838 Жыл бұрын

    Is it safe to use Aync SQLAlchemy, do we run into race conditions and Is it production safe? Kindly reply

  • @aflous

    @aflous

    11 ай бұрын

    It is as safe as it can get, "we are all consenting adults here"

  • @sampri22
    @sampri22Ай бұрын

    Is there one session per request in this example?

  • @joaovictor-dl6ve
    @joaovictor-dl6ve10 ай бұрын

    What's the difference using async db and sync db? like, if I want I can use SYNC sqlalchemy with ASYNC fastapi , right?

  • @prettyprinted

    @prettyprinted

    10 ай бұрын

    Yes, you always have the option of using sync code in async code. But the other way around requires that you set up your app to use async. That comes for free in FastAPI, but if you were writing something like a script, you'd need to set it up to handle async. Why async? So you don't have to wait for input/output and do other things instead.

  • @joaovictor-dl6ve
    @joaovictor-dl6ve10 ай бұрын

    Can I use migrations with sqlalchemy assincronous?

  • @prettyprinted

    @prettyprinted

    10 ай бұрын

    Yeah, migrations can still be used.

  • @Useroftherisingsun
    @Useroftherisingsun10 ай бұрын

    I understand that nobody's probably gonna answer me soon here, but I don't understand why metadata.create_all() is placed into get_db() function. Like, isn't create_all() method is should only be used once while creating database, not when accesing it?

  • @prettyprinted

    @prettyprinted

    10 ай бұрын

    I did that for convenience so I wouldn't have to create all the tables separately. It doesn't hurt to run create_all multiple times because it doesn't have any effect if the tables already exists. But yes, in a real app, you wouldn't need it in get_db.

  • @Useroftherisingsun

    @Useroftherisingsun

    10 ай бұрын

    @@prettyprinted does it also have no effect on the execution time?

  • @prettyprinted

    @prettyprinted

    10 ай бұрын

    @@Useroftherisingsun There is definitely a small cost to using it, yes, so there's no need to use it in a production app. In a development environment, your database is often running on the same machine as your code, so it only adds a few milliseconds.

  • @Useroftherisingsun

    @Useroftherisingsun

    10 ай бұрын

    @@prettyprinted Got it. Thanks for your fast reply! Have a great day :)

  • @wattsfield1889
    @wattsfield18895 ай бұрын

    That's weird, my AsyncSession does not have the .query()

  • @fumano2679
    @fumano2679 Жыл бұрын

    Ill just stick to synchronous computing, if i wanted efficiency i would use rust and not python :)

  • @heroe1486

    @heroe1486

    9 ай бұрын

    Then continue with your logic and use Django/DRF, which is superior than other python options in most aspects outside of perfs.