简体   繁体   English

在 django/python 上访问请求头

[英]accessing request headers on django/python

I need to create a secure restFUL api using sencha and django.我需要使用 sencha 和 django 创建一个安全的 restFUL api。 I am fairly new to python.我对python相当陌生。 So far i am able to send request from sencha to server using basic authentication as below到目前为止,我能够使用基本身份验证将请求从 sencha 发送到服务器,如下所示

 new Ext.data.Store({
   proxy: {
     type: "ajax",
      headers: {
       "Authorization": "Basic asdjksdfsksf="
    }
   }
 })  

In php/apache i can access those header with ease with the code below在 php/apache 中,我可以使用下面的代码轻松访问这些标头

$headers = apache_request_headers();
print_r($headers);

How to do this in python?如何在python中做到这一点?

You can access them within a view using request.META , which is a dictionary.您可以使用request.META (一个字典)在视图中访问它们。

If you wanted the Authorization header, you could do request.META['HTTP_AUTHORIZATION']如果你想要授权头,你可以做request.META['HTTP_AUTHORIZATION']

If you're creating a restful API from scratch, you might want to take a look at using tastypie .如果您要从头开始创建一个宁静的 API,您可能想看看使用tyspypie

You can use您可以使用

request.META['HTTP_AUTHORIZATION']

and sometimes有时

request.META['Authorization']

can help.可以帮忙。

As of django 2.2 HttpRequest.headers were added to allow simple access to a request's headers.从 django 2.2 HttpRequest.headers添加到允许简单访问请求的标头。 So now you can also get authentication header using get() function on request.headers所以现在您还可以使用request.headers上的get()函数获取身份验证标头

request.headers.get('Authorization')

This will give you value token value back.这将为您提供价值代币价值。

Bearer eyJ0eYourToken...

https://docs.djangoproject.com/en/2.2/ref/request-response/#django.http.HttpRequest.headers https://docs.djangoproject.com/en/2.2/ref/request-response/#django.http.HttpRequest.headers

HttpRequest.headers HttpRequest.headers

New in Django 2.2. Django 2.2 中的新功能。

 if 'Authorization' in request.headers: # Authorization header exists
      #do something here
      pass
 
 else: # Authorization header not exists
     #do something here
     pass 

Read also Django official Doc另请阅读Django 官方文档

For older versions of django prior to 2.2, you'll need to access the headers in the following way using the META key.对于 2.2 之前的旧版本 django,您需要使用 META 键以下列方式访问标头。 Always important to first check if the key authorization header keys exists just in case it wasn't posted otherwise you'll run into non-existent key errors.首先检查密钥授权头密钥是否存在总是很重要的,以防万一它没有发布,否则你会遇到不存在的密钥错误。

if not ('HTTP_AUTHORIZATION' in request.META.keys()):

    return HttpResponse('NO AUTH HEADER PROVIDED')

elif (request.META['HTTP_AUTHORIZATION'] == 'Bearer YourAuthorizationKey123':

    # Validation passed - Proceed with whatever else you want to do

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM