This comprehensive guide to Python mocking will help you keep your unit tests straightforward and explain how to best use the mock.unittest library to your advantage. Learn how Wing can speed up developing and debugging Python code written for the Django web development framework.
Using Wing with Django
Index of All Documentation » How-Tos » How-Tos for Web Development »
Wing is a Python IDE that can be used to develop, test, anddebug Python code written for the Django webdevelopment framework. The debugger works with Django's auto-reload feature and can stepthrough and debug Python code and Django templates. Wing Pro also automates some aspectsof the creation and management of Django projects and applications.
Two versions of Wing are appropriate for use with this document: Wing Pro is thefull-featured Python IDE for professional developers, and Wing Personal is a freealternative with reduced feature set.
If you do not already have Wing installed, download it now.
This document describes how to configure Wing for Django. To get started using Wing asyour Python IDE, please refer to the tutorial in Wing's Help menu or read theQuickstart Guide.
Automated Configuration
The fastest way to get started working with a local installion of Django is to use WingPro's Django extensions. Skip ahead to the ManualConfiguration section below if youhave Wing Personal or if you need to work with Django running on a remote host.
Existing Django Project
To set up a Wing Pro project for an existing Django project, create a new project fromthe Project menu using project type Django. You will be prompted to select thePython executable to use with Django and the directory for your existing Djangoproject, where your manage.py is located.
If you are using Django with a named virtualenv or Anaconda environment, set PythonExecutable to ActivatedEnv and enter the command that activates the environment(for example activatedjango2 or condaactivatedjango3). The drop down menu tothe right of this field lists recently used and automatically found environments. If youare not using a named environment, select CommandLine instead and enter the full pathto python.exe or python. This value can be found by running Python outside of Wingand executing the following:
Once the project is created, this will display a dialog that confirms the configuration,with a detailed list of the settings that were made.
Now you should be able to start Django in Wing's debugger, set breakpoints in Python codeand Django templates, and reach those breakpoints in response to a browser page load.
In some cases, the project creation process may prompt you to take additional stepsmanually:
- If django-admin.py could not be found from the specified PythonExecutablethen you will be prompted to change this value in ProjectProperties, fromthe Project menu. Wing looks for django-admin.py in the same directory asthe selected Python's python.exe or python.
- If settings is a package in your project (instead of a settings.py file), youwill need to manually enable template debugging in Django. This is done by settingdebug to True under OPTIONS in the TEMPLATES section of yoursettings.py or settings package. If you are using Django 1.8 or earlier,instead set TEMPLATE_DEBUG to True.
New Django Project
If you are starting a new Django project at the same time as you are setting up your Wingproject:
- Select StartDjangoProject from the Extensions sub-menu of the Project menu,fill in the requested values, and press OK.
- Wing will display a confirmation dialog, with a detailed list of actions taken. This mayinclude a command that needs to be run manually to set up the superuser account for yournew Django project. If so, copy and paste to run it in a command shell.
- Finally, press CreateWingProject to create and configure a new Wing project forthe new Django project. This confirms the project configuration, as described abovefor existing Django projects.
Automated Django Tasks
The Django menu, shown in Wing when the current project is configured for Django,contains items for common tasks such as creating a new app, generating SQL for a selectedapp, migrating an app or database, running validation checks or unit tests, and restartingthe integrated PythonShell with the Django environment.
Wing's Django extensions are open source and can be found in scripts/django.py in theinstall directory listed in Wing's About box. For detailedinformation on writing extensions for Wing, see Scripting and Extending Wing.
Remote Development
Wing Pro can work with Django running on a remote host. See Remote Python Development for instructions on setting up remote access. Then usethe following manual configuration instructions. You'll be able to use either of thedescribed methods for debugging.
Manual Configuration
This section describes manual configuration of Wing projects for use with Django. Manualconfiguration is necessary when Django is running on a remote host or when using WingPersonal. If you are using Wing Pro with a local installation of Django, see AutomatedConfiguration above instead.
Configuring the Project
To get started, create a new project from the Project menu using the GenericPython project type for a local installation and ConnecttoRemoteHostviaSSH M kumaran son of magalakshmi torrent. fora remote installation of Django. If you are using a named virtualenv or Anacondaenvironment, set the PythonExecutable to ActivatedEnv and enter the command thatactivates the environment (for example activatedjango-test or condaactivateenv2). The drop down menu to the right of this field lists recently used andautomatically found environments. If you are not using a named environment, selectCommandLine instead and enter the full path of the Python used for Django. This pathcan be found by running Python outside of Wing and typing the following:
Then add your project files with AddExistingDirectory in the Project menu.
You may also need to set the DJANGO_SITENAME and DJANGO_SETTINGS_MODULEenvironment variables and add the project directory and its parent directory to thePythonPath under Environment tab in ProjectProperties, from the Projectmenu.
In Django 1.7 and later, set PYTHONSTARTUP_CODE in the Environment in ProjectProperties to importdjango;django.setup() so Django will be initialized in Wing'sintegrated PythonShell.
For unit testing in Wing Pro, set the DefaultTestFramework under the Testingtab of ProjectProperties to DjangoTests and then add manage.py as a testfile with AddSingleFile in the Testing menu. Cymatics jawz for serum.
Configuring the Debugger
There are two ways to debug Django code: Either (1) configure Django so it can be launchedby Wing's debugger, or (2) cause Django to attach to Wing from the outside as code thatyou wish to debug is executed.
Launching from Wing
To start Django from Wing, right-click on manage.py in the Project tool and selectSetasMainEntryPoint. This causes execution and debugging to start here.
Next, configure the command line arguments sent to manage.py by opening the file inthe editor or finding it in the Project tool and right-clicking to select FileProperties. Then set the run arguments under the Debug/Execute tab to your desiredlaunch arguments. For example:
Other command line arguments can be added here as necessary for your application.
If you are using Wing Pro, enable DebugChildProcesses under the Debug/Executetab of ProjectProperties. This allows Django to load changes you make to code withoutrestarting.
Child process debugging is not available in Wing Personal, so you instead need to add--noreload to the run arguments for manage.py:
In this case, you will need to restart Django each time you make a change, or use thedebugging method described below.
Launching Outside of Wing
Another method of debugging Django is to use wingdbstub.py to initiate debugging afterDjango is started from outside of Wing. This method can be used to debug a Django instanceremotely or to enable debugging reloaded Django processes with Wing Personal.
This is done by placing a copy of wingdbstub.py into the top of the Django directory,where manage.py is located. This file can be found in the install directory listed inWing's About box. Make sure that WINGHOME in your copyof wingdbstub.py is set to the full path of the install directory. On OS X, use thefull path of Wing's .app folder (without the Contents/Resources part).
If you are developing on a remote host, instead use the copy of wingdbstub.py that islocated in the remote agent's installation directory, on the remote host. This ispreconfigured to work correctly with your remote project, as described in Remote WebDevelopment.
Next, place the following code into files you wish to debug:
Then make sure that the Debugger > Listening > Accept Debug Connections preference is enabled inWing and start Django. The Django process should connect to Wing and stop at anybreakpoints reached after wingdbstub has been imported.
When code is changed, just save it and Django will restart. The debugger should reconnectto Wing once you request a page load in your browser that executes one of your importwingdbstub statements.
Debugging Django Templates
To enable debugging of Django templates, you need to:
- Enable template debug in Django. This is done by setting debug to True underOPTIONS in the TEMPLATES section of your settings.py or settingspackage. If you are using Django 1.8 or earlier, instead set TEMPLATE_DEBUG toTrue.
- Turn on Enable Django Template Debugging underthe Options tab of ProjectProperties, from the Project menu. When youchange this property, you will need to restart your Django debug process, if one isalready running.
Usage Tips
Python Static Method Call
Debugging Exceptions
Django contains a catch-all handler that displays exception information to the browser.When debugging with Wing, it is useful to also propagate these exceptions to the IDE. Thiscan be done with a monkey patch as follows (for example, in local_settings.py on yourdevelopment system):
The monkey patch only activates if Wing's debugger is active and assumes that theDebugger > Exceptions > Report Exceptions preference is left setto its default value WhenPrinted.
Template Debugging
If you enabled Django template debugging as described above, you should be able to setbreakpoints in any file that contains {%%} or {{}} tags, and the debugger willstop at them.
Python Monkey Patch Function
Note that stepping is tag by tag and not line by line, but breakpoints are limited tobeing set for a particular line and thus match all tags on that line.
When template debugging is enabled, you won't be able to step into Django internalsduring a template invocaton. To work around that, temporarily uncheck EnableDjangoTemplateDebugging under the Extension tab of Project Properties in Wing, andthen restart your debug process.
Better Auto-Completion
Wing provides auto-completion on Python code and Django templates. The completioninformation is based on static analysis of the files and runtime introspection if thedebugger is active and paused. It is often more informative to work with the debuggerpaused or at a breakpoint, particularly in Django templates where static analysis is notas effective as it is in Python code.
Running Unit Tests
Wing Pro includes a unit testing integration capable of running and debugging Django unittests. For Django projects, the DefaultTestingFramework under the Testing tab ofProjectProperties is set to DjangoTests so that the Testing tool runsmanage.pytest and displays the results. Individual tests can be run or debugged byselecting them and pressing RunTests or DebugTests in the Testing tool.
If unit tests need to be run with different settings, the environment variableWING_TEST_DJANGO_SETTINGS_MODULE can be set to replace DJANGO_SETTINGS_MODULE whenunit tests are run.
Django with Buildout
When using Django with buildout, Wing won't auto-detect your project as a Django projectbecause the manage.py file is instead named bin/django. To get it working, copybin/django to manage.py in the same directory as settings.py or thesettings package.
Related Documents
For more information see:
- Django home page provides downloads anddocumentation.
- Quickstart Guide contains additional basic informationabout getting started with Wing.
- Tutorial provides a gentler introduction to Wing's features.
- Wing Reference Manual documents Wing in detail.
- Remote Web Development describes how to set updevelopment to a remote host, VM, or container.
Monkey patching is a technique to modify module functions or class methods in Python and other dynamic languages run-time. It differs from the traditional source code patching that it does not need separate utility or compilation process to become effective. This means that you can deploy patches to codebase not under your control with your application without extra effort. Monkey patching has been made famous by Plone/Zope community where there is even collective.monkeypatcher add-on for managed monkey patching.
Because monkey patches do not need a compilation stage, the patch will work with the future versions of the application, assuming the patched function or method is not changed. So you can “safely” update the patched software and the patch will apply to the new version without need to go to command-line to perform some cumbersome commands. However, it is the best practice of open source community to report the bugs and submit the fixing patches, as source code patch, in the corresponding issue trackers.
In Django context, you can use monkey patching to
- Fix bugs or modify features of Django core without touching the source code
- Fix bugs or modify features of Django plug-ins (TinyMCE, filebrowser, Django CMS) without touching the source code
Patches are usually applied when Python does module imports. You have a special module called “monkeypatches.py” and when that is imported, it applies the patches when the module body level code runs. However, it is difficult to find stable import point in Django to run monkey patching. Django does some really evil magic to initialize INSTALLED_APPS, database models and stuff and doing any kind of work during import causes headache.
So I figured out that you can apply monkey patches using middleware. Middleware applies the monkey patch when the first HTTP request hits the process (note that if you run preforked web server like FCGI every process has its own run-time code in memory). This technique, of course, cannot be used to monkey-patch things that happen before middleware processing, but it is not often needed.
Below is an example how to monkey-patch Django CMS to normalize its unicode output. There was an issue with unicode characters and this is a stop-gap measure to fix it. (I think the proper fix would be fix related Cufon font renderin Javascript library).
We add our monkey patcher to loaded middleware in settings.py.
The actual monkey patching happens by fiddling with the class code in process_request(). Note that in this particular case we only need to transform the output of the original function, we can simply hold a reference into it, call it and perform our transformation on the result. This way our monkey patch do not hinder the orignal function and is update safe (it does not matter if the code of PlaceholderNode.render method changes).
As far as I know, monkey patching is something PHP cannot do 🙂