【问题标题】:How to return data from an API in Django?如何从 Django 中的 API 返回数据?
【发布时间】:2016-12-19 14:07:03
【问题描述】:

我正在尝试学习如何在 Django 中使用 API,并且我想从一个网页中的 html 中返回一些简单的数据。该 API 是 Mozscape,在终端中运行它时,可以获得 100 分的网站得分,如下所示:

from mozscape import Mozscape

client = Mozscape(
    'api_user_id',
    'secret_key')

url = 'http://www.google.com'

get_da = client.urlMetrics(url, cols=68719476736)

print(get_da)

这会打印以下内容

{u'pda': 100}

“100”是我想要的全部。我希望用户在 Django 页面中的表单中输入 url 并获取该分数 int,因此我制作了以下模型、视图和表单

class DomainAuthority(models.Model):
    url = models.URLField(max_length=300)


    def __str__(self):
        return self.url

    class Meta:
        verbose_name = 'Domain'
        verbose_name_plural = 'Domains'

views.py

def DomainAuthorityView(request):


    form = DomainAuthorityForm(request.POST or None)


    if form.is_valid():
        new_domain = form.save(commit=False)
        new_domain.save()


    return render(request, 'domain_authority.html', {'form': form})

forms.py

class DomainAuthorityForm(forms.ModelForm):
    class Meta:
        model = DomainAuthority 
        fields = ['url']

所以我的表单可以正常工作,当在 html 表单中输入 url 时,它会保存在管理后端,但我现在不知道该怎么做是如何将该 url 传递到 Mozscape API,以便我可以获得得分。

我查看了 Django rest 框架并安装了它,并在 Youtube 和其他地方观看了一些快速教程视频,但在这些示例中,他们将保存的 Django 对象(例如博客文章)作为 JSON 数据返回,这不是什么我想做。

我尝试将 API 导入到视图文件中,然后将此行添加到视图中

get_da = client.urlMetrics(new_domain, cols=68719476736)

但是在网页的表单中输入网址后出现此错误

<DomainAuthority: https://www.google.com> is not JSON serializable

我需要在这里做什么才能将用户输入的 url 传递给 API 并在网页中返回正确的响应?

谢谢

编辑 - 截至 8 月 19 日的更新视图

def DomainAuthorityView(request):


    form = DomainAuthorityForm(request.POST or None)


    if form.is_valid():
        new_domain = form.save(commit=False)
        new_domain.save()


        response = requests.get(new_domain.url, cols=68719476736)
        #response = requests.get(client.urlMetrics(new_domain.url,  cols=68719476736))
        json_response = response.json()

        score = json_response['pda']

        return render(request, 'domain_authority_checked.html', {'score': score})

    else:

    return render(request, 'domain_authority.html', {'form': form})

所以现在它应该在使用 url 成功完成表单后重定向,并将 url 传递给 API 以获取分数并重定向到“domain_authority_checked.html”

{{ score }}

所以我在这里有两个结果,如果我将“client.urlMetrics”传递给响应,我可以加载“domain_authority.html”,但是在他输入到表单中的 url 之后,错误页面会返回此

InvalidSchema at /domainauthority/
No connection adapters were found for '{'pda': 100}'

如果我不将“client.urlMetrics”传递给响应,那么 Django 不知道“cols”是什么并返回这个

TypeError at /domainauthority/
request() got an unexpected keyword argument 'cols'

【问题讨论】:

  • 错误的原因是new_domain 是一个DomainAuthority 实例,而不是urlMetrics() 函数所期望的字符串。您应该将其称为urlMetrics(new_domain.url)。现在,您是将调用结果存储在数据库中,还是仅在视图中使用?
  • 谢谢你,我要试试下面的答案,来回答你的问题我真的很想尝试两个,所以把分数保存到数据库中并在视图中使用它

标签: python json django api


【解决方案1】:

我建议这种方法:

import requests

response = requests.get(url)
json_response = response.json()

score = json_response['key_name']

然后您可以简单地呈现模板,将分数添加到模板上下文并使用 {{ }} 显示值。

您可能还想定义一个 rest_framework 序列化程序(否则您不需要 django_rest_framework)并验证针对此序列化程序的响应,以确保您收到了预期的结果:

serializer = MySerializer(data=json_response)
  if serializer.is_valid():
      score = json_response['key_name']

【讨论】:

  • 好的,你能澄清一下'key_name'应该是什么,因为我不清楚,谢谢
  • 通常,API 会返回 json 解析的数据。例如。 {'key_name','值'}。您必须检查您正在查询的 api 的返回,例如使用 curl 并相应地设置 key_name (实际上 api 经常返回几个字段)
  • 不,仍然 v.stuck tbh 并且不确定我在这里做什么,你能看到我上面编辑的代码吗?我不确定我是否以正确的方式进行此操作,'pda' 是 API 中得分的关键(我认为)。
  • 我看到您编辑的视图的第 6 行和第 7 行有重复项。这两个做同样的事情:查询 api。您应该删除第 6 行(从 get_da 开始)并将 cols 参数添加到下面的行。此外,您需要将 score 变量添加到上下文中,就像您对表单所做的那样,否则您无法使用模板标签 {{ }} 在模板中显示它
  • 你的渲染应该是这样的:return render(request, 'domain_authority.html', {'form': form, 'score': score})
【解决方案2】:

你可以使用:

return HttpResponse(json.dumps(data), content_type='application/json')

而不是渲染表单。只需要在 header 中导入 json 并创建一个名为“data”的空 dict。

【讨论】:

    猜你喜欢
    • 2021-05-02
    • 1970-01-01
    • 2020-10-22
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 2017-09-02
    • 2018-08-05
    相关资源
    最近更新 更多