Export django settings to my python file

460 views Asked by At

I am trying to make logparser.py in django project which parses the data coming from different servers.

And on running the command on terminal :

$ python logparser.py

This error is coming :

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

my logparser.py contains:

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

I know I am doing wrong something with command [python manage.py], but i need to run like this. Any solution for this exporting django settings to separate python file??

2

There are 2 answers

0
Rahul Tanwani On BEST ANSWER

Well, This is the exact Usecase why Django provided an ability to create custom commands. You can use all the features of django, in your script, Its like your script will be running inside a Django Container. Here is the Documentation https://docs.djangoproject.com/en/dev/howto/custom-management-commands/.

0
Torsten Engelbrecht On

In case you don't want to use custom management commands though there is also a simple way to run your code within Django's context. Simply put the following at the beginning of your python file, you want to run:

from django.conf import settings

from django.core import management
management.setup_environ(settings)