在运行服务器django之后立即运行python脚本

时间:2019-07-14 20:22:34

标签: django python-3.x

我有一个带不确定循环的python脚本,它一直在检查数据,现在我很困惑如何执行它,以便如果服务器正在运行,它就可以继续运行。 我认为该脚本应在我在Django中运行服务器后立即运行,但是如何运行此脚本? 有什么建议么?

2 个答案:

答案 0 :(得分:0)

django-admin runserver仅用于开发。假设这是一个开发环境,可能最简单的方法是仅在单独的控制台中运行脚本,或者制作一个简单的Shell脚本来启动django服务器,并在后台进行处理,然后运行您的脚本。

#!/bin/sh
django-admin runserver &
/path/to/my/script.py &

您需要在重新运行该脚本之前手动终止这些进程。

在生产环境中,使用WSGI运行Django,并使用supervisord之类的命令运行其他脚本。您可以配置OS初始化系统(可能是systemd),以确保这两个任务都在重新启动时启动并保持运行状态。

答案 1 :(得分:0)

第一个重要部分是将无限循环打包到一个函数中,并使用huey / celery / etc使其成为异步运行的``任务'',然后调用此任务在您的views.py/models中运行。 py / manage.py。

如何让任务同步运行:

HUEY:[https://huey.readthedocs.io/en/latest/]

启动服务器时如何运行任务(两种方式):

  1. 编辑您的manage.py,在导入manage.py的后一行添加函数调用。
#!/usr/bin/env python
import os
import sys

print('Interesting things happens.') # THIS IS WHERE YOU RUN YOUR tasks.checkdata.

if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'OTAKU.settings')

    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


  1. 但是,也许您想离开manage.py。在项目中创建一个带有views.py和models.py的新应用。(请记住,将此应用添加到settings.py中的INSTALLED_APPS中)

在views.py中:

print("The view is loading.")# THIS IS WHERE YOU CAN RUN YOUR tasks.checkdata.

在models.py中:

print("The models is loading.")# THIS IS WHERE YOU CAN RUN YOUR tasks.checkdata.

现在运行服务器时,可能会看到以下内容:

Interesting things happens.
The models is loading.
Interesting things happens.
The models is loading.
Performing system checks...

The view is preparing itself.
System check identified no issues (0 silenced).
July 15, 2019 - 11:52:03
Django version 2.1.3, using settings 'rayos.settings'
Starting development server at http://0.0.0.0:9988/
Quit the server with CONTROL-C.

用数据检查功能替换脚本的打印部分,它将起作用。