graphene-objecttype-from-sqlalchemy-table
Transform SQLAlchemy Table
into Graphene ObjectType
.
- Free software: MIT license
Features
The purpose of this library is to allow a lightweight GraphQL schema creation based on database table definitions when full SQLAlchemy ORM cannot be used. It converts Table
columns into their Graphene counterparts and creates the corresponding Graphene ObjectType
to be used as a schema field.
Note that if your application uses SQLAlchemy ORM, graphene-sqlalchemy still offers more features and you could benefit from using it.
Installation
In shell run:
pip install graphene-objecttype-from-sqlalchemy-table
Example usage
Let's start by defining a mock database table.
import sqlalchemy as sa
t = sa.Table(
'test_table',
sa.MetaData(),
sa.Column('foo', sa.String, doc='This will be passed to field description.'),
sa.Column('bar', sa.Integer),
)
Then create a Graphene object type using a Meta class with the reference to the SQLAlchemy table.
from graphene_objecttype_from_sqlalchemy_table import ObjectTypeFromTable
class TestTable(ObjectTypeFromTable):
class Meta:
table = t
And finally define the GraphQL query structure using the new object type.
from graphene import Field, ObjectType, Schema
class Query(ObjectType):
test_table = Field(TestTable)
# custom resolver for the table (probably a database query in a real world application)
# returns a dictionary or an object with attributes corresponding to column names
def resolve_test_table(root, info):
return {'foo': 'Hello world', 'bar': 42}
schema = Schema(query=Query)
# confirm that the query resolves correctly
schema.execute('query { testTable { foo, bar } }')
# {'data': {'testTable': {'foo': 'Hello world', 'bar': 42}}}
It is possible to exclude specific columns from the resulting object by listing them as excluded_columns
or to select only a subset of columns with only_selected_columns
attribute.
class TestTable(ObjectTypeFromTable):
class Meta:
table = t
excluded_columns = ('foo', )
# only_selected_columns = ('bar', )
Credits
This package was created with Cookiecutter and the audreyr/cookiecutter-pypackage project template.