开发者

Test out small snippets of Django code

开发者 https://www.devze.com 2023-01-27 12:42 出处:网络
I am still in the development phase of a Django App. Before even writing my views.py, I test them out to see if my models are correctly defined. This I do it in the terminal by invoking

I am still in the development phase of a Django App. Before even writing my views.py, I test them out to see if my models are correctly defined. This I do it in the terminal by invoking

python manage.py shell

But oh so often I make some syntax开发者_如何学JAVA error prompting me to abort the shell ctrl-D & retype everything. This process is taking forever. It would be better if I could write all this in some file just for my trials & if all's well copy it to views.py.

What's the process for this? Is it as simple as creating a trial.py in my app directory. Won't I have to import the Django env? What's the best way to do this?


How about writing unit tests? You can execute them easily with one command. You can probably get started by reading the django manual chapter on testing


By all means create a trial.py for simple experimentation, then after doing

python manage.py shell

you can do

>>> import trial

and then invoke the code in trial, directly from the prompt, e.g.

trial.myfunc()

If you need to change things you can just save your changed trial.py and do

reload(trial)

Of course, you may need to recreate any existing objects in the interactive session in order to make use of your changes.

This should be seen as complementary to writing unit tests (as per Jani's answer), but I do find this approach useful for trying things out using iterative refinement.


Create your file-for-tests in the Django project directory and add path to your project to env variable:

import sys
sys.path.append(os.path.realpath(os.path.dirname(__file__)))

After that you'll be able to import any module from the project (e.g. models from models.py or just functions from views.py) and use your favorite IDE with it's editor and shell.


For simpler cases you can use django-extensions add-on that contains shell_plus management command that is similar to the standard shell command but preloads all models.


You need to set the module used for settings.


I also had this problem before,

may be you could install ipython,which has a magic function called like this:

%save.

This will save what you input into a file .

and ipython is a very charming tool ,which can take the palce of standard python prompt perfectly.. It also have other wonderful things !

And in django , if you have install ipython, when you input python manage.py shell,

it will invoke ipython directly.

0

精彩评论

暂无评论...
验证码 换一张
取 消