Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

python - How to use Django shell to interact with running server?

In the apps.py of one of my apps I set some class variables for models that can't be set at initialization because they depend on other apps and the models in them. This works fine and the class variables are set, but what I want to do is then test these classes to see if they'll work as intended. My problem is the class variables are set when I run the development server, but I want to also be able to create new instances of these models for testing. I realize that this can be accomplished by building the front-end that will interact with the models in production, but this seems to be excessive for simple testing.

Is there a way to use Django's shell on a currently running server, or do I have to go through importing and running all the things that manage.py usually takes care of on its own?

In case what I have written isn't clear, here's an example of the files in question:

# example.models.py

from django.db.models import *

class ExampleModel(Model):
    class_var = None
    
    .
    .
    .

# apps.py

from django.apps import AppConfig


class ExampleConfig(AppConfig):
    name = 'example'

    def ready(self):
        from example.models import ExampleModel
        ExampleModel.class_var = 'something'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you run python manage.py shell alot of the same set up happens as what happens when you run runserver. In particular, all of the ready methods in your AppConfigs will be called.

For this reason there is no need for your server to be running to do the testing you want.

You can even test this. Simply add a print("This happens") and run python manage.py shell. You should see something like this:

(env)your-current-location % python manage.py shell
This happens       <---- Here you see it is printed 
Python 3.8.6 (default, Oct  8 2020, 14:06:32)
[Clang 12.0.0 (clang-1200.0.32.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>

For what it's worth, you can open a shell, and run your server at the same time yes. But these will be different processes, and variables set on classes, will refer to differnt things. They will be (at the code level) completely separate.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...