Django-04 GET和POST 1,GET處理 2,POST處理

  • 無論是GET還是POST,統一由視圖函數接收請求,通過判斷request.method區分具體的請求動作
  • 樣例:
if reuqest.method == 'GET':
  處理GET請求時的業務邏輯
elif requset.method == 'POST':
  處理POST請求的業務邏輯
else:
  其他請求業務邏輯

1,GET處理

  • GET請求動作嗎,一般用於向服務器獲取數據
  • 能夠產生GET請求的場景
    • 瀏覽器地址欄中輸入URL,回車後
    • <a href="地址?參數=值&參數=值">
    • form表單中的method爲get
  • GET請求方法中,如果有數據需要傳遞給服務器,通常會用查詢字符串(Query String)傳遞【注意:不要傳遞敏感數據】
  • URL格式:xxx?參數1=值1&參數名2=值2...
  • 服務器端接收參數:
def test_get_post(request):
    if request.method == 'GET':
        print(request.GET)
        print(request.GET.get('c','no c'))
        print(request.GET.getlist('a'))
        pass
    elif request.method == 'POST':
        pass
    else:
        pass
    return HttpResponse('test post get')

打印:

<QueryDict: {'a': ['1', '2', '3']}>
no c
['1', '2', '3']

2,POST處理

  • POST請求動作,一般用於向服務器提交大量/隱私數據
  • 使用post方式接收客戶端數據:
POST_FORM = '''
<form method='post' action="/test_get_post">
  用戶名:<input type="text" name="username">
  <input type='submit' value='登錄'>
</form>
'''

def test_get_post(request):
    if request.method == 'GET':
        print(request.GET)
        print(request.GET.get('c','no c'))
        print(request.GET.getlist('a'))
        return HttpResponse(POST_FORM)
    elif request.method == 'POST':
        print('username is ',request.POST['username'])
        return HttpResponse('post is ok')
    else:
        pass
    return HttpResponse('test post get')
取消csrf驗證
  • 取消csrf驗證,否則Django將會拒絕客戶端發來的POST請求,報403響應
  • 禁止掉settings.py中MIDDLEWARE中的CsrfViewsMiddleWare的中間件
MIDDLEWARE=[
  ...
    # 'django.middleware.csrf.CsrfViewMiddleware',
  ...
]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章