django視圖獲取用戶請求信息以及請求頭


 request可以直接在前端用,不需要在render里再定義。

 

 

request.body  //前端頁面數據內容的原生值。如果前端不是從POST,GET,FILES里面獲取的數據,就從body里獲取

  request.POST  //從request.body里拿數據再封裝到request.POST里面

  request.FILES  //從request.body里拿數據再封裝到request.FILES里面

  request.GET  //從request.body里拿數據再封裝到request.GET里面

  request.XXX.getlist  //獲取列表

        request.post.getlist  //獲取列表

 

request.Meta  (request headers)  //獲取請求頭相關的信息。

  request.method  //請求方法

  request.path_info  //獲取URL

  request.COOKIES  //獲取cookies

 

cookie信息或在rep里添加的鍵值對將會寫到response headers里面

a= 'python'

rep = HttpResponse(...) 或 rep = render(request, ...)或rep =redirect('/index/')

 

a= 'python'

rep = HttpResponse(a)

rep['name'] = 'zhou'

rep.set_cookie()

return rep

 

HttpResponse可以返回字節和字符串

 

def index(request):
    from django.core.handlers.wsgi import WSGIRequest
    print(type(request))

    print(request.environ)
    for k,v in request.environ.items():  //查看所有用戶請求信息 
print(k,v) print(request.environ['HTTP_USER_AGENT'])  //查看請求終端類型
return HttpResponse('OK')

 

用HttpResponse發送圖片

urls

    url(r'^image.html', views.get_image),

 

視圖函數

def get_image(request):
    with open('static/imgs/16.jpg','rb') as fp:
        data = fp.read()
    return HttpResponse(data)

 

前端html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<img src="/image.html">

</body>
</html>

 

CBV

實例:

視圖函數

from django.views import View
class Home(View):

    def dispatch(self, request, *args, **kwargs):
        print('before')
        result = super(Home,self).dispatch(request,*args,**kwargs)
        print('after')
        return result

    def get(self,request):  # GET方式提交
        print('get')

        return render(request,'home.html')

    def post(self,request):  # POST方式提交
        print('post')

        return render(request,'home.html')

 

urls

urlpatterns = [

    url(r'^home/', views.Home.as_view()),

]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM