1

I'm new to python, trying to learn and use Fastapi, Ariadne and SQLAlchemy. I'm following the docs and I'm stuck.

I have my dependency injection get_db() for normal REST requests, which provides a Session object, which I pass through few different modules from the request start until I actually do the db work, and honestly I don't get this design. But I left it there.

Then, another problem come up. How can I pass db to Ariadne GraphQL? Should I use context_value or are there any other options?

shyos
  • 1,390
  • 1
  • 16
  • 29
  • Does Ariadne integrate directly with SQLAlchemy? I couldn't find any information about that - it seems like you'd write graphql resolvers and then query the database to resolve the information that is required to resolve that particular node. – MatsLindh Nov 20 '21 at 19:36
  • @MatsLindh I have resolvers and everything. I had it up and running with flask then decided to migrate fastapi. Now on fastapi it seem db object needs to be passed as parameter to graphql, and currently i am using context_value for that. But I was wondering if there are any other options? – shyos Nov 21 '21 at 19:48

1 Answers1

3

You need to create a session of SQLAlchemy from ariadne resolvers. And don't forget to close the connection after resolvers finished.

Let's say your database file like following,

import os

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = os.getenv("DB_CONN_STRING")

engine = create_engine(SQLALCHEMY_DATABASE_URL)
LocalSession = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def get_db():
    db = None
    try:
        db = LocalSession()
        yield db
    finally:
        if db:
            db.close()
  • You can do like following on the resolvers
# Import the local session from local database file
from app.database import LocalSession

db = LocalSession()
# Do whatever you need to do
db.close()