背景
測試工具箱寫到一半,今天遇到了一個前后端數據交互的問題,就一起做一下整理。
環境
--------------------------------------------------------
版本相關
操作系統: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 []
新聞熱點
疑難解答