我正在尝试在django项目中创建logparser.py,它解析来自不同服务器的数据。
在终端上运行命令:
$ python logparser.py
此错误即将发生:
Traceback (most recent call last):
File "logparser.py", line 13, in <module>
SMTP_CONF = settings.SMTP_CONF
File "/home/arya/.virtualenv/Devel/.virtualenvs/hu/local/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/home/arya/.virtualenv/Devel/.virtualenvs/hu/local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in _setup
self._wrapped = Settings(settings_module)
File "/home/arya/.virtualenv/Devel/.virtualenvs/hu/local/lib/python2.7/site-packages/django/conf/__init__.py", line 134, in __init__
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'hma.settings' (Is it on sys.path?): No module named hma.settings
我的logparser.py包含:
import re
import os
import fnmatch
import gzip
import bz2
from collections import defaultdict
from django.core.mail import send_mail
from django.core.mail.backends import smtp
import smtplib
from email.mime.text import MIMEText
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hma.settings")
from django.conf import settings
SMTP_CONF = settings.SMTP_CONF
def send_email(self,fromaddress,toaddresses,content,subject):
smtp_server = SMTP_CONF["SERVER"]
smtp_username = SMTP_CONF["USERNAME"]
smtp_password = SMTP_CONF["PASSWORD"]
smtp_port = SMTP_CONF["PORT"]
msg = MIMEText(content, 'html', _charset='utf-8')
msg['Subject'] ='Alert message for bad and internal server error'
msg['From'] = fromaddress
msg['To'] = toaddresses
server = smtplib.SMTP(smtp_server,smtp_port)
server.starttls()
server.login(smtp_username,smtp_password)
server.send_mail(fromaddress,toaddresses,msg.as_string())
server.quit()
return True
我知道我在使用命令[python manage.py]做错了,但我需要像这样运行。这个导出django设置的任何解决方案都可以分离python文件??
答案 0 :(得分:1)
嗯,这就是为什么Django提供了创建自定义命令的能力的确切用法。您可以在脚本中使用django的所有功能,就像您的脚本将在Django Container中运行一样。这是文档https://docs.djangoproject.com/en/dev/howto/custom-management-commands/。
答案 1 :(得分:1)
如果您不想使用自定义管理命令,虽然还有一种在Django上下文中运行代码的简单方法。只需将以下内容放在python文件的开头,就要运行:
from django.conf import settings
from django.core import management
management.setup_environ(settings)