graphql-python / graphql-python/flask-graphql

Connect to multiple data sources in same app

未关闭
#57 0 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看
主要语言
Python
星标
1.3k
派生
139
PR 合并指标
30 天内没有已合并 PR

描述

It appears I can only bind a single SQLAlchemy session to an app at once via the context variable:

from flask import Flask
from flask_graphql import GraphQLView
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from schema import schema

# connect to database sources
engine1 = create_engine('sqlite:///db1.sqlite3')
engine2 = create_engine('sqlite:///db2.sqlite3')
session1 = scoped_session(sessionmaker(bind=engine1))
session2 = scoped_session(sessionmaker(bind=engine2))

# create app and add GraphiQL route
app = Flask(__name__)
app.add_url_rule('/graphql', view_func=GraphQLView.as_view(
'graphql',
schema=schema,
graphiql=True,
get_context=lambda: {'session': session1}
))

Is there any way to connect to more than one data source at once or is this not possible?

If not, Flask-SQLAlchemy handles this well by binding the data source name to the sqlalchemy model. I'd recommend doing something similar: http://flask-sqlalchemy.pocoo.org/2.3/binds/

I figured out a workaround by specifying the right session in the GraphQL query but this seems very hacky and prevents me from using nice extensions like [Graphene-SQLAlchemy](http://docs.graphene-python.org/projects/sqlalchemy/en/latest/)

class Query(ObjectType):
node = relay.Node.Field()

# requires session1 (both resolvers work because default session is session1)
all_employees = SQLAlchemyConnectionField(EmployeeConnections)
employees = graphene.List(EmployeeNode, name=graphene.String())

# requires session2
all_departments = SQLAlchemyConnectionField(DepartmentConnections) # can't do this because default session is session1
departments = graphene.List(DepartmentNode, name=graphene.String())

def resolve_departments(self, info, **kwargs):
name = kwargs.get('name')
if not name:
raise GraphQLError('Name argument is required.')
return session2.query(Department).filter_by({'name': kwargs.get('name')}).all()

贡献指南

这个仓库没有索引到贡献指南

评估

这个 Issue 还没有评估数据。

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。