| 1 | """ |
| 2 | Django embedded IPython shell |
| 3 | |
| 4 | When using the development server Django's embedded IPython shell allows you to |
| 5 | drop into a Python shell at any point during a request to inspect the local |
| 6 | namespace. |
| 7 | |
| 8 | Requires IPython. |
| 9 | |
| 10 | usage: |
| 11 | |
| 12 | from django.utils.shell import ipshell |
| 13 | |
| 14 | def some_view(request): |
| 15 | response = render_to_response(...) |
| 16 | ipshell() # suspend request here and drop into IPython shell |
| 17 | return response |
| 18 | |
| 19 | If a call to ipshell() is left in production code a warning will be sent to |
| 20 | stdout and processing will continue normally. |
| 21 | |
| 22 | """ |
| 23 | |
| 24 | BANNER = """ |
| 25 | # Interrupting this request to bring you the Django Shell! |
| 26 | |
| 27 | Django %s |
| 28 | Python %s |
| 29 | IPython %s |
| 30 | |
| 31 | ? -> Introduction to IPython's features. |
| 32 | %%magic -> Information about IPython's 'magic' functions. |
| 33 | help -> Python's own help system. |
| 34 | object? -> Details about 'object'. ?object also works, ?? prints more. |
| 35 | |
| 36 | Type Ctrl-D or 'quit' to continue serving the request.""" |
| 37 | |
| 38 | def make_fake_shell(message): |
| 39 | def ipshell(): |
| 40 | print "\n# %s\n" % message |
| 41 | return ipshell |
| 42 | |
| 43 | try: |
| 44 | from IPython.Shell import IPShellEmbed |
| 45 | except ImportError: |
| 46 | ipshell = make_fake_shell("Django Shell error: Could not import IPython") |
| 47 | else: |
| 48 | import django |
| 49 | import sys |
| 50 | import IPython |
| 51 | |
| 52 | def version_to_string(version_info): |
| 53 | return '%s.%s.%s %s' % version_info[:4] |
| 54 | |
| 55 | # Django development server sets a __builtin__ flag so we can check it is running |
| 56 | try: |
| 57 | __DJANGO_DEVELOPMENT_SERVER__ |
| 58 | except NameError: |
| 59 | ipshell = make_fake_shell("Django Shell warning: ipshell() called from non-development server, ignored") |
| 60 | else: |
| 61 | ipshell = IPShellEmbed([], banner=BANNER % ( |
| 62 | version_to_string(django.VERSION), |
| 63 | version_to_string(sys.version_info), |
| 64 | IPython.__version__)) |