在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):graphql-python/graphene-sqlalchemy开源软件地址(OpenSource Url):https://github.com/graphql-python/graphene-sqlalchemy开源编程语言(OpenSource Language):Python 99.7%开源软件介绍(OpenSource Introduction):Version 3.0 is in beta stage. Please read #348 to learn about progress and changes in upcoming beta releases. Graphene-SQLAlchemyA SQLAlchemy integration for Graphene. InstallationFor installing Graphene, just run this command in your shell. pip install "graphene-sqlalchemy>=3" ExamplesHere is a simple SQLAlchemy model: from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class UserModel(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String)
last_name = Column(String) To create a GraphQL schema for it, you simply have to write the following: import graphene
from graphene_sqlalchemy import SQLAlchemyObjectType
class User(SQLAlchemyObjectType):
class Meta:
model = UserModel
# use `only_fields` to only expose specific fields ie "name"
# only_fields = ("name",)
# use `exclude_fields` to exclude specific fields ie "last_name"
# exclude_fields = ("last_name",)
class Query(graphene.ObjectType):
users = graphene.List(User)
def resolve_users(self, info):
query = User.get_query(info) # SQLAlchemy query
return query.all()
schema = graphene.Schema(query=Query) Then you can simply query the schema: query = '''
query {
users {
name,
lastName
}
}
'''
result = schema.execute(query, context_value={'session': db_session}) You may also subclass SQLAlchemyObjectType by providing from graphene_sqlalchemy import SQLAlchemyObjectType
class ActiveSQLAlchemyObjectType(SQLAlchemyObjectType):
class Meta:
abstract = True
@classmethod
def get_node(cls, info, id):
return cls.get_query(info).filter(
and_(cls._meta.model.deleted_at==None,
cls._meta.model.id==id)
).first()
class User(ActiveSQLAlchemyObjectType):
class Meta:
model = UserModel
class Query(graphene.ObjectType):
users = graphene.List(User)
def resolve_users(self, info):
query = User.get_query(info) # SQLAlchemy query
return query.all()
schema = graphene.Schema(query=Query) Full ExamplesTo learn more check out the following examples: ContributingSee CONTRIBUTING.md |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论