Using Django models in external python script

前端 未结 3 917
耶瑟儿~
耶瑟儿~ 2020-12-08 05:31

I was very confused today.

I was trying to use my django app models in my python script.

here is my approach

import os, sys

sys.path.append(         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 06:26

    You need to write a custom management command, instead of doing these weird acrobatics.

    Create a module called management (in other words, create a directory management and inside it create an empty __init__.py file) inside the directory of any app that you have listed in INSTALLED_APPS. So if you have myapp, you would create:

    myapp
     |
     > management
     | | __init__.py
     > models.py
     > views.py
    

    Then in the management directory, create another module commands and in it create a file which is the name of your command; for example my_command.py, like this:

    myapp
     |
     > management
     | | __init__.py
     | | commands
     | | | __init__.py
     | | | my_command.py
     > models.py
     > views.py
    

    In my_command.py, write this boilerplate code:

    from django.core.management.base import BaseCommand, CommandError
    from myapp.models import MyModel
    
    class Command(BaseCommand):
        help = 'Does some magical work'
    
        def handle(self, *args, **options):
            """ Do your work here """
            self.stdout.write('There are {} things!'.format(MyModel.objects.count()))
    

    Once you save the file, you'll be able to do python manage.py my_command and it will have access to all your models and settings.

    If you need to run it as a daemon, Daniel Roseman wrote django-initd which does exactly that. Once you have installed it:

    from django.core.management.base import CommandError
    from daemon_command import DaemonCommand
    from myapp.models import MyModel
    
    class Command(DaemonCommand):
        help = 'Does some magical work'
    
        def loop_callback(self, *args, **options):
            """ Do your work here """
            self.stdout.write('There are {} things!'.format(MyModel.objects.count()))
    

    Once you have that done from the github readme:

    The important parts of such a process are these:
    
        * it comes up automatically on server startup
        * it logs errors and information to a named location, which is configurable
        * if the process dies, it restarts itself straight away 
    
    [...]
    
    Run the command as normal, but pass one of --start, --stop or --restart to 
    work as a daemon. Otherwise, the command will run as a standard application.
    

提交回复
热议问题