1

我正在尝试在 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 文件的任何解决方案?

4

2 回答 2

1

好吧,这就是 Django 提供创建自定义命令的能力的确切用例。您可以在脚本中使用 django 的所有功能,就像您的脚本将在 Django 容器中运行一样。这是文档https://docs.djangoproject.com/en/dev/howto/custom-management-commands/

于 2013-08-26T08:25:19.540 回答
1

如果您不想使用自定义管理命令,尽管还有一种简单的方法可以在 Django 的上下文中运行您的代码。只需将以下内容放在要运行的 python 文件的开头:

from django.conf import settings

from django.core import management
management.setup_environ(settings)
于 2013-08-26T08:39:38.743 回答