Reputation: 21
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
When I run the testapscheduler.py file, I get the above error. Is it because I only run one file in the Dajngo frame that I get the above error? How can I test it?
testapscheduler.py:
import logging
from models import Todo
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta
import pytz
import requests
def notify_todo():
# 現在の日時を取得
now = datetime.now(pytz.timezone('Asia/Tokyo'))
# 締め切りが30分以内のTODOリストを取得
todos = Todo.objects.filter(
deadline__gt=now - timedelta(minutes=30),
deadline__lt=now + timedelta(minutes=30),
ttime__isnull=False,
ttime__gt=now.time()
)
# 30分以内のTODOリストの数を出力
# ログの出力名を設定
logger = logging.getLogger('mylog')
#ログレベルを設定
logger.setLevel(logging.DEBUG)
#ログをコンソール出力するための設定
sh = logging.StreamHandler()
logger.addHandler(sh)
logger.debug(f'{len(todos)}個のTODOリストが締め切り30分以内にあります。')
for todo in todos:
#LINE NotifyのAPIトークンを取得
api_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# 通知メッセージの作成
message = f"【{todo.title}】\n締切時間:{todo.deadline.strftime('%Y/%m/%d %H:%M')}\n詳細:{todo.description}"
# LINE Notifyに通知を送信
headers = {'Authorization': f'Bearer {api_token}'}
payload = {'message': message}
requests.post('https://notify-api.line.me/api/notify', headers=headers, data=payload)
def start():
scheduler =BackgroundScheduler(timezone='Asia/Tokyo')
scheduler.add_job(notify_todo, 'interval', seconds=2) # 2秒ごとに実行
scheduler.start()
models.py
from django.db import models
class Todo(models.Model):
title = models.CharField("タスク名", max_length=30)
description = models.TextField("詳細", blank=True)
deadline = models.DateField("締切")
ttime = models.TimeField("")
def __str__(self):
return self.title
Upvotes: 0
Views: 653
Reputation: 3717
I recommend to use the standard way to execute a command from command line but within the django context: django management commands.
See the answer to this question this is the code for my manage.py script i would like someone to explain each line please i barely understand it
in your case code in start() needs to go into handle() function of the management command.
file: app_name/management/command/start.py
--------------
class Command(BaseCommand):
def add_arguments(self, parser):
return
def handle(self, *args, **kwargs):
scheduler =BackgroundScheduler(timezone='Asia/Tokyo')
scheduler.add_job(notify_todo, 'interval', seconds=2) # 2秒ごとに実行
scheduler.start()
def notify_todo():
.....
then just call the command by
> python manage.py start
Upvotes: 0