django调用py报错 django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured.
完整报错信息如下
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
经查询由于user_enterpoint.py文件和manage.py文件在同级目录下,因此在main方法里面要加入如下代码,并且在开头import那里不能导入models模块
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "crazyeyes.settings") import django django.setup()
import getpass,os
#from audit import models #models模块不能再此处import
from django.contrib.auth import authenticate
完整代码如下所示
import getpass,os
from django.contrib.auth import authenticate
class UserPortal(object):
"""用户命令行端交互入口"""
def __init__(self):
pass
def user_auth(self):
"""完成用户交互"""
retry_count=0
while retry_count<3:
username=input("Username").strip()
if len(username) == 0: continue
password=getpass.getpass("Password:").strip()
print("Password can not be null")
user=authenticate(username=username,password=password)
if user:
self.user=user
print("welcome login... ")
retry_count+=1
else:
exit("Too many attempts.")
def interactive(self):
"""交互函数"""
self.user_auth()
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "crazyeyes.settings")
import django
django.setup()
from audit import models
portal=UserPortal()
portal.interactive()
再次执行user_enterpoint.py, 不在报错