【问题标题】:Django: return query result as apiDjango:将查询结果作为api返回
【发布时间】:2014-06-18 10:59:20
【问题描述】:

我正在尝试使用 Django 构建 API 服务器。我有几张表,需要根据 url 传入的参数运行查询:

http://server.com/api/request/p1=123&p2=321...

服务器会从 url 中提取 p1p2 并使用它们运行查询,然后以 json 或 xml 的形式返回结果。

我尝试过 Tastypie,它很容易设置为从一个模型中检索数据。但我的情况比这要复杂一些,有时我需要运行空间查询。因此,如果我可以运行查询并以 json/xml 形式返回结果,那就太好了!

非常新的后端技术,感谢任何起点的帮助!

谢谢!

[编辑] 只是想让我的情况更清楚。假设我使用qs = cursor.execute(sql) 等运行了一个原始查询,我想将该结果作为 json/xml 返回给 api 调用。我可以用 Tastypie 或 Rest Framework 做到这一点吗?或者我可以在没有 3rd 方框架的任何帮助的情况下做到这一点吗?

【问题讨论】:

    标签: django rest tastypie django-rest-framework


    【解决方案1】:

    这是我使用 return json 的一个视图,你应该可以很容易地适应它:

    import json
    from django.http import HttpResponse
    from django.template.defaultfilters import slugify
    from .models import *
    
    def response_times(request):
        response_data = {}  #Create an empty dictionary
        websites = Website.objects.all()  #Query your models
        for site in websites:  
            key = slugify(site.name)
            response_data[key] = {}
            history = History.objects.filter(website=site)[:60]
            response_data[key]['response_times'] = []
            for response in history:
                response_data[key]['response_times'].append({'time': str(response.time), 'timestamp': response.added.strftime('%s')}) 
        return HttpResponse(json.dumps(response_data), content_type="application/json")
    

    【讨论】:

    • 刚刚试了一下。像魅力一样工作!非常感谢!
    【解决方案2】:

    您似乎在某些模型实例的结果查询集中。因此,您可以指定序列化程序来处理您的模型,并使用它使用 Rest Framework 将模型实例序列化为原生 python 数据。详情请看here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-05
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 2013-10-01
      • 2021-11-10
      • 2016-01-03
      • 1970-01-01
      相关资源
      最近更新 更多