django中使用POST方法获取POST数据

yipeiwu_com5年前Python基础

在django中获取post数据,首先要规定post发送的数据类型是什么。

1.获取POST中表单键值数据

如果要在django的POST方法中获取表单数据,则在客户端使用JavaScript发送POST数据前,定义post请求头中的请求数据类型:

xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

在django的views.py相关方法中,需要通过request.POST获取表单的键值数据,并且可以通过reques.body获取整个表单数据的字符串内容

if(request.method == 'POST'):
    print("the POST method")
    concat = request.POST
    postBody = request.body
    print(concat)
    print(type(postBody))
    print(postBody)

相关日志:

the POST method
<QueryDict: {u'username': [u'abc'], u'password': [u'123']}>
<type 'str'>
username=abc&password=123

2.获取POST中json格式的数据

如果要在django的POST方法中获取json格式的数据,则需要在post请求头中设置请求数据类型:

xmlhttp.setRequestHeader("Content-type","application/json");

在django的views.py中导入python的json模块(import json),然后在方法中使用request.body获取json字符串形式的内容,使用json.loads()加载数据。

if(request.method == 'POST'):
    print("the POST method")
    concat = request.POST
    postBody = request.body
    print(concat)
    print(type(postBody))
    print(postBody)
    json_result = json.loads(postBody)
    print(json_result)

相关日志:

the POST method
<QueryDict: {}>
<type 'str'>
{"sdf":23}
{u'sdf': 23}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python输出决策树图形的例子

windows10: 1,先要pip安装pydotplus和graphviz: pip install pydotplus pip install graphviz 2,www.g...

Python2中文处理纪要的实现方法

python2不是以unicode作为基本代码字符类型,碰到乱码的几率是远远高于python3,但即便如此,相信很多人,也不想随意的迁移到python3,这里就总结几个我平常碰到的问题及...

python 字典 按key值大小 倒序取值的实例

如下所示: viedoUrl_dict = {1:'hello',2:'python',3:'nihao'} bit_list = sorted(viedoUrl_dict.keys...

python搜索包的路径的实现方法

查看python搜索包的路径的实现方法: python搜索包的路径存储在sys.path下 查看方法: import sys sys.path 临时添加python搜索包路径的方法: 方...

python 微信好友特征数据分析及可视化

python 微信好友特征数据分析及可视化

一、背景及研究现状 在我国互联网的发展过程中,PC互联网已日趋饱和,移动互联网却呈现井喷式发展。数据显示,截止2013年底,中国手机网民超过5亿,占比达81%。伴随着移动终端价格的下降及...