国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Django接受前端數據的幾種方法總結

2020-02-23 01:42:09
字體:
來源:轉載
供稿:網友

背景

測試工具箱寫到一半,今天遇到了一個前后端數據交互的問題,就一起做一下整理。

環境

--------------------------------------------------------

版本相關

操作系統:Mac OS X EI Caption

Python版本:2.7

IDE:PyCharm

Django: 1.8.2

---------------------------------------------------------

注: 我測試的是Get方法,POST方法也同樣適用

字符型

字符型的數據相對好獲取,前端傳遞的方法如下:

sendData = {
  "exporttype": exporttype,
  "bugids": bugids,
  "test": JSON.stringify({"test": "test"})
};

在Django的后端只要使用exporttype = request.GET.get("exporttype")

就能正常的獲取到這個數據了。

注意: 在Python2.7中數據是unicode編碼的,如果要使用,有時候需要進行轉str

結果示例:

Excle <type 'unicode'>

數組型

獲取數組型的數據如果使用獲取字符串的數據的方法,打出的結果是None。我們要使用這個方法:

bugids = request.GET.getlist("bugids[]")

這樣獲取的數據就是數組類型。

注意: 獲取的數組中的元素是unicode編碼的,在某些時候使用需要轉編碼

結果示例:

•傳遞的url

[14/Jul/2016 11:00:41]"GET /testtools/exportbug/?exporttype=Excle&bugids%5B%5D=102&bugids%5B%5D=101&bugids%5B%5D

•獲取的數據

[u'102', u'101', u'100', u'99', u'98', u'97', u'96', u'95', u'94', u'93', u'92', u'91', u'90', u'89', u'88', u'87'

字典型

字典型數據其實可以當成字符串數據來處理,獲取到對應字符串后使用JSON模塊做一下格式化就行了。

對于前端來說,傳遞字典型的數據就是傳遞JSON數據,所以使用的方法是:

"test": JSON.stringify({"test": "test"})

結果示例:

{"test":"test"} <type 'unicode'>

相關源碼

•Get方法

Get方法是wsgi里面的一個方法。

def GET(self):    # The WSGI spec says 'QUERY_STRING' may be absent.    raw_query_string = get_bytes_from_wsgi(self.environ, 'QUERY_STRING', '')    return http.QueryDict(raw_query_string, encoding=self._encoding)

最終返回的是一個http.QueryDict(raw_query_string, encoding=self._encoding)http的原始數據,而QueryDict繼承于MultiValueDict ,所以我們直接看MultiValueDict就好了。

•MultiValueDict

其實源碼看起來并不難。

def get(self, key, default=None):    """    Returns the last data value for the passed key. If key doesn't exist    or value is an empty list, then default is returned.    """    try:      val = self[key]    except KeyError:      return default    if val == []:      return default    return val  def getlist(self, key, default=None):    """    Returns the list of values for the passed key. If key doesn't exist,    then a default value is returned.    """    try:      return super(MultiValueDict, self).__getitem__(key)    except KeyError:      if default is None:        return []      return default  def __getitem__(self, key):    """    Returns the last data value for this key, or [] if it's an empty list;    raises KeyError if not found.    """    try:      list_ = super(MultiValueDict, self).__getitem__(key)    except KeyError:      raise MultiValueDictKeyError(repr(key))    try:      return list_[-1]    except IndexError:      return []            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 广昌县| 隆回县| 岳西县| 沐川县| 民权县| 封丘县| 高平市| 天柱县| 灯塔市| 石台县| 社旗县| 红桥区| 竹北市| 石首市| 泗水县| 长海县| 裕民县| 中方县| 容城县| 沈丘县| 石家庄市| 鄂尔多斯市| 亳州市| 鲁甸县| 海伦市| 新乡市| 洛川县| 定兴县| 绥化市| 松阳县| 山东省| 霍林郭勒市| 盱眙县| 新民市| 噶尔县| 明溪县| 枣庄市| 江永县| 醴陵市| 玉山县| 海口市|