django 小程序api
by Karthik Venkateswaran
由Karthik Venkateswaran
Here are the topics we’ll cover in this article if you want to jump around:
如果您想跳来跳去,以下是我们将在本文中介绍的主题:
GraphQL is a data query language developed by Facebook. It is not tied to any specific database. It provides a way for the client to query from different databases at the same time by requesting what they need. It returns the response in the format requested by the client
GraphQL是Facebook开发的一种数据查询语言。 它没有绑定到任何特定的数据库。 它为客户端提供了一种通过请求他们需要的内容同时从不同数据库中进行查询的方法。 它以客户端请求的格式返回响应
What are the different approaches available to build a GraphQL server? We’ll learn how Hasura GraphQL engine provides the easiest way to get a GraphQL API on your existing database.
构建GraphQL服务器有哪些不同的方法? 我们将学习Hasura GraphQL引擎如何提供在现有数据库上获取GraphQL API的最简单方法。
We’ll go through installing Hasura GraphQL engine. Then we’ll expose tables over a GraphQL API.
我们将安装Hasura GraphQL引擎。 然后,我们将通过GraphQL API公开表。
So let’s get started!
因此,让我们开始吧!
In a typical Django application, any new feature requirements or schema change will require adding to or modifying an existing view. This can have a huge impact on developer productivity. This will require code updates at all the places that a particular API is being consumed.
在典型的Django应用程序中,任何新功能要求或架构更改都将需要添加或修改现有视图。 这会对开发人员的生产力产生巨大影响。 这将要求在使用特定API的所有位置进行代码更新。
This is where GraphQL comes in handy. GraphQL is a query language for APIs. It abstracts multiple data sources. This enables app developers to request data in the format they need. It does this without requiring any backend API changes. Instead of calling individual endpoints to get data we call a single endpoint. We get back all the information we want, structured exactly the way we want it.
这是GraphQL派上用场的地方。 GraphQL是API的查询语言。 它抽象了多个数据源。 这使应用程序开发人员能够以他们所需的格式请求数据。 它不需要任何后端API更改就可以做到这一点。 而不是调用单个端点来获取数据,而是调用单个端点。 我们获取所需的所有信息,并按照所需的方式进行结构化。
So this may make you wonder: how do I get a GraphQL API on my existing Django app?
因此,这可能使您感到奇怪:如何在现有的Django应用程序上获取GraphQL API?
To build a GraphQL server, all you need to do is define a schema. A Schema is a directory of the data types in your application. Resolver functions tell the server where and how to fetch the data for each data type.
要构建GraphQL服务器,您需要做的就是定义一个模式。 模式是应用程序中数据类型的目录。 解析器功能告诉服务器每种数据类型在何处以及如何获取数据。
Current approaches involve writing it from scratch (schema, resolver functions) with the help of tools like django-graphene.
当前的方法包括借助django-graphene等工具从头开始编写(模式,解析器功能)。
In this post, I will use Hasura GraphQL engine to get a GraphQL API on my existing Django application running locally. We will arrive at a solution as shown in the below diagram.
在本文中,我将使用Hasura GraphQL引擎在本地运行的现有Django应用程序上获取GraphQL API。 我们将得出如下图所示的解决方案。
Hasura GraphQL engine (HGE) gives you Instant Real-time GraphQL API on top of your existing Postgres. HGE works out of the box with your existing:
Hasura GraphQL引擎 (HGE)在您现有的Postgres之上为您提供Instant Real-time GraphQL API。 HGE可与您现有的产品一起使用:
Postgres database — Connects with your existing database and provides a GraphQL API to your database.
Postgres数据库 —与现有数据库连接,并为数据库提供GraphQL API。
Authentication system — Connects with your existing authentication system to secure GraphQL API.
身份验证系统 -与您现有的身份验证系统连接以保护GraphQL API。
Migration system — Hasura GraphQL Engine doesn’t interfere with the existing Django’s migration system. The schema can be managed separately through models.py and django migrate until and unless it doesn’t alter the schema tracked by the GraphQL Engine. More info on how Hasura GraphQL engine manages your schema state can be found here.
迁移系统 - Hasura GraphQL引擎不与现有的Django的迁移系统干扰。 可以通过models.py和django migration分别管理模式 直到并且除非它不会改变GraphQL Engine跟踪的模式。 在此处可以找到有关Hasura GraphQL引擎如何管理架构状态的更多信息。
Also, it comes with a nifty console (similar to Django admin) which can be used for debugging GraphQL APIs.
此外,它还带有一个漂亮的控制台(类似于Django admin),可用于调试GraphQL API。
Hasura GraphQL engine can be installed onto Heroku using the button below:
可以使用以下按钮将Hasura GraphQL引擎安装到Heroku:
or onto any machine which can run Docker. Check out the getting-started section for more info.
或任何可以运行Docker的机器上。 查看入门部分以获取更多信息。
Before I install Hasura GraphQL Engine, I need to get the Postgres connection string for the Hasura GraphQL engine to connect with the database. I can get the Postgres connection string from my application’s settings.py
.
在安装Hasura GraphQL Engine之前,我需要获取Postgres连接字符串,以使Hasura GraphQL引擎与数据库连接。 我可以从应用程序的settings.py
获取Postgres连接字符串。
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'SECUREPASSWORD',
'HOST': '172.17.0.1',
'PORT': '5432',
}
}
The database connection URL will become:
数据库连接URL将变为:
postgres://postgres:[email protected]:5432/postgres
Once Hasura GraphQL engine starts, visiting http://localhost:8080 opens Hasura Console as below. The Data section shows a list of untracked tables present in the database grouped by schema. If you are wondering about what untracked tables are, head to the docs for more info.
Hasura GraphQL引擎启动后,访问http:// localhost:8080将打开Hasura控制台,如下所示。 数据部分显示了按模式分组的数据库中存在的未跟踪表的列表。 如果您想知道什么是未跟踪的表,请访问文档以获取更多信息。
The above screenshot lists the tables created by the Django application as defined in this models.py file under untracked tables. Clicking on the add button shows on the list of tracked tables on the left. It exposes them to be queried via GraphQL APIs:
上面的屏幕截图列出了在此models.py中定义的Django应用程序创建的表。 文件放在未跟踪的表格下。 单击添加按钮将在左侧的跟踪表列表中显示。 公开它们以通过GraphQL API查询:
To test whether everything works, let’s try to fetch all the authors
available in the table:
为了测试一切是否正常,让我们尝试获取表中所有可用的authors
:
query {
medium_author {
id
name
interests
}
}
The response from the GraphQL engine is:
GraphQL引擎的响应为:
{
"data": {
"medium_author": [
{
"name": "Karthik",
"id": 2,
"interests": "Cricket, Music, Code"
},
{
"name": "Second Author",
"id": 4,
"interests": "Hockey"
}
]
}
}
GraphQL engine parses your schema and suggests relationships based on the foreign keys defined between tables.
GraphQL引擎解析您的架构并根据表之间定义的外键建议关系。
GraphQL engine automatically suggests two relationships for every foreign key it encounters.
GraphQL引擎针对遇到的每个外键自动建议两个关系。
Object relationship: 1:1 relationship. For example, one article will have only one author.
对象关系 :1:1关系。 例如,一篇文章将只有一位作者。
Array relationship: 1:many. For example, one author can write many articles.
数组关系 :1:很多。 例如,一位作者可以写许多文章。
In the blog schema, mediumArticlesByauthorId
is an “array relationship.” It is based on the foreign key medium_article :: author_id ->
id in the medium_artic
le. mediumAuthorByAutho
rId is an “object relationship” based on the same foreign key.
在博客架构中 , mediumArticlesByauthorId
是“数组关系”。 它是基于外键medium_article :: author_id ->
ID在T he medium_artic
升e. mediumAuthorByAutho
e. mediumAuthorByAutho
rId是基于相同外键的“对象关系”。
When we track these relationships, the derived GraphQL schema contains the relation names. Both tables and relationship can be queried in a single query:
当我们跟踪这些关系时,派生的GraphQL模式包含关系名称。 可以在单个查询中查询表和关系:
By default, GraphQL engine is installed in development mode. All the tables/views which are tracked by the GraphQL engine can be viewed/updated without any checks. This is dangerous and is not recommended for a production environment.
默认情况下,GraphQL引擎以开发模式安装。 无需任何检查即可查看/更新GraphQL引擎跟踪的所有表/视图。 这很危险,不建议在生产环境中使用。
Hasura lets you define granular access controls for every field in your GraphQL schema, basically every table or view in your Postgres schema. These access control rules can use dynamic variables that come in with every request. Check out the docs for more info.
Hasura允许您为GraphQL模式中的每个字段(基本上是Postgres模式中的每个表或视图)定义精细的访问控制。 这些访问控制规则可以使用每个请求附带的动态变量。 查看文档以获取更多信息。
GraphQL engine can be secured from accessing it directly by configuring a webhook URL. This will be called by the GraphQL engine to validate every request unless the request contains a valid access-key
.
通过配置Webhook URL,可以防止GraphQL引擎直接访问它。 除非请求包含有效的access-key
否则GraphQL引擎将调用此方法来验证每个请求。
Before we secure the GraphQL endpoint with access-key
and auth-hook
(webhook URL), let’s add a simple access control rule using Hasura console to restrict the author
to fetch only his data and make a query using the GraphQL explorer.
在使用access-key
和auth-hook
(webhook URL)保护GraphQL端点之前,让我们使用Hasura控制台添加一个简单的访问控制规则,以限制author
仅获取其数据并使用GraphQL Explorer进行查询。
Here is how the access control rule looks like for the medium_author
table for role =user
.
这是role = user
的medium_author
表的访问控制规则。
I have only created the select
permission, but you can configure for all the four types of operation (select, insert, update, delete). Check out the docs for more info.
我仅创建了select
权限,但是您可以为所有四种操作类型(选择,插入,更新,删除)进行配置。 查看文档以获取更多信息。
Let’s query from the medium_author
table and see what the response is:
让我们从medium_author
表中查询,看看响应是什么:
Here, please note that x-hasura-user-id
is set to “2” and x-hasura-role
is set to “user”. This is the auth
data which will be passed by auth-hook
in the production mode (GraphQL engine started with access-key
and auth-hook
).
在此,请注意, x-hasura-user-id
设置为“ 2”, x-hasura-role
设置为“ user”。 这是将在生产模式下由auth-hook
传递的auth
数据(以access-key
和auth-hook
开头的GraphQL引擎)。
Let’s secure the GraphQL engine withaccess-key
. Let's configure auth-hook
with the authentication handler, in this case the Django app. The configured webhook will be invoked by the GraphQL engine. The webhook will return appropriatex-hasura-role
and x-hasura-user-id
.
让我们使用access-key
保护GraphQL引擎。 让我们使用身份验证处理程序(在本例中为Django应用)配置auth-hook
。 配置的网络挂接将由GraphQL引擎调用。 x-hasura-role
将返回适当的x-hasura-role
和x-hasura-user-id
。
version: '3.6'
services:
postgres:
image: postgres
environment:
- "POSTGRES_PASSWORD:mysecretpassword"
ports:
- "5432:5432"
restart: always
volumes:
- db_data:/var/lib/postgresql/data
graphql-engine:
image: hasura/graphql-engine:v1.0.0-alpha13
ports:
- "8080:8080"
depends_on:
- "postgres"
restart: always
environment:
HASURA_GRAPHQL_DATABASE_URL: postgres://postgres:mysecretpassword@postgres:5432/postgres
command:
- graphql-engine
- serve
- --access-key=mysecretkey
- --auth-hook=http://192.168.2.58:9090/validate_request
- --enable-console
volumes:
db_data:
Let’s try to make the query again and see what the response is:
让我们尝试再次进行查询,看看响应是什么:
The configured webhook rejects, as the request is not authenticated. Let’s try to login as a user and make the request with the user’s auth token. Django auth system resolves cookies.
It adds the user info into the request context, which can then be used by the request handler.
由于未验证请求,因此配置的Webhook拒绝。 让我们尝试以用户身份登录,并使用用户的auth令牌发出请求。 Django身份验证系统解析cookies.
它将用户信息添加到请求上下文中,然后供请求处理程序使用。
For the sake of this blog, I have written a simple auth middleware. It will parse Authorization: Bearer
为了撰写本博客,我编写了一个简单的auth中间件。 它将解析Authorization: Bearer
The user is authenticated by the webhook. The webhook returns the corresponding x-hasura-user-id
and x-hasura-role
. GraphQL engine responds with the appropriate results as configured in the access rules.
用户通过Webhook进行身份验证。 x-hasura-user-id
返回相应的x-hasura-user-id
和x-hasura-role
。 GraphQL引擎以访问规则中配置的适当结果进行响应。
Hasura GraphQL engine comes with powerful Rails-inspired migration tooling to help you keep track of the changes you make to your schema. As you use the Hasura console, the Hasura CLI will spit out migration files for you. You can put them in version control and even edit them.
Hasura GraphQL引擎带有受Rails启发的强大迁移工具,可帮助您跟踪对模式所做的更改。 在使用Hasura控制台时,Hasura CLI将为您吐出迁移文件。 您可以将它们置于版本控制中,甚至可以对其进行编辑。
By default, Hasura console is served by the GraphQL engine. It can be used to quickly test out the features provided by the GraphQL engine. However if you are building a complex application or adding Hasura to the existing application or database, you’ll need to store migration to ensure your iteration and CI/CD is smooth.
默认情况下,GraphQL引擎为Hasura控制台提供服务。 它可用于快速测试GraphQL引擎提供的功能。 但是,如果要构建复杂的应用程序或将Hasura添加到现有应用程序或数据库中,则需要存储迁移以确保迭代和CI / CD顺利进行。
Install hasura
by executing the following command on your terminal if you are using a Mac/Linux machine. Otherwise, head to our docs to install hasura on different environments.
如果使用的是Mac / Linux计算机,请在终端上执行以下命令来安装hasura
。 否则,请前往我们的文档在不同的环境中安装hasura。
curl -L https://cli.hasura.io/install.sh | bash
Executing the following command will initialize a directory with hasura configuration files configured to use your GraphQL engine.
执行以下命令将使用配置为使用GraphQL引擎的hasura配置文件初始化目录。
$ hasura init --directory blog-hasura-app --endpoint http://localhost:8080 --access-key=mysecretkey
Replace the value of endpoint
and access-key
to appropriate values.
将endpoint
和access-key
的值替换为适当的值。
Since Django takes care of migrations by default, Hasura migration can be disabled by typing hasura console
on your terminal. To open the Hasura console, navigate to Data ->Migrations (on the left nav bar) and disable Allow postgres schema chan
ges.
由于Django默认情况下负责迁移,因此可以通过在终端上键入hasura console
来禁用Hasura迁移。 要打开Hasura控制台中,导航到数据- > Migratio NS(左侧导航栏上)和disab le Allow postgres schema chan
g ^ ES。
We can still store the Hasura metadata just to ensure the application is always in a recoverable state:
我们仍然可以存储Hasura元数据只是为了确保应用程序始终处于可恢复状态:
Export the Hasura metadata and store it in the migrations folder. This will ensure that your system is always recoverable from any undesirable state.
导出Hasura元数据并将其存储在migrations文件夹中。 这将确保您的系统始终可以从任何不良状态中恢复。
hasura metadata export
The above command will export the metadata.yaml
and store it inside the migrations
folder.
上面的命令将导出metadata.yaml
并将其存储在migrations
文件夹中。
Please ensure that tables/views are created/modified only through the Django models.py file to avoid inconsistency.
请确保仅通过Django models.py文件创建/修改表/视图,以避免不一致。
If you are looking to use Hasura migration system instead, check out the docs for more info.
如果您想使用Hasura迁移系统,请查看文档以获取更多信息。
Hasura gives you instant realtime GraphQL APIs over any Postgres database without having to write any backend code.
Hasura 为您提供任何Postgres数据库上的即时实时GraphQL API,而无需编写任何后端代码。
For those of you who are new to the Hasura GraphQL engine, this is a good place to get started.
对于Hasura GraphQL引擎新手来说, 这是一个入门的好地方。
翻译自: https://www.freecodecamp.org/news/how-to-get-instant-graphql-apis-on-your-existing-django-application-c8fcfdb945aa/
django 小程序api