Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SQLAlchemy implementation #1

Open
somada141 opened this issue Apr 9, 2018 · 2 comments
Open

SQLAlchemy implementation #1

somada141 opened this issue Apr 9, 2018 · 2 comments

Comments

@somada141
Copy link

Hi there and thanks a lot for posting this :). Would you happen to have figured out how to glue together Graphene, Graphene-SQLAlchemy, and Falcon?

@alecrasmussen
Copy link
Owner

I haven't worked with Graphene-SQLAlchemy myself, but it looks to me like you could create your schema the same way you usually would and then use that. To copy from Graphene-SQLAlchemy's first example, you could try something like this:

Base = declarative_base()

class UserModel(Base):
    __tablename__ = 'department'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    last_name = Column(String)

class User(SQLAlchemyObjectType):
    class Meta:
        model = UserModel

# Define a GraphQL query schema.
class Query(graphene.ObjectType):
    users = graphene.List(User)

    def resolve_users(self, info):
        query = User.get_query(info)  # SQLAlchemy query
        return query.all()

# Create the schema that will be used to resolve GraphQL requests.
schema = graphene.Schema(query=Query)

The main other thing that you may need to add is to pass in your db handler via context when calling schema.execute.

@somada141
Copy link
Author

I think that's where my primary hangup was, namely passing the SQLAlchemy session to the context while ensuring that we're using per-request sessions instead of a hanging one that eventually times out.

Further tinkering and http://docs.graphene-python.org/projects/sqlalchemy/en/latest/tips/#querying makes me think that there are three options here.:

  1. Create a scoped_session and pass it to the resource-class which in-turn passes it to the context.
  2. Create a scoped_session and boil it in the SQLAlchemy Base much like https://medium.com/@fasterpancakes/graphql-server-up-and-running-with-50-lines-of-python-85e8ada9f637
  3. Allow the resource-class to create an engine to the DB and explicitly create sessions per request which it then passes to the context.

Thanks a lot for the code again! Any plans to make it into a pypi package for easier integration?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants