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

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

问题描述

我有一个使用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

我有:

角度< --- API --->外部数据

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

现在我有

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

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

我需要什么:

角度< --- 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/< str:key>

@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的客户端中提供该API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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