【问题标题】:Django app initialization processDjango 应用程序初始化过程
【发布时间】:2015-10-08 23:32:55
【问题描述】:

在我的服务器启动期间,我需要执行一组功能。无论路径是“/”、“/blog/”、“/blog/post”。出于开发目的,我希望每次运行python manage.py runserver 时都运行此脚本,而出于生产目的,我会喜欢此脚本在部署期间运行。有人知道如何做到这一点吗?

我的脚本正在抓取数据并使用 python 及其一些库调用 Facebook 的 Graph API。

【问题讨论】:

标签: python django deployment development-environment


【解决方案1】:

我建议你使用custom management commands:

  1. 创建初始化命令:

    例如app/management/commands/initialize_some_stuff.py

    from django.core.management.base import BaseCommand
    
    
    class Command(BaseCommand):
        help = 'Description of your command.'
    
        def handle(self, *args, **options):
            # Add your initialization here.
            print 'What should I initialize?'
    
  2. 在开发过程中创建运行服务器的命令:

    例如app/management/commands/rundevserver.py

    import os
    
    from django.core.management import call_command
    from django.core.management.base import BaseCommand
    
    
    class Command(BaseCommand):
        help = 'Description of your command.'
    
        def handle(self, *args, **options):
            if not os.environ.get('RUN_MAIN'):
                call_command('initialize_some_stuff', *args, **options)
            call_command('runserver', *args, **options)
    
  3. 在开发过程中调用./manage.py rundevserver 而不是./manage.py runserver

  4. ./manage.py initialize_some_stuff 添加到您的部署脚本中。

作为第 3 条的替代方案,您还可以 override default runserver command 并有条件地从中调用 ./manage.py initialize_some_stuff

  1. 添加额外的导入:

    import os
    
    from django.conf import settings
    
  2. 覆盖handle 方法:

    def handle(self, *args, **options):
        if os.environ.get('RUN_MAIN') and settings.DEBUG:
            call_command('initialize_some_stuff', *args, **options)
        super(Command, self).handle(*args, **options)
    

【讨论】:

    【解决方案2】:

    听起来最快(如果不是最优雅)的解决方案是在脚本末尾调用“python manage.py runserver”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      • 2011-11-17
      • 2011-03-06
      • 2011-01-26
      • 2015-04-29
      • 2013-07-02
      相关资源
      最近更新 更多