Django API 请求 [英] Django API Requests

查看:20
本文介绍了Django API 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问另一个服务的 API,使用我的模型字段作为 API 请求中的关键字.URL 如下所示:

http://api.example.com/json/?first_name=FNAME&last_name=LNAME&key={key}

这是我在 views.py 中的代码:

class ExamplePersonView(ListView):context_object_name = "example_person"template_name = "模板/example_person.html"def get_queryset(self):lname = get_object_or_404(ExamplePeople, lname__iexact=self.args[0])返回 ExamplePeople.objects.filter(lname=lname)

据我所知,我需要使用 AJAX 在我的页面模板和我的 views.py 之间进行通信以发送请求,然后在页面上显示信息.

我发现了几个 Django 应用程序,它们可以轻松地将您的模型转换为公共 API,但没有一个可以帮助您从其他服务访问 API.有没有人知道这样的应用程序?

如果没有,有没有人对使用 AJAX 和 Django 发出请求并在模板中呈现它有很好的理解?

解决方案

有几种方法可以与外部"API 进行通信.没有必要使用ajax.Ajax 仅用于在模板中进行后台调用,触发您想到的任何事件.

但假设您想与 facebook GraphAPI 通信以检索个人资料

http://graph.facebook.com/bill.clinton

标准结果被序列化为 JSON,它可以轻松实现到 AJAX 或任何 JavaScript 库中,因此名称为 JavaScript Object Notation.

AJAX 的一个例子可能是:

function callFacebook() {$.ajax({类型:获取",数据: ({}),数据类型:'json',网址:http://graph.facebook.com/bill.clinton",成功:功能(数据){alert("我是前任"+data.name);}});}调用脸书();

在您的 javascript 文件中或在脚本标签之间的模板中包含此内容,您应该会收到一条很好的警报消息:

<块引用>

我是前总统比尔克林顿

现在你可以把这个警报变成更有意义的东西,并将它放在一个 h1 标签中(不知道为什么这很有意义)

$("body").html("

"+data.name+"

");

但有时您希望检索数据并在您的应用程序的服务器端对其进行处理.

所以创建一个 django urlpattern 并查看,例如:

from urllib2 import urlopen从 django.http 导入 HttpResponse从 django.utils 导入 simplejsondef call_bill(请求):url = "http://graph.facebook.com/bill.clinton"json = urlopen(url).read()# 做你想做的返回 HttpResponse(simplejson.dumps(json), mimetype="application/json")# 将此添加到您的网址模式url("^call_bill_clinton/$", call_bill)

现在访问您的网址

作为逻辑结果,也完全有可能通过某些用户操作触发异步事件.例如,前面提到的 ajax 示例中的 URL 参数也可以是像/call_bill_clinton/"这样的 django url.

<button onclick="callFacebook();">Call Bill</button>函数调用Facebook(){$.ajax({类型:获取",数据: ({}),数据类型:'json',url: "/call_bill_clinton/",成功:功能(数据){alert("我以前是"+data.name+",我来自Django");}});)//移除自动调用

此外,ajax 调用可以让你做与 http 请求相同的技巧,你可以使用多种请求方法结合很酷的 javascript 事件,比如 beforeSend 事件

 beforeSend: function() {$('#loading').show();},

#loading 可能是这样的:

 

I'm trying to access another service's API, using my model's fields as the keywords in the API request. The URL would be like like so:

http://api.example.com/json/?first_name=FNAME&last_name=LNAME&key={key}

Here's my code from views.py:

class ExamplePersonView(ListView):

    context_object_name = "example_person"
    template_name = "templates/example_person.html"

    def get_queryset(self):
        lname = get_object_or_404(ExamplePeople, lname__iexact=self.args[0])
        return ExamplePeople.objects.filter(lname=lname)

From what I understand, I'll need to use AJAX to communicate between my page template and my views.py to send the request and then present the information on the page.

I've found several Django apps that make it easy to turn your models into a public API, but none that help you access API's from another service. Does anyone know of an app like that?

If not, does anyone have a good understanding of using AJAX with Django to make the request and present it in the template?

解决方案

There's several ways to communicate with a "foreign" API. There's no necessity for ajax. Ajax is just for making background calls in a template, triggering whatever event you have in mind.

But let's say you want to communicate with the facebook GraphAPI to retrieve a profile

http://graph.facebook.com/bill.clinton

The standard result is serialized as JSON, which implements easily into AJAX or any JavaScript library, hence the name JavaScript Object Notation.

So an example with AJAX might be:

function callFacebook() {
    $.ajax({
        type: "GET",
        data: ({}),
        dataType: 'json',
        url: "http://graph.facebook.com/bill.clinton",
        success: function(data){
            alert("Hi I am former "+data.name);
        }
    });
}
callFacebook();

Include this in your javascript file or within your template between script tags and you should get a nice alert message:

Hi I am former President Bill Clinton

Now you could turn this alert into something more meaningful, and put it within a h1 tag (not sure why this is meaningful)

$("body").html("<h1>"+data.name+"</h1>");

But sometimes you would want to retrieve data and do something with it server side in your application.

So create a django urlpattern and view, e.g.:

from urllib2 import urlopen
from django.http import HttpResponse
from django.utils import simplejson    

def call_bill(request):
    url = "http://graph.facebook.com/bill.clinton"
    json = urlopen(url).read()
    # do whatever you want
    return HttpResponse(simplejson.dumps(json), mimetype="application/json")

# add this to your url patterns
url("^call_bill_clinton/$", call_bill)

Now visit your url

As a logic result, it's also perfectly possible to trigger async events by some user action. Eg the URL parameter in the previously mentioned ajax example, could also be a django url like "/call_bill_clinton/".

<!-- add a button to call the function -->
<button onclick="callFacebook();">Call Bill</button>

function callFacebook() {
    $.ajax({
        type: "GET",
        data: ({}),
        dataType: 'json',
        url: "/call_bill_clinton/",
        success: function(data){
            alert("Hi I am former "+data.name+" and I came from Django");
        }
    });
)
// remove the auto call

Furthermore ajax calls let you do the same trickery as http requests, you can use a variety of request methods combined with cool javascript events, like a beforeSend event

    beforeSend: function() {
        $('#loading').show();
    },

Where the #loading could be something like:

   <div id="loading" style="display:none;">
        <img src="{% static "images/loading.gif" %}" />
    </div>

这篇关于Django API 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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