使用Graphene Python构建GraphQL × Flask × SQLAlchemy服务器
本篇文章的內容。
- この記事では、Graphene Python を利用した GraphQL × Flask × SQLAlchemy Server の構築方法をまとめたものとなっております
GraphQL 是一种(原则上)的技术
-
- Facebook製 オープンソースのクエリ言語
-
- RESTに変わるものとして注目されている
-
- クライアントとサーバ間のデータのやりとりを容易に記述することができる
- クエリに対して、JSON で結果を返す
请参考以下链接:
* https://qiita.com/syu_chan_1005/items/3350f1d12c17a77e98c7
* https://vitalify.jp/app-lab/20171006-graphql/
* https://tukumemo.com/graphql/
石墨烯是一种材料。
-
- Python 用 GraphQL フレームワーク (JavaScript用もあるらしい)
https://graphene-python.org/
运行环境
-
- MacOS Mojave 10.14.1
-
- Python 3.6.5
-
- Flask 1.0.2
- sqlite 3.24.0
直到移动
http://docs.graphene-python.org/projects/sqlalchemy/en/latest/tutorial/ の内容ベースで翻訳しております
## プロジェクト用のディレクトリを作成
mkdir flask_sqlalchemy
cd flask_sqlalchemy
## virtualenv 環境の作成と読み込み
virtualenv env
source env/bin/activate # On Windows use `env\Scripts\activate`
## SQLAlchemy と graphene_sqlalchemy の pip install
pip install SQLAlchemy
pip install graphene_sqlalchemy
## Flask と Flask-GraphQL のインストール
pip install Flask
pip install Flask-GraphQL
模型的定义 de
# flask_sqlalchemy/models.py
from sqlalchemy import *
from sqlalchemy.orm import (scoped_session, sessionmaker, relationship,
backref)
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///database.sqlite3', convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
# We will need this for querying
Base.query = db_session.query_property()
class Department(Base):
__tablename__ = 'department'
id = Column(Integer, primary_key=True)
name = Column(String)
class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True)
name = Column(String)
hired_on = Column(DateTime, default=func.now())
department_id = Column(Integer, ForeignKey('department.id'))
department = relationship(
Department,
backref=backref('employees',
uselist=True,
cascade='delete,all'))
创建模式
GraphQL将对象表示为图结构,而不是常见的分层结构。
本次例子中,我们通过all_employees提供了列出所有员工的功能,并且通过节点提供了获取特定节点的功能。
创建一个名为 flask_sqlalchemy/schema.py 的文件,并按照以下方式进行编辑。
# flask_sqlalchemy/schema.py
import graphene
from graphene import relay
from graphene_sqlalchemy import SQLAlchemyObjectType, SQLAlchemyConnectionField
from models import db_session, Department as DepartmentModel, Employee as EmployeeModel
class Department(SQLAlchemyObjectType):
class Meta:
model = DepartmentModel
interfaces = (relay.Node, )
class DepartmentConnection(relay.Connection):
class Meta:
node = Department
class Employee(SQLAlchemyObjectType):
class Meta:
model = EmployeeModel
interfaces = (relay.Node, )
class EmployeeConnection(relay.Connection):
class Meta:
node = Employee
class Query(graphene.ObjectType):
node = relay.Node.Field()
# Allows sorting over multiple columns, by default over the primary key
all_employees = SQLAlchemyConnectionField(EmployeeConnection)
# Disable sorting over this field
all_departments = SQLAlchemyConnectionField(DepartmentConnection, sort=None)
schema = graphene.Schema(query=Query)
创建在Flask上的GraphQL环境。
与 RESTful API 不同,GraphQL 只有一个访问 URL。
使用Flask创建一个服务器,在/graphql路径下公开GraphQL模式,并创建一个称为GraphiQL的接口,用于轻松执行查询操作。
Flask-GraphQL库可以支持实现此功能。
# flask_sqlalchemy/app.py
from flask import Flask
from flask_graphql import GraphQLView
from models import db_session
from schema import schema, Department
app = Flask(__name__)
app.debug = True
app.add_url_rule(
'/graphql',
view_func=GraphQLView.as_view(
'graphql',
schema=schema,
graphiql=True # for having the GraphiQL interface
)
)
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
if __name__ == '__main__':
app.run()
我试着创建一些数据
使用Python 3打开控制台。
>>> from models import engine, db_session, Base, Department, Employee
>>> Base.metadata.create_all(bind=engine)
>>> # Fill the tables with some data
>>> engineering = Department(name='Engineering')
>>> db_session.add(engineering)
>>> hr = Department(name='Human Resources')
>>> db_session.add(hr)
>>> peter = Employee(name='Peter', department=engineering)
>>> db_session.add(peter)
>>> roy = Employee(name='Roy', department=engineering)
>>> db_session.add(roy)
>>> tracy = Employee(name='Tracy', department=hr)
>>> db_session.add(tracy)
>>> db_session.commit()
GraphQL 测试操作
现在,准备工作已经完成。让我们从命令行启动服务器并检查其运行情况。
$ python3 ./app.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
启动后,请尝试访问 http://localhost:5000/graphql。
在左侧输入查询以验证功能。
{
allEmployees {
edges {
node {
id
name
department {
name
}
}
}
}
}
通过这个,您可以确认查询的响应了。
构建一个简单的 GraphQL + DB 服务器时,本文的内容非常有用。
如果有运行不顺利的问题,可以尝试查看 Github 仓库中的示例并进行尝试。
非常感谢您耐心地阅读这篇长文❗️
给你一个额外的好处
似乎还有MongoDB的教程:
* https://graphene-mongo.readthedocs.io/en/latest/tutorial.html