我尝试使用Tokken身份验证来验证我的用户,问题是我不知道如何使用Tokken添加标头,以便我可以进入我的管理面板。在我实施此方法之前,如果我输入http://127.0.0.1:8000/admin,我可以毫无问题地访问它。
这是我的models.py
class Stock(models.Model):
ticker = models.CharField(max_length=10)
open = models.FloatField()
close = models.FloatField()
volume = models.IntegerField()
def __str__(self):
return self.ticker
# This code is triggered whenever a new user has been created and saved to the database
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
这是我的views.py(我认为这是我必须改变一些事情):
@api_view(['GET', 'POST'])
def stock_list(request, format=None):
if request.method == 'GET':
stocks = Stock.objects.all()
serializer = StockSerializer(stocks, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = StockSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', 'POST', 'DELETE'])
def stock_detail(request, pk, format=None):
try:
stock = Stock.objects.get(pk=pk)
except Stock.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = StockSerializer(stock)
return Response(serializer.data)
elif request.method == 'PUT':
serializer = StockSerializer(stock, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
stock.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
这是我的网址:
urlpatterns = [
url(r'^stocks/$', views.stock_list),
url(r'^stocks/(?P<pk>[0-9]+)$', views.stock_detail),
]
urlpatterns = format_suffix_patterns(urlpatterns)
这是我的网址项目:
urlpatterns = [
url(r'^', include('companies.urls')),
url(r'^api-token-auth/', views.obtain_auth_token),
]
我知道当用户注册时会创建tokken,如果我输入: 卷曲 - 数据&#34;用户名= admin&amp;密码=密码&#34; http://127.0.0.1:8000/api-token-auth/ 我获得了admin的tokken,任何想法如何添加tokken的标题?
答案 0 :(得分:0)
添加标题的确切方法将根据您提出请求的方式而变化 但bewlo行应包含在标题中以验证用户
Authorization:Token <token>
确保您已在'rest_framework.authentication.TokenAuthentication'
休息框架
DEFAULT_AUTHENTICATION_CLASSES
EX。
卷曲请求示例:
curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token <token>'
在python脚本中,您可以执行以下命令:
import requests
headers = {
'content-type': "application/json",
'authorization': "Token <token>",
}
response = requests.request("<request-typle>", <url>, data=<payload-if-any>, headers=headers) # while making nay request you need to mention headers as dictionary and `authorization` key to specify token
如果您正在编写测试,那么您可以将其编写为:
self.client.credentials(HTTP_AUTHORIZATION='Token ' + <token>)
阅读this主题
中的详细信息