Twisted

Installation

  1. Open Web Platform Installer and install "Python project":

Example wsgi.py

def application(environ, start_response):
    start_response('200 OK', [('Content-type','text/html'),])
    yield "<html><body>You requested <code>"
    yield environ.get('PATH_INFO')
    yield "</code></body></html>"

Deployment

To deploy Python Tornado application you will need to install Python Hosting Package and Twisted on a target server. Then just copy IIS web site from one machine to another.

web.config example

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
 <system.webServer>
  <heliconZoo>
   <application name="twisted.wsgi.app" >
    <environmentVariables>
     <add name="PYTHONPATH" value="%APPL_PHYSICAL_PATH%;%APPL_PHYSICAL_PATH%\python_modules\Lib\site-packages;%PYTHONPATH%" /> 
     <add name="WSGI_APP" value="wsgi.application" />
     <add name="DEPLOY_FILE" value="deploy.py" />
     <add name="DEPLOY_LOG" value="log\deploy.log" />
    </environmentVariables>
   </application>
  </heliconZoo>
  <handlers>
   <add name="twisted.wsgi.app#x86" scriptProcessor="python.2.7.twisted"  
        path="*" verb="*" modules="HeliconZoo_x86" preCondition="bitness32" 
        resourceType="Unspecified" requireAccess="Script" />
   <add name="twisted.wsgi.app#x64" scriptProcessor="python.2.7.twisted"  
        path="*" verb="*" modules="HeliconZoo_x64" preCondition="bitness64" 
        resourceType="Unspecified" requireAccess="Script" />
   </handlers>
 </system.webServer>
</configuration>

Environment variables

  • PYTHONPATH — path to Python modules. In the example it points to application root, the python_modules\Lib\site-packages subfolder and also includes value defined by user.
  • WSGI_APP — full path to the application’s entry point function.
  • WATCH_FILE_CHANGES_MASK — files to watch. Worker is restarted every time a file of specified type changes. In the example all .py files are watched.

deploy.py file example

Deploy file is used to execute commands, such as components installations or database migrations, on a server when the application initially starts or updated. The following code is only an example. We recommend you to use deploy.py file that comes with the Python project template.

# This file is example of deploy.py
# The file is executed once on the first request after every restart of IIS application.
# The file output is redirected to log file described in DEPLOG_LOG environment variable.

import sys
import os
import os.path

PROJECT_DIR = os.path.dirname(__file__)
os.chdir(PROJECT_DIR)

PIP_EXE = os.path.join(os.path.dirname(sys.executable), 'scripts\\pip.exe')

# update APPDATA env for pip
os.environ['APPDATA'] = os.path.join(PROJECT_DIR, 'python_modules')

# install requirements to local folder
os.system('{0} install --install-option="--prefix={1}" --requirement=requirements.txt'.format(PIP_EXE, os.path.join(PROJECT_DIR, 'python_modules')))