runscript.rst 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. RunScript
  2. =============
  3. :synopsis: Runs a script in the django context.
  4. Introduction
  5. ------------
  6. The runscript command lets you run an arbritrary set of python commands within
  7. the django context. It offers the same usability and functionality as running a
  8. set of commands in shell accessed by::
  9. $ python manage.py shell
  10. Getting Started
  11. ---------------
  12. To get started create a scripts directory in your project root, next to
  13. manage.py::
  14. $ mkdir scripts
  15. $ touch scripts/__init__.py
  16. Note: The *__init__.py* file is necessary so that the folder is picked up as a
  17. python package.
  18. Next, create a python file with the name of the script you want to run within
  19. the scripts directory::
  20. $ touch scripts/delete_all_polls.py
  21. This file must implement a *run()* function. This is what gets called when you
  22. run the script. You can import any models or other parts of your django project
  23. to use in these scripts.
  24. For example::
  25. # scripts/delete_all_polls.py
  26. from Polls.models import Poll
  27. def run():
  28. # Get all polls
  29. all_polls = Poll.objects.all()
  30. # Delete polls
  31. all_polls.delete()
  32. Note: You can put a script inside a *scripts* folder in any of your apps too.
  33. Usage
  34. -----
  35. To run any script you use the command *runscript* with the name of the script
  36. that you want to run.
  37. For example::
  38. $ python manage.py runscript delete_all_polls
  39. Note: The command first checks for scripts in your apps i.e. *app_name/scripts*
  40. folder and runs them before checking for and running scripts in the
  41. *project_root/scripts* folder. You can have multiple scripts with the same name
  42. and they will all be run sequentially.
  43. Passing arguments
  44. -----------------
  45. You can pass arguments from the command line to your script by passing a comma-separated
  46. list of values with ``--script-args``. For example::
  47. $ python manage.py runscript delete_all_polls --script-args=staleonly
  48. The list of argument values gets passed as arguments to your *run()* function. For
  49. example::
  50. # scripts/delete_all_polls.py
  51. from Polls.models import Poll
  52. def run(*args):
  53. # Get all polls
  54. all_polls = Poll.object.all()
  55. if 'staleonly' in args:
  56. all_polls = all_polls.filter(active=False)
  57. # Delete polls
  58. all_polls.delete()