django - 如何在 django shell 中以现有用户身份登录
问题描述
在 django shell 中,我想调试一个特定的 api 调用,并且要使资源正常工作,应该登录。
from django.test import Client
from urllib.parse import urlsplit, parse_qsl
client = Client()
client.login(username='my_username', password='my_password')
# I also tried client.force_login() without success
url_data = urlsplit(url)
r = client.get(path=url_data.path, data=parse_qsl(url_data.query))
# r is <HttpUnauthorized status_code=401, "text/html; charset=utf-8">
编辑:我说的是具有真实凭据的真实环境(预生产)
如何正确登录?
解决方案
尝试
from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
if user is not None:
# A backend authenticated the credentials
else:
# No backend authenticated the credentials
https://docs.djangoproject.com/en/3.1/topics/auth/default/#authenticating-users
推荐阅读
- java - 如何在没有 Activity 的情况下为 App Widget 注册 BroadcastReceiver?
- python - 在 PyQt5 中隐藏小部件后如何设置更小的窗口大小?
- php - 在php中的未序列化数组中搜索给定值
- python - SQLalchemy:使用 Union 优化和链接子查询
- python - 在 Python 中使用 redis 实现推/拉(或队列)
- r - 如何将数据框中的一行复制到另一个df并一次将其转换为一列?
- nginx - Http 响应 401 访问 nginx 反向代理后面的服务
- arm - armclang/armcc 是否提供复制省略选项?
- php - php多数组编辑
- windows - Kafka Brokers - Windows 中的日志保留问题 - 是否有任何临时解决方法?