[Django]-Easiest way to write a Python program with access to Django database functionality

13👍

from django.core.management import setup_environ
from django.core.mail import EmailMultiAlternatives, send_mail
from django.contrib.auth.models import User

import settings
from my.app.models import *

setup_environ(settings)

This was how I did it for a cron that emailed parties daily updates. The .py lived in the root of my django app, so the import settings would reflect that accordingly.

9👍

An alternative to all the approaches given here is to write your cron job as a custom ./manage.py command. This is very easy to do, and gives you the ability to do ./manage.py yourcommand either on the command line or in your crontab.

The documentation on this is very sparse, but it does tell you to look at the code for the existing commands, which you can use as a template for your own.

2👍

Edit: For Django 1.7

import os
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")
django.setup()
#have fun

Credit


Selected answer is deprecated since Django 1.4

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")
#from your_app_name import models
##have fun

Source: https://stackoverflow.com/a/18760222

👤Mike S

0👍

You want something like this in your crontab:

PYTHONPATH=/path/to/your/project DJANGO_SETTINGS_MODULE=settings myscript.py

And then your python script should start with this:

#!/usr/bin/env python

from django.conf import settings

From there, you should be able to import your models / views / forms / whatever else, and have an environment pretty much just like a ./manage.py shell

Note: Depending on how you do your imports inside your project, this may not work exactly as shown. If you are always doing something like “from myproject.myapp.models import *”, then you will want to set cron line to look more like this:

PYTHONPATH=/path/to/1_level_before_your_project DJANGO_SETTINGS_MODULE=myproject.settings myscript.py

0👍

I’d like to have a Python program
which is run using a cronjob instead
of manually visiting the correct URL
to update the information.

A simplistic alternative: write a cronjob to automatically “visit the correct URL to update the information” — could be as simple as a curl or wget, after all. This doesn’t answer the question in the title, but given the way you explain your real underlying problem it just might be the simplest and most immediate approach to solve it.

Leave a comment