With Web application developed as a hobby, "Collect articles from news sites every morning at 7 o'clock" I wanted to do something like that
What is Django Command in the first place?
python manage.py runserver
python manage.py migrate
What follows python manage.py
like
The above two are the original commands Actually, you can make this command yourself For details from official
First, create a management
directory under the app 1 directory
Create a commands
directory under the management
directory
You don't have to create __init__.py
Create some script under the commands
directory
This will be the new Django command
In other words
python manage.py something
`
If you enter, the script in "something" will be executed
project
├── App 1
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── management ← I will make a new one
│ │ ├── __init__.py
│ │ └── commands ← I will make a new one
│ │ ├── __init__.py
│ │ └── Something.py ← I'll make a new one
│ ├── migrations
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── App 2
└── manage.py
Now, the situation where App 1/management/commands/something .py
is created
Placement is OK
Next, you need to tell the contents, "This is a Django command."
The minimum required description for that is as follows
sample.py
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
"""Write your favorite script here"""
pass
Edit with crontab -e
#Do something every morning at 7am
#Execution result is log.Record in txt
0 7 * * * /Absolute path/python3 /Absolute path/manage.py something> /Absolute path/log.txt 2>&1
When entering the command you want to execute with crontab, it is better to specify it with an absolute path Especially when using python in a virtual environment
Recommended Posts