python django中,使用POST,利用json进行传输数据实例

本文介绍如何在Python Django中通过POST方法利用JSON传输数据。客户端发送JSON数据时,需注意request.body接收的数据为bytes类型并进行decode,同时为避免POST请求的403错误,需添加@csrf_exempt装饰器。

<span style="font-family: Arial, Helvetica, sans-serif;">在项目中,往往需要利用python的httplib2和urllib进行传输数据。传输数据时,可以利用json传输dict数据,可以降低服务端解析数据的难度。下面是一个实例:</span>

客户端:

import json, urllib
from httplib2 import Http

class client(object)
	node_info = {'ID': 'abcdefg', 'name': 'node1'}
	cfstats_info = {'read':'1 time', 'write': '2 times'}
	def post_cfstats_info(self):

	    cfstats_info = self.get_cfstats_info()
	    content = {'node_info': self.node_info,
	               'cfstats_info': self.cfstats_info,
	               }
	    path = '/getdata/cfstats'
	    self.send_post(content, path)         

	def send_post(self, body, path):
	    """ post data"""
	    headers = {"Content-type": "application/x-www-form-urlencoded",
	               "Accept": "text/plain"}
	    url = 'http://' + self.host + ":" + self.port + path
	    body = json.dumps(body)
	    response, content = Http().request(
	        url, method="POST", headers=headers, body=body
	    )

服务端:

from django import http
import json, urllib
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def get_cfstats_info(request):
    if request.method != 'POST':
        return http.HttpResponse("BAD request")
    print(request.POST.get('cfstats_info'))
    content = request.body.decode()
    content = json.loads(content)
    node_info = content['node_info']
    cfstats_info = content['cfstats_info']
<p>
</p>

需要注意的是,其中request.body接受的数据时bytes类型,需要对其进行decode。此外,因为是post,需要加上@csrf_exempt才不会出现403错误


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值