项目作者: graphql-python

项目描述 :
Graphene MongoEngine integration
高级语言: Python
项目地址: git://github.com/graphql-python/graphene-mongo.git
创建时间: 2018-01-22T04:06:16Z
项目社区:https://github.com/graphql-python/graphene-mongo

开源协议:MIT License

下载


Build Status Coverage Status Documentation Status PyPI version PyPI pyversions Downloads

Lint Test Package

Graphene-Mongo

A Mongoengine integration for Graphene.

Installation

For installing graphene-mongo, just run this command in your shell

  1. pip install graphene-mongo

Examples

Here is a simple Mongoengine model as models.py:

  1. from mongoengine import Document
  2. from mongoengine.fields import StringField
  3. class User(Document):
  4. meta = {'collection': 'user'}
  5. first_name = StringField(required=True)
  6. last_name = StringField(required=True)

To create a GraphQL schema and sync executor; for it you simply have to write the following:

  1. import graphene
  2. from graphene_mongo import MongoengineObjectType
  3. from .models import User as UserModel
  4. class User(MongoengineObjectType):
  5. class Meta:
  6. model = UserModel
  7. class Query(graphene.ObjectType):
  8. users = graphene.List(User)
  9. def resolve_users(self, info):
  10. return list(UserModel.objects.all())
  11. schema = graphene.Schema(query=Query)

Then you can simply query the schema:

  1. query = '''
  2. query {
  3. users {
  4. firstName,
  5. lastName
  6. }
  7. }
  8. '''
  9. result = await schema.execute(query)

To create a GraphQL schema and async executor; for it you simply have to write the following:

  1. import graphene
  2. from graphene_mongo import AsyncMongoengineObjectType
  3. from graphene_mongo.utils import sync_to_async
  4. from concurrent.futures import ThreadPoolExecutor
  5. from .models import User as UserModel
  6. class User(AsyncMongoengineObjectType):
  7. class Meta:
  8. model = UserModel
  9. class Query(graphene.ObjectType):
  10. users = graphene.List(User)
  11. async def resolve_users(self, info):
  12. return await sync_to_async(list, thread_sensitive=False,
  13. executor=ThreadPoolExecutor())(UserModel.objects.all())
  14. schema = graphene.Schema(query=Query)

Then you can simply query the schema:

  1. query = '''
  2. query {
  3. users {
  4. firstName,
  5. lastName
  6. }
  7. }
  8. '''
  9. result = await schema.execute_async(query)

To learn more check out the following examples:

Contributing

After cloning this repo, ensure dependencies are installed by running:

  1. pip install -r requirements.txt

After developing, the full test suite can be evaluated by running:

  1. make test