graphql在 django中的实现(一)

基于已有的 my_django_project, 建立一个空白分支

$ cd my_django_project

$ git checkout --orphan graphql
切换到一个新分支 'graphql'

$ git log
fatal: bad default revision 'HEAD'

$ git rm -rf .
rm '.commit_template'
rm '.gitignore'
rm 'README.md'
rm 'project_001/app_001/__init__.py'
rm 'project_001/app_001/admin.py'
rm 'project_001/app_001/apps.py'
rm 'project_001/app_001/migrations/__init__.py'
rm 'project_001/app_001/models.py'
rm 'project_001/app_001/tests.py'
rm 'project_001/app_001/views.py'
rm 'project_001/db.sqlite3'
rm 'project_001/manage.py'
rm 'project_001/project_001/__init__.py'
rm 'project_001/project_001/settings.py'
rm 'project_001/project_001/urls.py'
rm 'project_001/project_001/wsgi.py'

## 文件夹 `project_001` 可能不会被删除。如果没有删除,手动删除 `rm -rf project_001`;
## project 中如果没有文件,可能无法commit。此时可以建立一个文件(比如.gitignore或者.commit_template)
$ git commit

安装 graphene-django

$ pip install graphene-django
Collecting graphene-django
  Downloading http://mirrors.aliyun.com/pypi/packages/33/34/1b82fe1752c20d2b375d10299c801b8410f5df5c95dd5c739b38ee49ec88/graphene-django-1.3.tar.gz
Requirement already satisfied: six>=1.10.0 in /root/.virtualenvs/py2.7.13cmdb2.0/lib/python2.7/site-packages (from graphene-django)
Collecting graphene>=1.4 (from graphene-django)
  Downloading http://mirrors.aliyun.com/pypi/packages/3a/12/04b4b89eec5f5dd97d06c2143e5db3ec0801f4b940e69db072dd89de8514/graphene-1.4.1.tar.gz
Requirement already satisfied: Django>=1.6.0 in /root/.virtualenvs/py2.7.13cmdb2.0/lib/python2.7/site-packages (from graphene-django)
Collecting iso8601 (from graphene-django)
  Downloading http://mirrors.aliyun.com/pypi/packages/ef/57/7162609dab394d38bbc7077b7ba0a6f10fb09d8b7701ea56fa1edc0c4345/iso8601-0.1.12-py2.py3-none-any.whl
Requirement already satisfied: singledispatch>=3.4.0.3 in /root/.virtualenvs/py2.7.13cmdb2.0/lib/python2.7/site-packages (from graphene-django)
Collecting graphql-core>=1.1 (from graphene>=1.4->graphene-django)
  Downloading http://mirrors.aliyun.com/pypi/packages/b0/89/00ad5e07524d8c523b14d70c685e0299a8b0de6d0727e368c41b89b7ed0b/graphql-core-1.1.tar.gz (70kB)
    100% |████████████████████████████████| 71kB 280kB/s
Collecting graphql-relay>=0.4.5 (from graphene>=1.4->graphene-django)
  Downloading http://mirrors.aliyun.com/pypi/packages/5e/b0/b91fadc180544fc9e3c156d7049561fd5f1e2211d26fd29033548fd50934/graphql-relay-0.4.5.tar.gz
Collecting promise>=2.0 (from graphene>=1.4->graphene-django)
  Downloading http://mirrors.aliyun.com/pypi/packages/62/a4/d979b8cbfef42b695a9c3851d3d918884fb0d2f84f6c43451311a2acb5bf/promise-2.0.2.tar.gz
Requirement already satisfied: pytz in /root/.virtualenvs/py2.7.13cmdb2.0/lib/python2.7/site-packages (from Django>=1.6.0->graphene-django)
Collecting typing (from promise>=2.0->graphene>=1.4->graphene-django)
  Downloading http://mirrors.aliyun.com/pypi/packages/1c/15/aeaae0c01afa895ad774cfd408eca17818fd753817d433f55385d8e36364/typing-3.6.2-py2-none-any.whl
Building wheels for collected packages: graphene-django, graphene, graphql-core, graphql-relay, promise
  Running setup.py bdist_wheel for graphene-django ... done
  Stored in directory: /root/.cache/pip/wheels/f8/f6/09/8e04b5f33720bd00cfc5422090472243033f32658e033b78db
  Running setup.py bdist_wheel for graphene ... done
  Stored in directory: /root/.cache/pip/wheels/40/45/84/4da96e789ddd5cf2fc85d594f1ff96c619da1fd2570fe01bf9
  Running setup.py bdist_wheel for graphql-core ... done
  Stored in directory: /root/.cache/pip/wheels/a8/2d/58/060e91a49245d5515396f455cdfc15d0c1da5ff489dd23df17
  Running setup.py bdist_wheel for graphql-relay ... done
  Stored in directory: /root/.cache/pip/wheels/3a/6b/db/bc482e6a5c41aa0aaa9bcc3626a95f774771d4baeac707f13e
  Running setup.py bdist_wheel for promise ... done
  Stored in directory: /root/.cache/pip/wheels/12/2f/d7/d0f8c817cb6dc37eab930c880f6a9d2b76902703b1a50fa9cd
Successfully built graphene-django graphene graphql-core graphql-relay promise
Installing collected packages: typing, promise, graphql-core, graphql-relay, graphene, iso8601, graphene-django
Successfully installed graphene-1.4.1 graphene-django-1.3 graphql-core-1.1 graphql-relay-0.4.5 iso8601-0.1.12 promise-2.0.2 typing-3.6.2

建立一个project dmyz

$ django-admin startproject dmyz

$ cd dmyz/
## 执行migrate创建表
$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying sessions.0001_initial... OK


## 建立用户。
$ python manage.py createsuperuser
Username (leave blank to use 'root'): root
Email address:
Password:
Password (again):
Superuser created successfully.

## 为方便后续测试,可以建立多个用户

$ python manage.py createsuperuser
Username: jiaxiaolei
Email address:
Password:
Password (again):
Superuser created successfully.
$ python manage.py createsuperuser
Username: wkp
Email address:
Password:
Password (again):
Superuser created successfully.
$ python manage.py createsuperuser
Username: wzb
Email address: wzb@qq.com
Password:
Password (again):
Superuser created successfully.

编辑settings.py,将graphene-django加入INSTALLED_APPS:

INSTALLED_APPS = (
    # ...
    'graphene_django',
)

再编辑urls.py,导入GraphQLView,加上graphql的设置:

from graphene_django.views import GraphQLView

urlpatterns = [
    # ...
    url(r'^graphql', GraphQLView.as_view(graphiql=True)),
]
$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
August 24, 2017 - 02:16:46
Django version 1.11.3, using settings 'dmyz.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

在浏览器中输入: http://172.28.32.49:8000/graphql(主机ip为172.28.32.49), 提示访问失败:

ERR_CONNECTION_REFUSED

修改 runserver 的启动参数:

$ python manage.py runserver 0.0.0.0:8000

在浏览器中访问,提示:

DisallowedHost

修改 settings.py, 允许所有host访问。

#ALLOWED_HOSTS = ['*']
ALLOWED_HOSTS = []

再次访问 /graphql会报错,显示没有提供schema。

$ python manage.py runserver 0.0.0.0:8000
Performing system checks...

System check identified no issues (0 silenced).
August 24, 2017 - 02:17:14
Django version 1.11.3, using settings 'dmyz.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
Not Found: /
[24/Aug/2017 02:17:17] "GET / HTTP/1.1" 404 2020
Internal Server Error: /graphql
Traceback (most recent call last):
  File "/root/.virtualenvs/py2.7.13cmdb2.0/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/root/.virtualenvs/py2.7.13cmdb2.0/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/root/.virtualenvs/py2.7.13cmdb2.0/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/root/.virtualenvs/py2.7.13cmdb2.0/lib/python2.7/site-packages/django/views/generic/base.py", line 62, in view
    self = cls(**initkwargs)
  File "/root/.virtualenvs/py2.7.13cmdb2.0/lib/python2.7/site-packages/graphene_django/views.py", line 84, in __init__
    assert isinstance(self.schema, GraphQLSchema), 'A Schema is required to be provided to GraphQLView.'
AssertionError: A Schema is required to be provided to GraphQLView.
[24/Aug/2017 02:17:31] "GET /graphql HTTP/1.1" 500 73787

在dmyz目录中新建schema.py文件,目录结构如下:

dmyz
├── db.sqlite3
├── dmyz
│   ├── __init__.py
│   ├── schema.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── manage.py

编辑schema.py文件,导入DjangoObjectType和graphene,处理django自带的User Model,代码如下:

from django.contrib.auth.models import User as UserModel

from graphene_django import DjangoObjectType
import graphene

class User(DjangoObjectType):
    class Meta:
        model = UserModel

class Query(graphene.ObjectType):
    users = graphene.List(User)

    @graphene.resolve_only_args
    def resolve_users(self):
        return UserModel.objects.all()

schema = graphene.Schema(query=Query)

最后编辑settings.py,加上配置:

GRAPHENE = {
    'SCHEMA': 'dmyz.schema.schema'
}

现在重新访问/graphql,可以看到自带的前端界面,在左上方文本框中输入:

{
  users {
    username
    email
  }
}

运行(点击上方![▶️]按钮)返回admin用户的username和email。右侧的Docs会显示Query信息,下划线命名也会自动转成驼峰命名。
查询语句完整格式是 query 名称{},上面的查询语句省掉了query,因为GraphQL默认会作为query语句执行,如果是mutation就需要加上了。关于查询语句可以参考官方文档:http://graphql.org/learn/queries/

扩展阅读:

GRAPHQL+DJANGO提供基本API
http://dmyz.org/archives/778
简介:

graphql 在 django 中的实现。这个例子操作性很强,照着操作就可以实现。很好用。

https://github.com/graphql-python/graphene-django
简介:
github上graphene-django的地址。其中有几个实用的demo,还是很有用的。
在django中,实现一个功能的插件很多,但并不是每个插件都好用。需要自己去踩坑。
有些插件由个人维护,后续的更新和维护也是件比较烦人的事情。

http://graphql.org/learn/queries/
简介:

graphql 官方文档,可以看到查询语句的API.

Queries and Mutations
On this page, you'll learn in detail about how to query a GraphQL server.

在GIT中创建一个空分支
https://segmentfault.com/a/1190000004931751
简介:
建立一个空分支。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容