graphql-python / graphql-python/flask-graphql
Connect to multiple data sources in same app
還沒有人認領這個 Issue。
- 主要語言
- 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
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 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
先追蹤 GraphQLView 對 get_context 的處理方式,以及 SQLAlchemyConnectionField 如何取得其 session,接著將所要求的行為與 Graphene-SQLAlchemy 進行比較。此 issue 沒有提供可作為目標的 repository 檔案或測試。完成的標準是:多個已設定的資料來源可以在同一個 app 中運作,同時保留 SQLAlchemyConnectionField 及相關擴充功能,而不需要針對 resolver 的 session 變通方案。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- flask, graphql, python, sqlalchemy
- 領域
- api, backend, database
- Issue 類型
- 功能
- 難度
- 5/5
- 預估耗時
- 一週以上
- 活躍度
- 停滯
- 描述清晰度
- 需要釐清
- 新手友好度
- 25/100