django 小程序api_如何在现有的Django应用程序上获取即时GraphQL API

django 小程序api

by Karthik Venkateswaran

由Karthik Venkateswaran

如何在现有的Django应用程序上获取即时GraphQL API (How to get instant GraphQL APIs on your existing Django application)

TL; DR (TL;DR)

Here are the topics we’ll cover in this article if you want to jump around:

如果您想跳来跳去,以下是我们将在本文中介绍的主题:

为什么选择GraphQL? (Why GraphQL?)

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开发的一种数据查询语言。 它没有绑定到任何特定的数据库。 它为客户端提供了一种通过请求他们需要的内容同时从不同数据库中进行查询的方法。 它以客户端请求的格式返回响应

建立一个GraphQL服务器 (Build a GraphQL Server)

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的最简单方法。

设置GraphQL引擎 (Setup GraphQL engine)

We’ll go through installing Hasura GraphQL engine. Then we’ll expose tables over a GraphQL API.

我们将安装Hasura GraphQL引擎。 然后,我们将通过GraphQL API公开表。

保护GraphQL服务器 (Securing GraphQL server)
处理迁移 (Handle Migration)

So let’s get started!

因此,让我们开始吧!

为什么选择GraphQL? (Why GraphQL?)

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?

建立一个GraphQL服务器 (Build a GraphQL server)

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.pydjango 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。

安装 (Installation)

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的机器上。 查看入门部分以获取更多信息。

使用docker安装并连接到现有的Postgres (Installation using docker and connecting to existing Postgres)

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:SECUREPASSWORD@172.17.0.1: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"
      }
    ]
  }
}
对象与数组的关系 (Object and Array Relationship)

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_article. mediumAuthorByAuthorId is an “object relationship” based on the same foreign key.

博客架构中mediumArticlesByauthorId是“数组关系”。 它是基于外键medium_article :: author_id -> ID在T he medium_artice. 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模式包含关系名称。 可以在单个查询中查询表和关系:

认证方式 (Authentication)

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-keyauth-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 = usermedium_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-keyauth-hook开头的GraphQL引擎)。

安全的GraphQL API (Secure GraphQL API)

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-rolex-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 <token> and resolve it into a Django user. The user will be added to the request context. Here is the code snippet of the same.

为了撰写本博客,我编写了一个简单的auth中间件。 它将解析Authorization: Bearer <tok en>并将其解析为Django用户。 用户将被添加到请求CON 文本 。 这是相同的代码段。

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-idx-hasura-role 。 GraphQL引擎以访问规则中配置的适当结果进行响应。

迁移系统 (Migration System)

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顺利进行。

建立 (Setup)

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.

endpointaccess-key的值替换为适当的值。

禁用迁移 (Disable migration)

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 changes.

由于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元数据只是为了确保应用程序始终处于可恢复状态:

元数据导出 (Metadata export)

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 migrationsfolder.

上面的命令将导出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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值