調試Django框架寫的服務時,需要模擬客戶端發送POST請求,然而瀏覽器只能模擬簡單的GET請求(將參數寫在url內),網上搜索得到了HttpRequester這一firefox插件,完美的實現了模擬POST提交表單的需求,這里記錄一下簡單Django服務的搭建、以及使用HttpRequester對應進行GET/POST請求操作的流程。
1,搭建Django服務
1.1 搭建簡單服務
搭建一個簡單的Django服務很容易,只需要一行命令即可創建一個可運行的Django服務,若未安裝Django,則需要先執行pip install django安裝:
django-admin startproject testsite cd testsite/ python manage.py runserver
服務默認監聽8000端口:
此時的目錄結構如下:
testsite: db.sqlite3 manage.py r testsite: __init__.py settings.py urls.py wsgi.py
1.2 增加自定義模塊
我們手動添加一個子模塊faketest,在其中創建一個urls.py和views.py(還要添加一個空的__init__.py文件,這樣python才會將對應的文件夾識別為一個模塊,允許對其進行調用),實現一個http接口供外部調用,在接口內部對http請求的參數進行輸出並返回:
文件:testsite/testsite/faketest/urls.py #!/usr/bin/env python # coding=utf-8 from django.conf.urls import url import views urlpatterns = [ url(r'^fake_query/$', views.fake_query), ]
文件: testsite/testsite/faketest/views.py #!/usr/bin/env python # coding=utf-8 import json import requests from django.views.decorators.csrf import csrf_exempt from django.http import HttpRequest, HttpResponse
# 默認開啟了csrf保護機制,本服務僅作自測使用,加上csrf_exempt去除掉csrf保護 @csrf_exempt def fake_query(request): print('get into fake_query') dct = { 'fake': 'test', 'GET': request.GET, 'POST': request.POST, 'body': request.body, } try: dct['json_parsed_body'] = json.loads(request.body) except Exception as e: print('json loads except:{}'.format(e)) return HttpResponse(HttpResponse(json.dumps(dct)), content_type='application/json')
在testsite/testsite/urls.py中,將新模塊faketest引入。
文件: testsite/testsite/urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^faketest/', include('testsite.faketest.urls')), ]
此時的目錄結構如下:
testsite:
db.sqlite3 manage.py r testsite: __init__.py settings.py urls.py wsgi.py faketest: __init__.py urls.py views.py
2,使用HttpRequester進行GET/POST請求
在firefox的擴展商店(https://addons.mozilla.org/zh-CN/firefox/addon/httprequester/)添加該插件后(FireFox57及以上版本不再兼容此插件,因此不能使用最新版firefox,),點擊右上角HttpRequester的圖標,將彈出如下界面:
使用方法一目了然,支持http請求的GET/POST/PUT/DELETE等多種methods。
2.1 GET方法請求Django服務:
GET由於僅通過請求行傳遞參數,即將參數通過?和&符號添加到url后面,所以其實簡單的將請求行復制到瀏覽器地址欄,就可以實現GET請求了,以下為用HTTPRquester進行GET請求的結果:
對應Django服務后台的控制台輸出,注意由於GET請求里面沒有有效的body數據,json試圖對body進行解析時,拋出了一個異常:
2.2 POST方法請求Django服務
POST方法請求要麻煩一些,根據POST body的具體內容要設置好對應的content_type,這里以application/json和application/x-www-form-urlencoded兩種content_type的提交舉例觀察非表單和表單提交的POST請求。
2.2.1非表單內容提交:
對應的Django服務控制台輸出:
可以從右邊的返回結果里面看到,request的body成員就是POST請求時的contetn內容,並且在服務中經過json解析后,又再次返回放入服務返回的json串之中了,同時這次由於body中是可以正常解析的json串,所以服務端並沒有拋異常,而是將json串解析后又返回給了調用方。
可以注意到,服務收到POST請求時,其request.POST對象卻是一個空字典,並沒有任何POST請求里面的content內容,這是為什么呢?
這涉及到Django框架的具體實現,根據Django的官方文檔:
-
HttpRequest.
POST
¶ -
A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data. See the
QueryDict
documentation below. If you need to access raw or non-form data posted in the request, access this through theHttpRequest.body
attribute instead.It’s possible that a request can come in via POST with an empty
POST
dictionary – if, say, a form is requested via the POST HTTP method but does not include form data. Therefore, you shouldn’t useif request.POST
to check for use of the POST method; instead, useif request.method == "POST"
(seeHttpRequest.method
).POST
does not include file-upload information. SeeFILES
.
在Django的實現中,request.POST對象是用於存儲包含表單數據的對象,而在request.body中則包含了content中的原始(raw)非表單數據,接下來我們通過POST傳遞表單數據來進一步驗證這一點。
2.2.2 POST請求提交表單數據
對應的Django服務控制台輸出:
可以看到,在返回結果中body和POST都有了數據,body包含的是未經解析的原始content數據,由於不是一個有效json串,在試圖解析時還拋了異常,而POST則是一個字典,以key-value的形式包含了解析了的body數據。