【问题标题】:What is a best practice to receive JSON input in Django views?在 Django 视图中接收 JSON 输入的最佳实践是什么?
【发布时间】:2014-02-22 16:47:52
【问题描述】:

我试图在 Django 的视图中接收 JSON 作为 REST 服务。我知道有相当成熟的 REST 库(例如 Django REST Framework)。但我需要使用 Python/Django 的默认库。

【问题讨论】:

  • 两者,POST 和 GET

标签: python json django rest


【解决方案1】:

request.POST是django预处理的,所以你想要的是request.body。使用 JSON 解析器对其进行解析。

import json

def do_stuff(request):
  if request.method == 'POST':
    json_data = json.loads(request.body)
    # do your thing

【讨论】:

  • 这会导致 Python 3 中的 TypeError: the JSON object must be str, not 'bytes'
  • @gtd 谢谢!您需要先对其进行解码:json.loads(request.body.decode("utf-8"));请参阅stackoverflow.com/questions/29514077/… 了解更多详情。
【解决方案2】:

使用HttpResponse 将响应发送到浏览器而不刷新页面。

views.py

from django.shortcuts import render, HttpResponse,

import simplejson as json

def json_rest(request):
   if request.method == "POST":
      return HttpResponse(json.dumps({'success':True, 'error': 'You need to login First'}))
   else:
      return render(request,'index.html')

urls.py

(r^'/','app.views.json_rest')

客户端:

$.ajax({
     type:"post",
     url: "/",
     dataType: 'json',
     success: function(result) {
         console.log(result)    

       }
});

【讨论】:

  • 您在谈论响应。对于响应,我有以下机制:@json def feed_one(request, id): sample = get_object_or_404(Sample, pk=id) return sample
  • @json 是装饰器,看起来像:def json(fn): def wrapper(request, *args, **kwargs): try: fn_result = fn(request, *args, **kwargs) json_result = {'is_successful': True, 'message': None, 'data': fn_result} except Exception as e: if DEBUG: raise e json_result = {'is_successful': False, 'message': e.message, 'data': None} return HttpResponse(to_json(json_result), mimetype='application/json') return wrapper 现在我正在编写响应 hadnling 机制,需要类似于上面显示的代码。
猜你喜欢
  • 2019-08-11
  • 2013-10-04
  • 1970-01-01
  • 1970-01-01
  • 2016-07-17
  • 1970-01-01
  • 2010-11-16
  • 2021-01-20
  • 2015-02-09
相关资源
最近更新 更多