Django中API分析
阿新 • • 發佈:2017-08-12
urn view 進行 字典 def ret http 發出 highlight
下面,我將仔細分析一次請求的旅程:
web端發出一個請求報文,到獲得服務器的響應報文結束。
1.打開瀏覽器,輸入URL,進入API頁面:
http://127.0.0.1:8000/api/salt
2.輸入命令,按下確認按鈕
根據URLconf,由上到下進行匹配,最終將請求報文(request對象)交給cmd方法
url(r‘^api/salt‘,web_views.cmd,name=‘cmd‘),
這裏說明一下:request對象有很多屬性,其中用的最多的要數POST屬性,他是類字典對象的一個實例對象
這時cmd方法就是一個API,它接受並處理request對象並且返回response對象到html文件
def cmd(request): if request.POST: command = CommandForm(request.POST) a = print(request.POST) # host_ip = request.POST.get(‘host_ip‘) func = request.POST.get(‘func‘) # args = request.POST.get(‘args‘) # command.host_ip = host_ip # command.func = func # command.args = args # command.save() result = os.popen(func).read() return render(request,‘salt_api.html‘,{‘result‘:result,‘post‘:request.POST,}) else: command = CommandForm() return render(request,‘salt_api.html‘,{‘form‘:command})
response對象被送給了html文件
下面就是在html中如何展示response對象
<h3>執行結果:</h3><pre style="background-color: cornsilk; font-family: ‘微軟雅黑‘;">{{result|safe}}</pre> <h3>post對象:</h3> <pre>{{post}}</pre>
3.返回響應報文到客戶端瀏覽器
下面使我們看到的瀏覽器結果
好了!以上就是一次請求開始,到獲得結果的詳細過程!
Django中API分析