3.Relay tutorial中继教程
Graphene has a number of additional features that are designed to make working with Django really simple.
Graphene还有许多附加功能,这些功能旨在使Django的使用变得非常简单。
Note: The code in this quickstart is pulled from the cookbook example app.
注意:此快速入门中的代码来自cookbook example app.
A good idea is to check the following things first:
一个好主意是首先检查以下事项:
Setup the Django project 设置Django项目
We will setup the project, create the following:
我们将设置项目,创建以下内容:
- A Django project called
cookbook
- 一个名为
cookbook
的Django项目 - An app within
cookbook
calledingredients
- 一个名为
ingredients
的应用程序
# Create the project directory
# 创建项目目录
mkdir cookbook
cd cookbook
# Create a virtualenv to isolate our package dependencies locally
#创建一个virtualenv来在本地隔离包依赖关系
virtualenv env
source env/bin/activate # On Windows use `env\Scripts\activate`
# Install Django and Graphene with Django support
#使用Django支持安装Django和Graphene
pip install django
pip install graphene_django
# Set up a new project with a single application
#使用单个应用程序设置新项目
django-admin.py startproject cookbook . # Note the trailing '.' character
cd cookbook
django-admin.py startapp ingredients
Now sync your database for the first time:
现在第一次同步数据库:
python manage.py migrate
Let’s create a few simple models...
让我们创建几个简单的模型...
Defining our models 定义我们的模型
Let’s get started with these models:
让我们从这些模型开始:
# cookbook/ingredients/models.py
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Ingredient(models.Model):
name = models.CharField(max_length=100)
notes = models.TextField()
category = models.ForeignKey(Category, related_name='ingredients')
def __str__(self):
return self.name
Don’t forget to create & run migrations:
不要忘记创建和运行迁移:
python manage.py makemigrations
python manage.py migrate
Load some test data 加载一些测试数据
Now is a good time to load up some test data. The easiest option will be to download the ingredients.json fixture and place it in cookbook/ingredients/fixtures/ingredients.json
. You can then run the following:
现在是加载一些测试数据的好时机。最简单的选择是下载 ingredients.json固定并放在cookbook/ingredients/fixtures/ingredients.json
. 然后可以运行以下命令:
$ python ./manage.py loaddata ingredients
Installed 6 object(s) from 1 fixture(s)
Alternatively you can use the Django admin interface to create some data yourself. You’ll need to run the development server (see below), and create a login for yourself too (./manage.py createsuperuser
).
或者,您可以使用Django管理接口自己创建一些数据。您需要运行开发服务器(见下文),并为自己创建一个登录名(python manage.py createsuperuser
)。
Schema 架构
GraphQL presents your objects to the world as a graph structure rather than a more hierarchical structure to which you may be accustomed. In order to create this representation, Graphene needs to know about each type of object which will appear in the graph.
GraphQL将您的对象作为一个图结构呈现给世界,而不是一个您可能习惯的更具层次结构的结构。为了创建这种表示,Graphene需要知道将出现在图形中的每种类型对象。
This graph also has a root type through which all access begins. This is the Query
class below. In this example, we provide the ability to list all ingredients via all_ingredients
, and the ability to obtain a specific ingredient via ingredient
.
此图还具有一个根类型,所有访问都通过它开始。这是下面的“Query”类。在本例中,我们提供了通过“all_components”列出所有成分的功能,以及通过“component”获取特定成分的功能。
Create cookbook/ingredients/schema.py
and type the following:
创建 cookbook/ingredients/schema.py
并键入以下内容:
# cookbook/ingredients/schema.py
from graphene import relay, ObjectType
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from ingredients.models import Category, Ingredient
# Graphene will automatically map the Category model's fields onto the CategoryNode.
# Graphene自动将类别模型的字段映射到CategoryNode上。
# This is configured in the CategoryNode's Meta class (as you can see below)
# 这是在CategoryNode的元类中配置的(如下所示)
class CategoryNode(DjangoObjectType):
class Meta:
model = Category
filter_fields = ['name', 'ingredients']
interfaces = (relay.Node, )
class IngredientNode(DjangoObjectType):
class Meta:
model = Ingredient
# Allow for some more advanced filtering here
# 这里允许一些更高级的过滤
filter_fields = {
'name': ['exact', 'icontains', 'istartswith'],
'notes': ['exact', 'icontains'],
'category': ['exact'],
'category__name': ['exact'],
}
interfaces = (relay.Node, )
class Query(graphene.ObjectType):
category = relay.Node.Field(CategoryNode)
all_categories = DjangoFilterConnectionField(CategoryNode)
ingredient = relay.Node.Field(IngredientNode)
all_ingredients = DjangoFilterConnectionField(IngredientNode)
The filtering functionality is provided by django-filter. See the usage documentation for details on the format for filter_fields
. While optional, this tutorial makes use of this functionality so you will need to install django-filter
for this tutorial to work:
过滤功能由django filter提供。有关“filter_fields”格式的详细信息,请参阅使用说明文件。虽然可选,但本教程使用了此功能,因此您需要安装“django filter”才能使用本教程:
pip install django-filter
Note that the above Query
class is marked as ‘abstract’. This is because we will now create a project-level query which will combine all our app-level queries.
请注意,上面的Query
类被标记为“abstract”。这是因为我们现在将创建一个项目级查询,它将合并所有的应用程序级查询。
Create the parent project-level cookbook/schema.py
:
创建父项目级cookbook/schema.py
:
import graphene
import ingredients.schema
class Query(ingredients.schema.Query, graphene.ObjectType):
# This class will inherit from multiple Queries
# 此类将从多个查询继承
# as we begin to add more apps to our project
# 当我们开始向我们的项目中添加更多应用程序时
pass
schema = graphene.Schema(query=Query)
You can think of this as being something like your top-level urls.py
file (although it currently lacks any namespacing).
你可以把这看作是你的高层urls.py
文件(尽管它目前没有任何命名空间)。
Testing everything so far 测试到目前为止的一切
Update settings 更新设置
Next, install your app and GraphiQL in your Django project. GraphiQL is a web-based integrated development environment to assist in the writing and executing of GraphQL queries. It will provide us with a simple and easy way of testing our cookbook project.
接下来,在Django项目中安装应用程序和GraphiQL。GraphiQL是一个基于web的集成开发环境,用于帮助编写和执行GraphQL查询。它将为我们提供一个简单易行的方法来测试我们的菜单项目。
Add ingredients
and graphene_django
to INSTALLED_APPS
in cookbook/settings.py
:
将ingredients
和graphene_django
添加到cookbook/settings.py
中的INSTALLED_APPS
:
INSTALLED_APPS = [
...
# This will also make the `graphql_schema` management command available
#这将使`graphql_schema`管理命令可用
'graphene_django',
# Install the ingredients app
#安装ingredients应用程序
'ingredients',
]
And then add the SCHEMA
to the GRAPHENE
config in cookbook/settings.py
:
然后将SCHEMA
添加到cookbook/settings.py
中的GRAPHENE
:
GRAPHENE = {
'SCHEMA': 'cookbook.schema.schema'
}
Alternatively, we can specify the schema to be used in the urls definition, as explained below.
或者,我们可以指定在url定义中使用的模式,如下所述。
Creating GraphQL and GraphiQL views 创建GraphQL和GraphiQL视图
Unlike a RESTful API, there is only a single URL from which GraphQL is accessed. Requests to this URL are handled by Graphene’s GraphQLView
view.
不同于RESTful API,只有一个URL可以访问GraphQL。对这个URL的请求由Graphene的GraphQLView
视图处理。
This view will serve as GraphQL endpoint. As we want to have the aforementioned GraphiQL we specify that on the params with graphiql=True
.
此视图将用作GraphQL端点。因为我们希望有前面提到的GraphiQL,我们在带有graphiql=True
的参数上指定。
from django.conf.urls import url, include
from django.contrib import admin
from graphene_django.views import GraphQLView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^graphql$', GraphQLView.as_view(graphiql=True)),
]
If we didn’t specify the target schema in the Django settings file as explained above, we can do so here using:
如果我们没有如上所述在Django设置文件中指定目标架构,我们可以在这里使用:
from django.conf.urls import url, include
from django.contrib import admin
from graphene_django.views import GraphQLView
from cookbook.schema import schema
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^graphql$', GraphQLView.as_view(graphiql=True, schema=schema)),
]
Testing our GraphQL schema 测试GraphQL模式
We’re now ready to test the API we’ve built. Let’s fire up the server from the command line.
我们现在已经准备好测试我们构建的API了。让我们从命令行启动服务器。
$ python ./manage.py runserver
Performing system checks...
Django version 1.11, using settings 'cookbook.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Go to localhost:8000/graphql and type your first query!
转到localhost:8000/graphql然后键入您的第一个查询!
query {
allIngredients {
edges {
node {
id,
name
}
}
}
}
The above will return the names & IDs for all ingredients. But perhaps you want a specific ingredient:
上面将返回所有成分的名称和ID。但也许你想要一种特定的成分:
query {
# Graphene creates globally unique IDs for all objects.
# Graphene为所有对象创建全局唯一的ID。
# You may need to copy this value from the results of the first query
# 您可能需要从第一个查询的结果复制此值
ingredient(id: "SW5ncmVkaWVudE5vZGU6MQ==") {
name
}
}
You can also get each ingredient for each category:
您还可以获得每个类别的每种成分:
query {
allCategories {
edges {
node {
name,
ingredients {
edges {
node {
name
}
}
}
}
}
}
}
Or you can get only ‘meat’ ingredients containing the letter ‘e’:
或者你只能得到含有字母e
的meat
配料:
query {
# You can also use `category: "CATEGORY GLOBAL ID"`
# 也可以使用`category: "CATEGORY GLOBAL ID"`
allIngredients(name_Icontains: "e", category_Name: "Meat") {
edges {
node {
name
}
}
}
}
Final Steps 最后步骤
We have created a GraphQL endpoint that will work with Relay, but for Relay to work it needs access to a (non python) schema. Instructions to export the schema can be found on the Introspection Schema part of this guide.
我们已经创建了一个可以使用Relay的GraphQL端点,但是要使Relay工作,它需要访问一个(非python)模式。导出模式的说明可以在本指南的自省模式部分找到。