在 Django REST 服务器端使用 API,并在 Angular 客户端提供它 [英] Consume an API in Django REST, server side, and serve it ,client side, in Angular

查看:21
本文介绍了在 Django REST 服务器端使用 API,并在 Angular 客户端提供它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 API 客户端的 Angular 应用程序.由于这样做是不好的做法(我不想公开我的 API 凭据),因此我决定在 myapp 变大之前拆分为后端/前端.我成功地将我的 Angular 实现到 Django REST 框架应用程序中,并且一切正常.但是现在我需要更改我的 API 逻辑并让 DRF 使用外部 API

I have an Angular app that consume API client side. Since it's bad practice to do so (I don't want to expose my API credentials), I decided to split into backend/ frontend before myapp get to big. I succeed to implement my Angular into a Django REST framework app and everything is working fine. But now I need to change my API logic and have DRF consume the external API

我有:

Angular <---API--->外部数据

Angular <---API---> ext data

现在我有:

Django/Angular <---API--->外部数据

Django/ Angular <---API---> ext data

我需要什么:

Angular <---API--->Django <---API--->外部数据

Angular <---API---> Django <---API---> ext data

但是我对如何完成它感到非常困惑.我有在 DRF 中设置 API 端点的经验,但仅限于来自 DRF 中模型的数据.我也知道如何在 Django 中使用 API.但是如何链接两个 API 调用呢?我是否必须创建一个模型来存储查询和响应?即使返回的数据一直都是json,我是否需要编写序列化程序?既然来自外部 API 的数据可用,我的前端将如何?

But I am very confused about how to accomplish it. I have experience with setting up API endpoints in DRF, but only for data from models within DRF. I know as well how to consume API in Django. But how can I chain two API calls? Do I have to create a model to store the queries and then the response? Do I need to write serializers even if the returned data is json all the way? How my frontend will now that the data from the external API is available?

我需要有人向我解释这项任务的模式是什么.

What I need is someone to explain me what is the pattern for this task.

推荐答案

假设您有一个 FBV 映射到 django 中的 URL,如下所示:

Say you have a FBV mapped to an URL in django like this:

url:/api/animals/

@add_decorators_as_needed
def animals_view(request, key=None):
  data = requests.get(f'{API_URL}/{key}?api_key={API_KEY}') # grab data from ext provider
  json_data = ... # convert to json or do other manipulations

  return json_data # return data to the frontend

然后在前端,您的 Angular 应用程序中,您可以对 django 应用程序的这个 /api/animals/cow url 执行 get 请求,并从外部提供程序检索奶牛的数据,而无需暴露你的 API_KEY.

Then in the frontend, your Angular app, you can execute a get request to this /api/animals/cow url of your django app and retrieve the data for a cow from the external provider without exposing your API_KEY.

所以流程是这样的:

Angular 从 Django 请求数据,Django 从外部提供者那里获取数据,如果需要,进行一些数据处理,然后将该数据返回给 Angular.您不必在数据库中存储任何内容(但您当然可以这样做或例如记录内容,这是可选的).

Angular requests data from Django, Django gets that data from the external provider, does some data processing if required and then returns that data to Angular. You do not have to store anything in the database (but you can of course do it or for example log things, it's optional).

这篇关于在 Django REST 服务器端使用 API,并在 Angular 客户端提供它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆