django - 来自无“GMAIL_PASSWORD”的 Django/Selenium KeyError
问题描述
ERROR: test_can_get_email_link_to_log_in (functional_tests.test_login.LoginTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File ".../Django/python-tdd-book/functional_tests/test_login.py", line 36, in test_can_get_email_link_to_log_in
body = self.wait_for_email(test_email, SUBJECT)
File ".../Django/python-tdd-book/functional_tests/test_login.py", line 72, in wait_for_email
inbox.pass_(os.environ['GMAIL_PASSWORD'])
File "/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 679, in __getitem__
raise KeyError(key) from None
KeyError: 'GMAIL_PASSWORD'
我正在关注observerthetestinggoat这本书,这本书很棒,但我无法通过这个错误,我在这里发现另一个未解决的问题完全相同,但没有解决,我尝试深入研究gmail访问文档,例如。'允许不安全的应用程序',三重检查我已经加载了环境变量,系统实际上正在工作,即发送带有正确信息的电子邮件并在单击时允许该用户登录,除了测试之外,所有的都在工作,环境变量是加载在外壳中,我正在从 ie 执行测试。echo $GMAIL_PASSWORD,我确实注意到这个状态的 python 版本是系统 python3 但是当我从我的 virtualenv 运行 which python3 它显示 virtualenv 版本时,我什至尝试重新创建我的 virtualenv,任何帮助都会很棒我已经花了一天时间解决这个错误。
from django.core import mail
from selenium.webdriver.common.keys import Keys
import re
import os
import time
import poplib
def wait_for_email(self, test_email, subject):
if not self.staging_server:
email = mail.outbox[0]
self.assertIn(test_email, email.to)
self.assertEqual(email.subject, subject)
return email.body
email_id = None
start = time.time()
inbox = poplib.POP3_SSL('pop.gmail.com')
try:
inbox.user(test_email)
inbox.pass_(os.environ['GMAIL_PASSWORD'])
while time.time() - start < 60:
# get 10 newest messages
count, _ = inbox.stat()
for i in reversed(range(max(1, count - 10), count + 1)):
print('getting msg', i)
_, lines, __ = inbox.retr(i)
lines = [l.decode('utf8') for l in lines]
print(lines)
if f'Subject: {subject}' in lines:
email_id = i
body = '\n'.join(lines)
return body
time.sleep(10)
finally:
if email_id:
inbox.dele(email_id)
inbox.quit()
解决方案
if os.environ['GMAIL_PASSWORD']
is raise aKeyError
表示GMAIL_PASSWORD
当前环境中未设置环境变量。
仔细检查您的 shell 环境变量。该
env
命令列出所有环境变量。检查拼写错误、大写/小写等。不太可能,但你也可以检查你的 python 脚本——有什么东西会从环境中删除东西
del os.environ[...]
吗?
推荐阅读
- react-native-ios - 从 git 克隆时找不到 CFBundleIdentifier
- angularjs - AngularJS数据表总是显示没有找到匹配的记录
- angular - 如何使用 Visual Studio Code 将在 Visual Studio 2015 中开发的 Angular 4 项目使用到 Angular 6?
- java - 如何将远程配置获取时间保持 15 分钟
- docusignapi - 有没有办法在签署文件时创建自定义签名?
- django - 尝试将本地 django 连接到 Amazon RDS MySQL 数据库时出现 2026 SSL 连接错误
- javascript - 我们如何检查一个机器人是否在您的不和谐服务器中与另一个机器人
- python - 我已经设置了所有的头信息,但我仍然无法获取数据
- css - 完整性和跨域属性在链接标记中显示为无效
- html - 大图像仍然会破坏具有最大宽度和高度的引导列