How to Use Async SQLAlchemy in FastAPI

Поделиться
HTML-код
  • Опубликовано: 22 авг 2024
  • 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....
    Get the code I wrote in this video here: prettyprinted....
    Twitter: / pretty_printed
    Github: github.com/pre...

Комментарии • 43

  • @gerardorosiles8918
    @gerardorosiles8918 5 месяцев назад +2

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

  • @cusematt23
    @cusematt23 7 месяцев назад +1

    This helped me a ton ... great stuff👍

  • @Iamjafex
    @Iamjafex Год назад +1

    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  Год назад

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

  • @SsaliJonathan
    @SsaliJonathan Год назад +2

    Nice video Anthony

  • @sinancetinkaya
    @sinancetinkaya Год назад +1

    Yesterday I was looking for this :)

  • @night23412
    @night23412 Год назад +3

    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()

  • @jijojoseph8721
    @jijojoseph8721 Год назад +3

    can you help in how we can integrate alembic into this

  • @ineps7603
    @ineps7603 6 месяцев назад +2

    in this approach will be one Session per request?

  • @Learn_with_cosmos
    @Learn_with_cosmos 11 месяцев назад

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

  • @pococonut609
    @pococonut609 19 дней назад

    Thanks

  • @mauricioyepes3394
    @mauricioyepes3394 Год назад +2

    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.

  • @default_youtube_profile
    @default_youtube_profile 17 дней назад

    aiomysql extension for sqlalchemy does not have async_sessionmaker! what should I use?

  • @salmanmushtaq7633
    @salmanmushtaq7633 11 месяцев назад +1

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

    • @qqyyabs
      @qqyyabs 11 месяцев назад +1

      psycopg3 works pretty well

  • @sampri22
    @sampri22 3 месяца назад

    Is there one session per request in this example?

  • @TheAremoh
    @TheAremoh Год назад

    Nice video.

  • @ReRubis
    @ReRubis 8 месяцев назад

    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?

  • @tainebambrough6029
    @tainebambrough6029 Год назад

    Thank you for this !

  • @CodeTesting-pd1td
    @CodeTesting-pd1td Год назад

    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.

  • @danielfajt8090
    @danielfajt8090 Год назад

    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.

  • @moneeshkumar1838
    @moneeshkumar1838 Год назад

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

    • @aflous
      @aflous Год назад

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

  • @user-uc2lm7pw9x
    @user-uc2lm7pw9x Год назад

    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 11 месяцев назад

      use limit in statement

  • @joaovictor-dl6ve
    @joaovictor-dl6ve Год назад

    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  Год назад

      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.

  • @Useroftherisingsun
    @Useroftherisingsun Год назад

    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  Год назад

      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 Год назад

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

    • @prettyprinted
      @prettyprinted  Год назад +1

      @@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 Год назад

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

  • @random_act
    @random_act 9 месяцев назад

    cool

  • @wattsfield1889
    @wattsfield1889 7 месяцев назад

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

  • @joaovictor-dl6ve
    @joaovictor-dl6ve Год назад

    Can I use migrations with sqlalchemy assincronous?

  • @fumano2679
    @fumano2679 Год назад +1

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

    • @heroe1486
      @heroe1486 11 месяцев назад +3

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