使用angular$http和django-urlpatters来获得json文件

use angular $http with django urlpatterns to get a json file

本文关键字:json 文件 django-urlpatters angular http 使用      更新时间:2023-09-26

我要做的是向django-url模式发送一个$http GET请求,并返回一个.json文件。我可以使用urlpatters返回文件而不是视图吗?

这可能吗?

目前表单/数据返回500

testModule.js

angular.module('mod1', ['mod2'])
.controller('resorcesCtrl', ['mod2Factory',
     function(mod2Factory) {
        mod2Factory.getJSON();
     }
]);

angular.module('mod2', [])
   .factory('mod2Factory', [ '$http',
      function($http) {
        var getJSON = function() {
           return $http({
           url: "/form/data",
           method: "GET"
        })
      }
      return {
         getJSON:getJSON
      }; 
    }
  ])

urls.py

url(r'^form/data', 'myApp.views.getJSON', name='getJSON'),

views.py

def getJSON(request):
    context = {
        "json": json
    }
    return render(request, '', context)

从Django 1.7开始,有一个名为JsonResponse的新响应对象。

你的观点可以很简单:

from django.http import JsonResponse
def getJSON(request):
    # context is a Python dict.
    context = {
        "key": "value",
        "other_key": 365,
    }
    return JsonResponse(context)

context必须是有效的JSON可序列化对象。有关JsonResponse的更多详细信息,请参阅文档。如果您在序列化方面有任何问题,可以将自己的编码器传递给JsonResponse来处理自定义数据类型,请阅读更多信息。

我更喜欢使用类似的函数

import json
from django.http import HttpResponse
def json_responder(**kwargs):
    return HttpResponse(json.dumps(kwargs), content_type="application/json")
def yourview(request):
    return json_responder(type='error', msg='a message")

并且可以在每个django版本上使用