1 <?xml version="1.0" encoding="utf-8"?><!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html lang="en" xmlns="http://www.w3.org/1999/xhtml">
3 <title>Twisted Documentation: Configuring and Using the Twisted Web Server</title>
4 <link href="stylesheet.css" rel="stylesheet" type="text/css"/>
8 <h1 class="title">Configuring and Using the Twisted Web Server</h1>
9 <div class="toc"><ol><li><a href="#auto0">Twisted Web Development</a></li><ul><li><a href="#auto1">Main Concepts</a></li><li><a href="#auto2">Site Objects</a></li><li><a href="#auto3">Resource objects</a></li><li><a href="#auto4">Resource Trees</a></li><li><a href="#auto5">.rpy scripts</a></li><li><a href="#auto6">Resource rendering</a></li><li><a href="#auto7">Session</a></li><li><a href="#auto8">Proxies and reverse proxies</a></li></ul><li><a href="#auto9">Advanced Configuration</a></li><ul><li><a href="#auto10">Adding Children</a></li><li><a href="#auto11">Modifying File Resources</a></li><li><a href="#auto12">Virtual Hosts</a></li><li><a href="#auto13">Advanced Techniques</a></li></ul><li><a href="#auto14">Running a Twisted Web Server</a></li><ul><li><a href="#auto15">Serving Flat HTML</a></li><li><a href="#auto16">Resource Scripts</a></li><li><a href="#auto17">Web UIs</a></li><li><a href="#auto18">Spreadable Web Servers</a></li><li><a href="#auto19">Serving PHP/Perl/CGI</a></li><li><a href="#auto20">Serving WSGI Applications</a></li><li><a href="#auto21">Using VHostMonster</a></li></ul><li><a href="#auto22">Rewriting URLs</a></li><li><a href="#auto23">Knowing When We're Not Wanted</a></li><li><a href="#auto24">As-Is Serving</a></li></ol></div>
13 <h2>Twisted Web Development<a name="auto0"/></h2><a name="development" shape="rect"/>
15 <p>Twisted Web serves Python objects that implement the interface
18 <br clear="none"/><img alt="Twisted Web process" src="../img/web-process.png"/>
20 <h3>Main Concepts<a name="auto1"/></h3>
24 <li><a href="#sites" shape="rect">Site Objects</a> are responsible for
25 creating <code>HTTPChannel</code> instances to parse the HTTP request,
26 and begin the object lookup process. They contain the root Resource,
27 the resource which represents the URL <code>/</code> on the site.</li>
29 <li><a href="#resources" shape="rect">Resource</a> objects represent a single URL segment. The <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.resource.IResource.html" title="twisted.web.resource.IResource">IResource</a></code> interface describes the methods a Resource object must implement in order to participate in the object publishing process.</li>
31 <li><a href="#trees" shape="rect">Resource trees</a> are arrangements of Resource objects into a Resource tree. Starting at the root Resource object, the tree of Resource objects defines the URLs which will be valid.</li>
33 <li><a href="#rpys" shape="rect">.rpy scripts</a> are python scripts which the twisted.web static file server will execute, much like a CGI. However, unlike CGI they must create a Resource object which will be rendered when the URL is visited.</li>
35 <li><a href="#rendering" shape="rect">Resource rendering</a> occurs when Twisted Web locates a leaf Resource object. A Resource can either return an html string or write to the request object.</li>
37 <li><a href="#sessions" shape="rect">Session</a> objects allow you to store information across multiple requests. Each individual browser using the system has a unique Session instance.</li>
41 <p>The Twisted Web server is started through the Twisted Daemonizer, as in:</p>
43 <pre class="shell" xml:space="preserve">
47 <h3>Site Objects<a name="auto2"/></h3>
48 <a name="sites" shape="rect"/>
50 <p>Site objects serve as the glue between a port to listen for HTTP requests on, and a root Resource object.</p>
52 <p>When using <code>twistd -n web --path /foo/bar/baz</code>, a Site object is created with a root Resource that serves files out of the given path.</p>
54 <p>You can also create a <code>Site</code> instance by hand, passing
55 it a <code>Resource</code> object which will serve as the root of the
58 <pre class="python"><p class="py-linenumber"> 1
69 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">server</span>, <span class="py-src-variable">resource</span>
70 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">internet</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">reactor</span>
72 <span class="py-src-keyword">class</span> <span class="py-src-identifier">Simple</span>(<span class="py-src-parameter">resource</span>.<span class="py-src-parameter">Resource</span>):
73 <span class="py-src-variable">isLeaf</span> = <span class="py-src-variable">True</span>
74 <span class="py-src-keyword">def</span> <span class="py-src-identifier">render_GET</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">request</span>):
75 <span class="py-src-keyword">return</span> <span class="py-src-string">"<html>Hello, world!</html>"</span>
77 <span class="py-src-variable">site</span> = <span class="py-src-variable">server</span>.<span class="py-src-variable">Site</span>(<span class="py-src-variable">Simple</span>())
78 <span class="py-src-variable">reactor</span>.<span class="py-src-variable">listenTCP</span>(<span class="py-src-number">8080</span>, <span class="py-src-variable">site</span>)
79 <span class="py-src-variable">reactor</span>.<span class="py-src-variable">run</span>()
82 <h3>Resource objects<a name="auto3"/></h3>
83 <a name="resources" shape="rect"/>
85 <p><code>Resource</code> objects represent a single URL segment of a site. During URL parsing, <code>getChild</code> is called on the current <code>Resource</code> to produce the next <code>Resource</code> object.</p>
87 <p>When the leaf Resource is reached, either because there were no more URL segments or a Resource had isLeaf set to True, the leaf Resource is rendered by calling <code>render(request)</code>. See <q>Resource Rendering</q> below for more about this.</p>
89 <p>During the Resource location process, the URL segments which have already been processed and those which have not yet been processed are available in <code>request.prepath</code> and <code>request.postpath</code>.</p>
91 <p>A Resource can know where it is in the URL tree by looking at <code>request.prepath</code>, a list of URL segment strings.</p>
93 <p>A Resource can know which path segments will be processed after it by looking at <code>request.postpath</code>.</p>
95 <p>If the URL ends in a slash, for example <code>http://example.com/foo/bar/</code>, the final URL segment will be an empty string. Resources can thus know if they were requested with or without a final slash.</p>
97 <p>Here is a simple Resource object:</p>
99 <pre class="python"><p class="py-linenumber"> 1
112 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span>.<span class="py-src-variable">resource</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">Resource</span>
114 <span class="py-src-keyword">class</span> <span class="py-src-identifier">Hello</span>(<span class="py-src-parameter">Resource</span>):
115 <span class="py-src-variable">isLeaf</span> = <span class="py-src-variable">True</span>
116 <span class="py-src-keyword">def</span> <span class="py-src-identifier">getChild</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">name</span>, <span class="py-src-parameter">request</span>):
117 <span class="py-src-keyword">if</span> <span class="py-src-variable">name</span> == <span class="py-src-string">''</span>:
118 <span class="py-src-keyword">return</span> <span class="py-src-variable">self</span>
119 <span class="py-src-keyword">return</span> <span class="py-src-variable">Resource</span>.<span class="py-src-variable">getChild</span>(<span class="py-src-variable">self</span>, <span class="py-src-variable">name</span>, <span class="py-src-variable">request</span>)
121 <span class="py-src-keyword">def</span> <span class="py-src-identifier">render_GET</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">request</span>):
122 <span class="py-src-keyword">return</span> <span class="py-src-string">"Hello, world! I am located at %r."</span> % (<span class="py-src-variable">request</span>.<span class="py-src-variable">prepath</span>,)
124 <span class="py-src-variable">resource</span> = <span class="py-src-variable">Hello</span>()
127 <h3>Resource Trees<a name="auto4"/></h3>
128 <a name="trees" shape="rect"/>
130 <p>Resources can be arranged in trees using <code>putChild</code>. <code>putChild</code> puts a Resource instance into another Resource instance, making it available at the given path segment name:</p>
132 <pre class="python"><p class="py-linenumber">1
135 </p><span class="py-src-variable">root</span> = <span class="py-src-variable">Hello</span>()
136 <span class="py-src-variable">root</span>.<span class="py-src-variable">putChild</span>(<span class="py-src-string">'fred'</span>, <span class="py-src-variable">Hello</span>())
137 <span class="py-src-variable">root</span>.<span class="py-src-variable">putChild</span>(<span class="py-src-string">'bob'</span>, <span class="py-src-variable">Hello</span>())
140 <p>If this root resource is served as the root of a Site instance, the following URLs will all be valid:</p>
143 <li><code>http://example.com/</code></li>
144 <li><code>http://example.com/fred</code></li>
145 <li><code>http://example.com/bob</code></li>
146 <li><code>http://example.com/fred/</code></li>
147 <li><code>http://example.com/bob/</code></li>
151 <h3>.rpy scripts<a name="auto5"/></h3>
152 <a name="rpys" shape="rect"/>
154 <p>Files with the extension <code>.rpy</code> are python scripts which, when placed in a directory served by Twisted Web, will be executed when visited through the web.</p>
156 <p>An <code>.rpy</code> script must define a variable, <code>resource</code>, which is the Resource object that will render the request.</p>
158 <p><code>.rpy</code> files are very convenient for rapid development and prototyping. Since they are executed on every web request, defining a Resource subclass in an <code>.rpy</code> will make viewing the results of changes to your class visible simply by refreshing the page:</p>
160 <pre class="python"><p class="py-linenumber">1
167 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span>.<span class="py-src-variable">resource</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">Resource</span>
169 <span class="py-src-keyword">class</span> <span class="py-src-identifier">MyResource</span>(<span class="py-src-parameter">Resource</span>):
170 <span class="py-src-keyword">def</span> <span class="py-src-identifier">render_GET</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">request</span>):
171 <span class="py-src-keyword">return</span> <span class="py-src-string">"<html>Hello, world!</html>"</span>
173 <span class="py-src-variable">resource</span> = <span class="py-src-variable">MyResource</span>()
176 <p>However, it is often a better idea to define Resource subclasses in Python modules. In order for changes in modules to be visible, you must either restart the Python process, or reload the module:</p>
178 <pre class="python"><p class="py-linenumber">1
184 </p><span class="py-src-keyword">import</span> <span class="py-src-variable">myresource</span>
186 <span class="py-src-comment">## Comment out this line when finished debugging</span>
187 <span class="py-src-variable">reload</span>(<span class="py-src-variable">myresource</span>)
189 <span class="py-src-variable">resource</span> = <span class="py-src-variable">myresource</span>.<span class="py-src-variable">MyResource</span>()
192 <p>Creating a Twisted Web server which serves a directory is easy:</p>
194 <pre class="shell" xml:space="preserve">
195 % twistd -n web --path /Users/dsp/Sites
198 <h3>Resource rendering<a name="auto6"/></h3>
199 <a name="rendering" shape="rect"/>
201 <p>Resource rendering occurs when Twisted Web locates a leaf Resource object to handle a web request. A Resource's <code>render</code> method may do various things to produce output which will be sent back to the browser:</p>
204 <li>Return a string</li>
205 <li>Call <code>request.write("stuff")</code> as many times as desired, then call <code>request.finish()</code> and return <code>server.NOT_DONE_YET</code> (This is deceptive, since you are in fact done with the request, but is the correct way to do this)</li>
207 <li>Request a <code>Deferred</code>, return <code>server.NOT_DONE_YET</code>, and call <code>request.write("stuff")</code> and <code>request.finish()</code> later, in a callback on the <code>Deferred</code>.</li>
212 The <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.resource.Resource.html" title="twisted.web.resource.Resource">Resource</a></code>
213 class, which is usually what one's Resource classes subclass, has a
214 convenient default implementation
215 of <code class="python">render</code>. It will call a method
216 named <code class="python">self.render_METHOD</code>
217 where <q>METHOD</q> is whatever HTTP method was used to request this
218 resource. Examples: request_GET, request_POST, request_HEAD, and so
219 on. It is recommended that you have your resource classes
220 subclass <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.resource.Resource.html" title="twisted.web.resource.Resource">Resource</a></code>
221 and implement <code class="python">render_METHOD</code> methods as
222 opposed to <code class="python">render</code> itself. Note that for
223 certain resources, <code class="python">request_POST =
224 request_GET</code> may be desirable in case one wants to process
225 arguments passed to the resource regardless of whether they used GET
226 (<code>?foo=bar&baz=quux</code>, and so forth) or POST.
230 <h3>Session<a name="auto7"/></h3>
231 <a name="sessions" shape="rect"/>
233 <p>HTTP is a stateless protocol; every request-response is treated as an individual unit, distinguishable from any other request only by the URL requested. With the advent of Cookies in the mid nineties, dynamic web servers gained the ability to distinguish between requests coming from different <em>browser sessions</em> by sending a Cookie to a browser. The browser then sends this cookie whenever it makes a request to a web server, allowing the server to track which requests come from which browser session.</p>
235 <p>Twisted Web provides an abstraction of this browser-tracking behavior called the <em>Session object</em>. Calling <code>request.getSession()</code> checks to see if a session cookie has been set; if not, it creates a unique session id, creates a Session object, stores it in the Site, and returns it. If a session object already exists, the same session object is returned. In this way, you can store data specific to the session in the session object.</p>
237 <img src="../img/web-session.png"/>
239 <h3>Proxies and reverse proxies<a name="auto8"/></h3>
240 <a name="proxies" shape="rect"/>
242 <p>A proxy is a general term for a server that functions as an intermediary
243 between clients and other servers.</p>
245 <p>Twisted supports two main proxy variants: a <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.proxy.Proxy.html" title="twisted.web.proxy.Proxy">Proxy</a></code> and a <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.proxy.ReverseProxy.html" title="twisted.web.proxy.ReverseProxy">ReverseProxy</a></code>.</p>
249 <p>A proxy forwards requests made by a client to a destination server. Proxies
250 typically sit on the internal network for a client or out on the internet, and
251 have many uses, including caching, packet filtering, auditing, and circumventing
252 local access restrictions to web content.</p>
254 <p>Here is an example of a simple but complete web proxy:</p>
256 <pre class="python"><p class="py-linenumber">1
265 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">proxy</span>, <span class="py-src-variable">http</span>
266 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">internet</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">reactor</span>
268 <span class="py-src-keyword">class</span> <span class="py-src-identifier">ProxyFactory</span>(<span class="py-src-parameter">http</span>.<span class="py-src-parameter">HTTPFactory</span>):
269 <span class="py-src-keyword">def</span> <span class="py-src-identifier">buildProtocol</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">addr</span>):
270 <span class="py-src-keyword">return</span> <span class="py-src-variable">proxy</span>.<span class="py-src-variable">Proxy</span>()
272 <span class="py-src-variable">reactor</span>.<span class="py-src-variable">listenTCP</span>(<span class="py-src-number">8080</span>, <span class="py-src-variable">ProxyFactory</span>())
273 <span class="py-src-variable">reactor</span>.<span class="py-src-variable">run</span>()
276 <p>With this proxy running, you can configure your web browser to use
277 <code>localhost:8080</code> as a proxy. After doing so, when browsing the web
278 all requests will go through this proxy.</p>
280 <p><code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.proxy.Proxy.html" title="twisted.web.proxy.Proxy">Proxy</a></code> inherits
281 from <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.http.HTTPChannel.html" title="twisted.web.http.HTTPChannel">http.HTTPChannel</a></code>. Each client
282 request to the proxy generates a <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.proxy.ProxyRequest.html" title="twisted.web.proxy.ProxyRequest">ProxyRequest</a></code> from the proxy to the destination
283 server on behalf of the client. <code>ProxyRequest</code> uses
284 a <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.proxy.ProxyClientFactory.html" title="twisted.web.proxy.ProxyClientFactory">ProxyClientFactory</a></code> to create
285 an instance of the <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.proxy.ProxyClient.html" title="twisted.web.proxy.ProxyClient">ProxyClient</a></code>
286 protocol for the connection. <code>ProxyClient</code> inherits
287 from <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.http.HTTPClient.html" title="twisted.web.http.HTTPClient">http.HTTPClient</a></code>. Subclass <code>ProxyRequest</code> to
288 customize the way requests are processed or logged.</p>
290 <h4>ReverseProxyResource</h4>
292 <p>A reverse proxy retrieves resources from other servers on behalf of a
293 client. Reverse proxies typically sit inside the server's internal network and
294 are used for caching, application firewalls, and load balancing.</p>
296 <p>Here is an example of a basic reverse proxy:</p>
298 <pre class="python"><p class="py-linenumber">1
304 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">internet</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">reactor</span>
305 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">proxy</span>, <span class="py-src-variable">server</span>
307 <span class="py-src-variable">site</span> = <span class="py-src-variable">server</span>.<span class="py-src-variable">Site</span>(<span class="py-src-variable">proxy</span>.<span class="py-src-variable">ReverseProxyResource</span>(<span class="py-src-string">'www.yahoo.com'</span>, <span class="py-src-number">80</span>, <span class="py-src-string">''</span>))
308 <span class="py-src-variable">reactor</span>.<span class="py-src-variable">listenTCP</span>(<span class="py-src-number">8080</span>, <span class="py-src-variable">site</span>)
309 <span class="py-src-variable">reactor</span>.<span class="py-src-variable">run</span>()
312 <p>With this reverse proxy running locally, you can
313 visit <code>http://localhost:8080</code> in your web browser, and the reverse
314 proxy will proxy your connection to
315 <code>www.yahoo.com</code>.</p>
317 <p>In this example we use <code base="twisted.web">server.Site</code> to serve
318 a <code base="twisted.web.proxy">ReverseProxyResource</code> directly. There is
319 also a <code>ReverseProxy</code> family of classes
320 in <code>twisted.web.proxy</code> mirroring those of the <code>Proxy</code>
323 <p>Like <code>Proxy</code>, <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.proxy.ReverseProxy.html" title="twisted.web.proxy.ReverseProxy">ReverseProxy</a></code> inherits
324 from <code>http.HTTPChannel</code>. Each client request to the reverse proxy
325 generates a <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.proxy.ReverseProxyRequest.html" title="twisted.web.proxy.ReverseProxyRequest">ReverseProxyRequest</a></code> to the destination
326 server. Like <code>ProxyRequest</code>, <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.proxy.ReverseProxyRequest.html" title="twisted.web.proxy.ReverseProxyRequest">ReverseProxyRequest</a></code> uses a <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.proxy.ProxyClientFactory.html" title="twisted.web.proxy.ProxyClientFactory">ProxyClientFactory</a></code> to create an instance of
327 the <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.proxy.ProxyClient.html" title="twisted.web.proxy.ProxyClient">ProxyClient</a></code> protocol for
330 <p>Additional examples of proxies and reverse proxies can be found in
331 the <a href="../examples/index.html" shape="rect">Twisted web examples</a>.</p>
333 <h2>Advanced Configuration<a name="auto9"/></h2>
335 <p>Non-trivial configurations of Twisted Web are achieved with Python
336 configuration files. This is a Python snippet which builds up a
337 variable called application. Usually,
338 a <code>twisted.application.internet.TCPServer</code>
339 instance will be used to make the application listen on a TCP port
340 (80, in case direct web serving is desired), with the listener being
341 a <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.server.Site.html" title="twisted.web.server.Site">twisted.web.server.Site</a></code>. The resulting file
342 can then be run with <code class="shell">twistd
343 -y</code>. Alternatively a reactor object can be used directly to make
344 a runnable script.</p>
346 <p>The <code>Site</code> will wrap a <code>Resource</code> object -- the
349 <pre class="python"><p class="py-linenumber">1
358 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">application</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">internet</span>, <span class="py-src-variable">service</span>
359 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">static</span>, <span class="py-src-variable">server</span>
361 <span class="py-src-variable">root</span> = <span class="py-src-variable">static</span>.<span class="py-src-variable">File</span>(<span class="py-src-string">"/var/www/htdocs"</span>)
362 <span class="py-src-variable">application</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">Application</span>(<span class="py-src-string">'web'</span>)
363 <span class="py-src-variable">site</span> = <span class="py-src-variable">server</span>.<span class="py-src-variable">Site</span>(<span class="py-src-variable">root</span>)
364 <span class="py-src-variable">sc</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">IServiceCollection</span>(<span class="py-src-variable">application</span>)
365 <span class="py-src-variable">i</span> = <span class="py-src-variable">internet</span>.<span class="py-src-variable">TCPServer</span>(<span class="py-src-number">80</span>, <span class="py-src-variable">site</span>)
366 <span class="py-src-variable">i</span>.<span class="py-src-variable">setServiceParent</span>(<span class="py-src-variable">sc</span>)
369 <p>Most advanced configurations will be in the form of tweaking the
370 root resource object.</p>
372 <h3>Adding Children<a name="auto10"/></h3>
374 <p>Usually, the root's children will be based on the filesystem's contents.
375 It is possible to override the filesystem by explicit <code>putChild</code>
378 <p>Here are two examples. The first one adds a <code>/doc</code> child
379 to serve the documentation of the installed packages, while the second
380 one adds a <code>cgi-bin</code> directory for CGI scripts.</p>
382 <pre class="python"><p class="py-linenumber">1
389 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">internet</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">reactor</span>
390 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">static</span>, <span class="py-src-variable">server</span>
392 <span class="py-src-variable">root</span> = <span class="py-src-variable">static</span>.<span class="py-src-variable">File</span>(<span class="py-src-string">"/var/www/htdocs"</span>)
393 <span class="py-src-variable">root</span>.<span class="py-src-variable">putChild</span>(<span class="py-src-string">"doc"</span>, <span class="py-src-variable">static</span>.<span class="py-src-variable">File</span>(<span class="py-src-string">"/usr/share/doc"</span>))
394 <span class="py-src-variable">reactor</span>.<span class="py-src-variable">listenTCP</span>(<span class="py-src-number">80</span>, <span class="py-src-variable">server</span>.<span class="py-src-variable">Site</span>(<span class="py-src-variable">root</span>))
395 <span class="py-src-variable">reactor</span>.<span class="py-src-variable">run</span>()
398 <pre class="python"><p class="py-linenumber">1
405 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">internet</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">reactor</span>
406 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">static</span>, <span class="py-src-variable">server</span>, <span class="py-src-variable">twcgi</span>
408 <span class="py-src-variable">root</span> = <span class="py-src-variable">static</span>.<span class="py-src-variable">File</span>(<span class="py-src-string">"/var/www/htdocs"</span>)
409 <span class="py-src-variable">root</span>.<span class="py-src-variable">putChild</span>(<span class="py-src-string">"cgi-bin"</span>, <span class="py-src-variable">twcgi</span>.<span class="py-src-variable">CGIDirectory</span>(<span class="py-src-string">"/var/www/cgi-bin"</span>))
410 <span class="py-src-variable">reactor</span>.<span class="py-src-variable">listenTCP</span>(<span class="py-src-number">80</span>, <span class="py-src-variable">server</span>.<span class="py-src-variable">Site</span>(<span class="py-src-variable">root</span>))
411 <span class="py-src-variable">reactor</span>.<span class="py-src-variable">run</span>()
414 <h3>Modifying File Resources<a name="auto11"/></h3>
416 <p><code>File</code> resources, be they root object or children
417 thereof, have two important attributes that often need to be
418 modified: <code>indexNames</code>
419 and <code>processors</code>. <code>indexNames</code> determines which
420 files are treated as <q>index files</q> -- served up when a directory
421 is rendered. <code>processors</code> determine how certain file
422 extensions are treated.</p>
424 <p>Here is an example for both, creating a site where all <code>.rpy</code>
425 extensions are Resource Scripts, and which renders directories by
426 searching for a <code>index.rpy</code> file.</p>
428 <pre class="python"><p class="py-linenumber"> 1
439 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">application</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">internet</span>, <span class="py-src-variable">service</span>
440 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">static</span>, <span class="py-src-variable">server</span>, <span class="py-src-variable">script</span>
442 <span class="py-src-variable">root</span> = <span class="py-src-variable">static</span>.<span class="py-src-variable">File</span>(<span class="py-src-string">"/var/www/htdocs"</span>)
443 <span class="py-src-variable">root</span>.<span class="py-src-variable">indexNames</span>=[<span class="py-src-string">'index.rpy'</span>]
444 <span class="py-src-variable">root</span>.<span class="py-src-variable">processors</span> = {<span class="py-src-string">'.rpy'</span>: <span class="py-src-variable">script</span>.<span class="py-src-variable">ResourceScript</span>}
445 <span class="py-src-variable">application</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">Application</span>(<span class="py-src-string">'web'</span>)
446 <span class="py-src-variable">sc</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">IServiceCollection</span>(<span class="py-src-variable">application</span>)
447 <span class="py-src-variable">site</span> = <span class="py-src-variable">server</span>.<span class="py-src-variable">Site</span>(<span class="py-src-variable">root</span>)
448 <span class="py-src-variable">i</span> = <span class="py-src-variable">internet</span>.<span class="py-src-variable">TCPServer</span>(<span class="py-src-number">80</span>, <span class="py-src-variable">site</span>)
449 <span class="py-src-variable">i</span>.<span class="py-src-variable">setServiceParent</span>(<span class="py-src-variable">sc</span>)
452 <p><code>File</code> objects also have a method called <code>ignoreExt</code>.
453 This method can be used to give extension-less URLs to users, so that
454 implementation is hidden. Here is an example:</p>
456 <pre class="python"><p class="py-linenumber"> 1
467 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">application</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">internet</span>, <span class="py-src-variable">service</span>
468 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">static</span>, <span class="py-src-variable">server</span>, <span class="py-src-variable">script</span>
470 <span class="py-src-variable">root</span> = <span class="py-src-variable">static</span>.<span class="py-src-variable">File</span>(<span class="py-src-string">"/var/www/htdocs"</span>)
471 <span class="py-src-variable">root</span>.<span class="py-src-variable">ignoreExt</span>(<span class="py-src-string">".rpy"</span>)
472 <span class="py-src-variable">root</span>.<span class="py-src-variable">processors</span> = {<span class="py-src-string">'.rpy'</span>: <span class="py-src-variable">script</span>.<span class="py-src-variable">ResourceScript</span>}
473 <span class="py-src-variable">application</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">Application</span>(<span class="py-src-string">'web'</span>)
474 <span class="py-src-variable">sc</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">IServiceCollection</span>(<span class="py-src-variable">application</span>)
475 <span class="py-src-variable">site</span> = <span class="py-src-variable">server</span>.<span class="py-src-variable">Site</span>(<span class="py-src-variable">root</span>)
476 <span class="py-src-variable">i</span> = <span class="py-src-variable">internet</span>.<span class="py-src-variable">TCPServer</span>(<span class="py-src-number">80</span>, <span class="py-src-variable">site</span>)
477 <span class="py-src-variable">i</span>.<span class="py-src-variable">setServiceParent</span>(<span class="py-src-variable">sc</span>)
480 <p>Now, a URL such as <code>/foo</code> might be served from a Resource
481 Script called <code>foo.rpy</code>, if no file by the name of <code>foo</code>
484 <h3>Virtual Hosts<a name="auto12"/></h3>
486 <p>Virtual hosting is done via a special resource, that should be used
488 -- <code>NameVirtualHost</code>. <code>NameVirtualHost</code> has an
489 attribute named <code>default</code>, which holds the default
490 website. If a different root for some other name is desired,
491 the <code>addHost</code> method should be called.</p>
493 <pre class="python"><p class="py-linenumber"> 1
518 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">application</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">internet</span>, <span class="py-src-variable">service</span>
519 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">static</span>, <span class="py-src-variable">server</span>, <span class="py-src-variable">vhost</span>, <span class="py-src-variable">script</span>
521 <span class="py-src-variable">root</span> = <span class="py-src-variable">vhost</span>.<span class="py-src-variable">NameVirtualHost</span>()
523 <span class="py-src-comment"># Add a default -- htdocs</span>
524 <span class="py-src-variable">root</span>.<span class="py-src-variable">default</span>=<span class="py-src-variable">static</span>.<span class="py-src-variable">File</span>(<span class="py-src-string">"/var/www/htdocs"</span>)
526 <span class="py-src-comment"># Add a simple virtual host -- foo.com</span>
527 <span class="py-src-variable">root</span>.<span class="py-src-variable">addHost</span>(<span class="py-src-string">"foo.com"</span>, <span class="py-src-variable">static</span>.<span class="py-src-variable">File</span>(<span class="py-src-string">"/var/www/foo"</span>))
529 <span class="py-src-comment"># Add a simple virtual host -- bar.com</span>
530 <span class="py-src-variable">root</span>.<span class="py-src-variable">addHost</span>(<span class="py-src-string">"bar.com"</span>, <span class="py-src-variable">static</span>.<span class="py-src-variable">File</span>(<span class="py-src-string">"/var/www/bar"</span>))
532 <span class="py-src-comment"># The "baz" people want to use Resource Scripts in their web site</span>
533 <span class="py-src-variable">baz</span> = <span class="py-src-variable">static</span>.<span class="py-src-variable">File</span>(<span class="py-src-string">"/var/www/baz"</span>)
534 <span class="py-src-variable">baz</span>.<span class="py-src-variable">processors</span> = {<span class="py-src-string">'.rpy'</span>: <span class="py-src-variable">script</span>.<span class="py-src-variable">ResourceScript</span>}
535 <span class="py-src-variable">baz</span>.<span class="py-src-variable">ignoreExt</span>(<span class="py-src-string">'.rpy'</span>)
536 <span class="py-src-variable">root</span>.<span class="py-src-variable">addHost</span>(<span class="py-src-string">'baz'</span>, <span class="py-src-variable">baz</span>)
538 <span class="py-src-variable">application</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">Application</span>(<span class="py-src-string">'web'</span>)
539 <span class="py-src-variable">sc</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">IServiceCollection</span>(<span class="py-src-variable">application</span>)
540 <span class="py-src-variable">site</span> = <span class="py-src-variable">server</span>.<span class="py-src-variable">Site</span>(<span class="py-src-variable">root</span>)
541 <span class="py-src-variable">i</span> = <span class="py-src-variable">internet</span>.<span class="py-src-variable">TCPServer</span>(<span class="py-src-number">80</span>, <span class="py-src-variable">site</span>)
542 <span class="py-src-variable">i</span>.<span class="py-src-variable">setServiceParent</span>(<span class="py-src-variable">sc</span>)
545 <h3>Advanced Techniques<a name="auto13"/></h3>
547 <p>Since the configuration is a Python snippet, it is possible to
548 use the full power of Python. Here are some simple examples:</p>
550 <pre class="python"><p class="py-linenumber"> 1
565 </p><span class="py-src-comment"># No need for configuration of virtual hosts -- just make sure</span>
566 <span class="py-src-comment"># a directory /var/vhosts/<vhost name> exists:</span>
567 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">vhost</span>, <span class="py-src-variable">static</span>, <span class="py-src-variable">server</span>
568 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">application</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">internet</span>, <span class="py-src-variable">service</span>
570 <span class="py-src-variable">root</span> = <span class="py-src-variable">vhost</span>.<span class="py-src-variable">NameVirtualHost</span>()
571 <span class="py-src-variable">root</span>.<span class="py-src-variable">default</span> = <span class="py-src-variable">static</span>.<span class="py-src-variable">File</span>(<span class="py-src-string">"/var/www/htdocs"</span>)
572 <span class="py-src-keyword">for</span> <span class="py-src-variable">dir</span> <span class="py-src-keyword">in</span> <span class="py-src-variable">os</span>.<span class="py-src-variable">listdir</span>(<span class="py-src-string">"/var/vhosts"</span>):
573 <span class="py-src-variable">root</span>.<span class="py-src-variable">addHost</span>(<span class="py-src-variable">dir</span>, <span class="py-src-variable">static</span>.<span class="py-src-variable">File</span>(<span class="py-src-variable">os</span>.<span class="py-src-variable">path</span>.<span class="py-src-variable">join</span>(<span class="py-src-string">"/var/vhosts"</span>, <span class="py-src-variable">dir</span>)))
575 <span class="py-src-variable">application</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">Application</span>(<span class="py-src-string">'web'</span>)
576 <span class="py-src-variable">sc</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">IServiceCollection</span>(<span class="py-src-variable">application</span>)
577 <span class="py-src-variable">site</span> = <span class="py-src-variable">server</span>.<span class="py-src-variable">Site</span>(<span class="py-src-variable">root</span>)
578 <span class="py-src-variable">i</span> = <span class="py-src-variable">internet</span>.<span class="py-src-variable">TCPServer</span>(<span class="py-src-number">80</span>, <span class="py-src-variable">site</span>)
579 <span class="py-src-variable">i</span>.<span class="py-src-variable">setServiceParent</span>(<span class="py-src-variable">sc</span>)
582 <pre class="python"><p class="py-linenumber"> 1
594 </p><span class="py-src-comment"># Determine ports we listen on based on a file with numbers:</span>
595 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">vhost</span>, <span class="py-src-variable">static</span>, <span class="py-src-variable">server</span>
596 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">application</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">internet</span>, <span class="py-src-variable">service</span>
598 <span class="py-src-variable">root</span> = <span class="py-src-variable">static</span>.<span class="py-src-variable">File</span>(<span class="py-src-string">"/var/www/htdocs"</span>)
600 <span class="py-src-variable">site</span> = <span class="py-src-variable">server</span>.<span class="py-src-variable">Site</span>(<span class="py-src-variable">root</span>)
601 <span class="py-src-variable">application</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">Application</span>(<span class="py-src-string">'web'</span>)
602 <span class="py-src-variable">serviceCollection</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">IServiceCollection</span>(<span class="py-src-variable">application</span>)
604 <span class="py-src-keyword">for</span> <span class="py-src-variable">num</span> <span class="py-src-keyword">in</span> <span class="py-src-variable">map</span>(<span class="py-src-variable">int</span>, <span class="py-src-variable">open</span>(<span class="py-src-string">"/etc/web/ports"</span>).<span class="py-src-variable">read</span>().<span class="py-src-variable">split</span>()):
605 <span class="py-src-variable">serviceCollection</span>.<span class="py-src-variable">addCollection</span>(<span class="py-src-variable">internet</span>.<span class="py-src-variable">TCPServer</span>(<span class="py-src-variable">num</span>, <span class="py-src-variable">site</span>))
609 <h2>Running a Twisted Web Server<a name="auto14"/></h2>
611 <p>In many cases, you'll end up repeating common usage patterns of
612 twisted.web. In those cases you'll probably want to use Twisted's
613 pre-configured web server setup.</p>
615 <p>The easiest way to run a Twisted Web server is with the Twisted Daemonizer.
616 For example, this command will run a web server which serves static files from
617 a particular directory:</p>
619 <pre class="shell" xml:space="preserve">
620 % twistd web --path /path/to/web/content
623 <p>If you just want to serve content from your own home directory, the
624 following will do:</p>
626 <pre class="shell" xml:space="preserve">
627 % twistd web --path ~/public_html/
630 <p>You can stop the server at any time by going back to the directory you
631 started it in and running the command:</p>
633 <pre class="shell" xml:space="preserve">
634 % kill `cat twistd.pid`
637 <p> Some other configuration options are available as well: </p>
640 <li> <code>--port</code>: Specify the port for the web
641 server to listen on. This defaults to 8080. </li>
642 <li> <code>--logfile</code>: Specify the path to the
646 <p> The full set of options that are available can be seen with: </p>
648 <pre class="shell" xml:space="preserve">
652 <h3>Serving Flat HTML<a name="auto15"/></h3>
654 <p> Twisted Web serves flat HTML files just as it does any other flat file. </p>
656 <a name="ResourceScripts" shape="rect"/>
657 <h3>Resource Scripts<a name="auto16"/></h3>
659 <p> A Resource script is a Python file ending with the extension <code>.rpy</code>, which is required to create an instance of a (subclass of a) <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.resource.Resource.html" title="twisted.web.resource.Resource">twisted.web.resource.Resource</a></code>. </p>
661 <p> Resource scripts have 3 special variables: </p>
664 <li> <code class="py-src-identifier">__file__</code>: The name of the .rpy file, including the full path. This variable is automatically defined and present within the namespace. </li>
665 <li> <code class="py-src-identifier">registry</code>: An object of class <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.static.Registry.html" title="twisted.web.static.Registry">static.Registry</a></code>. It can be used to access and set persistent data keyed by a class.</li>
666 <li> <code class="py-src-identifier">resource</code>: The variable which must be defined by the script and set to the resource instance that will be used to render the page. </li>
669 <p> A very simple Resource Script might look like: </p>
671 <pre class="python"><p class="py-linenumber">1
677 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">resource</span>
678 <span class="py-src-keyword">class</span> <span class="py-src-identifier">MyGreatResource</span>(<span class="py-src-parameter">resource</span>.<span class="py-src-parameter">Resource</span>):
679 <span class="py-src-keyword">def</span> <span class="py-src-identifier">render_GET</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">request</span>):
680 <span class="py-src-keyword">return</span> <span class="py-src-string">"<html>foo</html>"</span>
682 <span class="py-src-variable">resource</span> = <span class="py-src-variable">MyGreatResource</span>()
685 <p> A slightly more complicated resource script, which accesses some
686 persistent data, might look like:</p>
688 <pre class="python"><p class="py-linenumber"> 1
702 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">resource</span>
703 <span class="py-src-keyword">from</span> <span class="py-src-variable">SillyWeb</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">Counter</span>
705 <span class="py-src-variable">counter</span> = <span class="py-src-variable">registry</span>.<span class="py-src-variable">getComponent</span>(<span class="py-src-variable">Counter</span>)
706 <span class="py-src-keyword">if</span> <span class="py-src-keyword">not</span> <span class="py-src-variable">counter</span>:
707 <span class="py-src-variable">registry</span>.<span class="py-src-variable">setComponent</span>(<span class="py-src-variable">Counter</span>, <span class="py-src-variable">Counter</span>())
708 <span class="py-src-variable">counter</span> = <span class="py-src-variable">registry</span>.<span class="py-src-variable">getComponent</span>(<span class="py-src-variable">Counter</span>)
710 <span class="py-src-keyword">class</span> <span class="py-src-identifier">MyResource</span>(<span class="py-src-parameter">resource</span>.<span class="py-src-parameter">Resource</span>):
711 <span class="py-src-keyword">def</span> <span class="py-src-identifier">render_GET</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">request</span>):
712 <span class="py-src-variable">counter</span>.<span class="py-src-variable">increment</span>()
713 <span class="py-src-keyword">return</span> <span class="py-src-string">"you are visitor %d"</span> % <span class="py-src-variable">counter</span>.<span class="py-src-variable">getValue</span>()
715 <span class="py-src-variable">resource</span> = <span class="py-src-variable">MyResource</span>()
718 <p> This is assuming you have the <code>SillyWeb.Counter</code> module,
719 implemented something like the following:</p>
721 <pre class="python"><p class="py-linenumber"> 1
731 </p><span class="py-src-keyword">class</span> <span class="py-src-identifier">Counter</span>:
733 <span class="py-src-keyword">def</span> <span class="py-src-identifier">__init__</span>(<span class="py-src-parameter">self</span>):
734 <span class="py-src-variable">self</span>.<span class="py-src-variable">value</span> = <span class="py-src-number">0</span>
736 <span class="py-src-keyword">def</span> <span class="py-src-identifier">increment</span>(<span class="py-src-parameter">self</span>):
737 <span class="py-src-variable">self</span>.<span class="py-src-variable">value</span> += <span class="py-src-number">1</span>
739 <span class="py-src-keyword">def</span> <span class="py-src-identifier">getValue</span>(<span class="py-src-parameter">self</span>):
740 <span class="py-src-keyword">return</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">value</span>
743 <h3>Web UIs<a name="auto17"/></h3>
746 The <a href="https://launchpad.net/nevow" shape="rect">Nevow</a> framework, available as
747 part of the <a href="https://launchpad.net/quotient" shape="rect">Quotient</a> project,
748 is an advanced system for giving Web UIs to your application. Nevow uses Twisted Web but is
749 not itself part of Twisted.
752 <a name="SpreadableWebServers" shape="rect"/>
753 <h3>Spreadable Web Servers<a name="auto18"/></h3>
755 <p> One of the most interesting applications of Twisted Web is the distributed webserver; multiple servers can all answer requests on the same port, using the <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.spread.html" title="twisted.spread">twisted.spread</a></code> package for <q>spreadable</q> computing. In two different directories, run the commands: </p>
757 <pre class="shell" xml:space="preserve">
759 % twistd web --personal [other options, if you desire]
762 <p> Once you're running both of these instances, go to <code>http://localhost:8080/your_username.twistd/</code> -- you will see the front page from the server you created with the <code>--personal</code> option. What's happening here is that the request you've sent is being relayed from the central (User) server to your own (Personal) server, over a PB connection. This technique can be highly useful for small <q>community</q> sites; using the code that makes this demo work, you can connect one HTTP port to multiple resources running with different permissions on the same machine, on different local machines, or even over the internet to a remote site. </p>
765 By default, a personal server listens on a UNIX socket in the owner's home
766 directory. The <code class="shell">--port</code> option can be used to make
767 it listen on a different address, such as a TCP or SSL server or on a UNIX
768 server in a different location. If you use this option to make a personal
769 server listen on a different address, the central (User) server won't be
770 able to find it, but a custom server which uses the same APIs as the central
771 server might. Another use of the <code class="shell">--port</code> option
772 is to make the UNIX server robust against system crashes. If the server
773 crashes and the UNIX socket is left on the filesystem, the personal server
774 will not be able to restart until it is removed. However, if <code class="shell">--port unix:/home/username/.twistd-web-pb:wantPID=1</code> is
775 supplied when creating the personal server, then a lockfile will be used to
776 keep track of whether the server socket is in use and automatically delete
780 <h3>Serving PHP/Perl/CGI<a name="auto19"/></h3>
782 <p>Everything related to CGI is located in
783 the <code>twisted.web.twcgi</code>, and it's here you'll find the
784 classes that you need to subclass in order to support the language of
785 your (or somebody elses) taste. You'll also need to create your own
786 kind of resource if you are using a non-unix operating system (such as
787 Windows), or if the default resources has wrong pathnames to the
790 <p>The following snippet is a .rpy that serves perl-files. Look at <code>twisted.web.twcgi</code>
791 for more examples regarding twisted.web and CGI.</p>
793 <pre class="python"><p class="py-linenumber">1
802 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">static</span>, <span class="py-src-variable">twcgi</span>
804 <span class="py-src-keyword">class</span> <span class="py-src-identifier">PerlScript</span>(<span class="py-src-parameter">twcgi</span>.<span class="py-src-parameter">FilteredScript</span>):
805 <span class="py-src-variable">filter</span> = <span class="py-src-string">'/usr/bin/perl'</span> <span class="py-src-comment"># Points to the perl parser</span>
807 <span class="py-src-variable">resource</span> = <span class="py-src-variable">static</span>.<span class="py-src-variable">File</span>(<span class="py-src-string">"/perlsite"</span>) <span class="py-src-comment"># Points to the perl website</span>
808 <span class="py-src-variable">resource</span>.<span class="py-src-variable">processors</span> = {<span class="py-src-string">".pl"</span>: <span class="py-src-variable">PerlScript</span>} <span class="py-src-comment"># Files that end with .pl will be</span>
809 <span class="py-src-comment"># processed by PerlScript</span>
810 <span class="py-src-variable">resource</span>.<span class="py-src-variable">indexNames</span> = [<span class="py-src-string">'index.pl'</span>]
813 <h3>Serving WSGI Applications<a name="auto20"/></h3>
815 <p><a href="http://wsgi.org/wsgi" shape="rect">WSGI</a> is the Web Server Gateway
816 Interface. It is a specification for web servers and application servers to
817 communicate with Python web applications. All modern Python web frameworks
818 support the WSGI interface.</p>
820 <p>The easiest way to get started with WSGI application is to use the twistd
823 <pre class="shell" xml:space="preserve">
824 % twistd -n web --wsgi=helloworld.application
827 <p>This assumes that you have a WSGI application called application in
828 your helloworld module/package, which might look like this:</p>
830 <pre class="python"><p class="py-linenumber">1
834 </p><span class="py-src-keyword">def</span> <span class="py-src-identifier">application</span>(<span class="py-src-parameter">environ</span>, <span class="py-src-parameter">start_response</span>):
835 <span class="py-src-string">"""Basic WSGI Application"""</span>
836 <span class="py-src-variable">start_response</span>(<span class="py-src-string">'200 OK'</span>, [(<span class="py-src-string">'Content-type'</span>,<span class="py-src-string">'text/plain'</span>)])
837 <span class="py-src-keyword">return</span> [<span class="py-src-string">'Hello World!'</span>]
840 <p>The above setup will be suitable for many applications where all that is
841 needed is to server the WSGI application at the site's root. However, for
842 greater control, Twisted provides support for using WSGI applications as
843 resources <code class="api">twisted.web.wsgi.WSGIResource</code>.</p>
845 <p>Here is an example of a WSGI application being served as the root resource
846 for a site, in the following tac file:</p>
848 <pre class="python"><p class="py-linenumber"> 1
873 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">server</span>
874 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span>.<span class="py-src-variable">wsgi</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">WSGIResource</span>
875 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">python</span>.<span class="py-src-variable">threadpool</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">ThreadPool</span>
876 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">internet</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">reactor</span>
877 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">application</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">service</span>, <span class="py-src-variable">strports</span>
879 <span class="py-src-comment"># Create and start a thread pool,</span>
880 <span class="py-src-variable">wsgiThreadPool</span> = <span class="py-src-variable">ThreadPool</span>()
881 <span class="py-src-variable">wsgiThreadPool</span>.<span class="py-src-variable">start</span>()
883 <span class="py-src-comment"># ensuring that it will be stopped when the reactor shuts down</span>
884 <span class="py-src-variable">reactor</span>.<span class="py-src-variable">addSystemEventTrigger</span>(<span class="py-src-string">'after'</span>, <span class="py-src-string">'shutdown'</span>, <span class="py-src-variable">wsgiThreadPool</span>.<span class="py-src-variable">stop</span>)
886 <span class="py-src-keyword">def</span> <span class="py-src-identifier">application</span>(<span class="py-src-parameter">environ</span>, <span class="py-src-parameter">start_response</span>):
887 <span class="py-src-string">"""A basic WSGI application"""</span>
888 <span class="py-src-variable">start_response</span>(<span class="py-src-string">'200 OK'</span>, [(<span class="py-src-string">'Content-type'</span>,<span class="py-src-string">'text/plain'</span>)])
889 <span class="py-src-keyword">return</span> [<span class="py-src-string">'Hello World!'</span>]
891 <span class="py-src-comment"># Create the WSGI resource</span>
892 <span class="py-src-variable">wsgiAppAsResource</span> = <span class="py-src-variable">WSGIResource</span>(<span class="py-src-variable">reactor</span>, <span class="py-src-variable">wsgiThreadPool</span>, <span class="py-src-variable">application</span>)
894 <span class="py-src-comment"># Hooks for twistd</span>
895 <span class="py-src-variable">application</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">Application</span>(<span class="py-src-string">'Twisted.web.wsgi Hello World Example'</span>)
896 <span class="py-src-variable">server</span> = <span class="py-src-variable">strports</span>.<span class="py-src-variable">service</span>(<span class="py-src-string">'tcp:8080'</span>, <span class="py-src-variable">server</span>.<span class="py-src-variable">Site</span>(<span class="py-src-variable">wsgiAppAsResource</span>))
897 <span class="py-src-variable">server</span>.<span class="py-src-variable">setServiceParent</span>(<span class="py-src-variable">application</span>)
900 <p>This can then be run like any other .tac file:</p>
902 <pre class="shell" xml:space="preserve">
903 % twistd -ny myapp.tac
906 <p>Because of the synchronous nature of WSGI, each application call (for
907 each request) is called within a thread, and the result is written back to the
908 web server. For this, a <code class="api">twisted.python.threadpool.ThreadPool</code>
909 instance is used.</p>
911 <h3>Using VHostMonster<a name="auto21"/></h3>
913 <p>It is common to use one server (for example, Apache) on a site with multiple
914 names which then uses reverse proxy (in Apache, via <code>mod_proxy</code>) to different
915 internal web servers, possibly on different machines. However, naive
916 configuration causes miscommunication: the internal server firmly believes it
917 is running on <q>internal-name:port</q>, and will generate URLs to that effect,
918 which will be completely wrong when received by the client.</p>
920 <p>While Apache has the ProxyPassReverse directive, it is really a hack
921 and is nowhere near comprehensive enough. Instead, the recommended practice
922 in case the internal web server is Twisted Web is to use VHostMonster.</p>
924 <p>From the Twisted side, using VHostMonster is easy: just drop a file named
925 (for example) <code>vhost.rpy</code> containing the following:</p>
927 <pre class="python"><p class="py-linenumber">1
929 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">vhost</span>
930 <span class="py-src-variable">resource</span> = <span class="py-src-variable">vhost</span>.<span class="py-src-variable">VHostMonsterResource</span>()
933 <p>Make sure the web server is configured with the correct processors
934 for the <code>rpy</code> extensions (the web server <code>twistd web
935 --path</code> generates by default is so configured).</p>
937 <p>From the Apache side, instead of using the following ProxyPass directive:</p>
939 <pre xml:space="preserve">
940 <VirtualHost ip-addr>
941 ProxyPass / http://localhost:8538/
942 ServerName example.com
946 <p>Use the following directive:</p>
948 <pre xml:space="preserve">
949 <VirtualHost ip-addr>
950 ProxyPass / http://localhost:8538/vhost.rpy/http/example.com:80/
951 ServerName example.com
955 <p>Here is an example for Twisted Web's reverse proxy:</p>
957 <pre class="python"><p class="py-linenumber"> 1
969 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">application</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">internet</span>, <span class="py-src-variable">service</span>
970 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">proxy</span>, <span class="py-src-variable">server</span>, <span class="py-src-variable">vhost</span>
971 <span class="py-src-variable">vhostName</span> = <span class="py-src-string">'example.com'</span>
972 <span class="py-src-variable">reverseProxy</span> = <span class="py-src-variable">proxy</span>.<span class="py-src-variable">ReverseProxyResource</span>(<span class="py-src-string">'internal'</span>, <span class="py-src-number">8538</span>,
973 <span class="py-src-string">'/vhost.rpy/http/'</span>+<span class="py-src-variable">vhostName</span>+<span class="py-src-string">'/'</span>)
974 <span class="py-src-variable">root</span> = <span class="py-src-variable">vhost</span>.<span class="py-src-variable">NameVirtualHost</span>()
975 <span class="py-src-variable">root</span>.<span class="py-src-variable">addHost</span>(<span class="py-src-variable">vhostName</span>, <span class="py-src-variable">reverseProxy</span>)
976 <span class="py-src-variable">site</span> = <span class="py-src-variable">server</span>.<span class="py-src-variable">Site</span>(<span class="py-src-variable">root</span>)
977 <span class="py-src-variable">application</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">Application</span>(<span class="py-src-string">'web-proxy'</span>)
978 <span class="py-src-variable">sc</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">IServiceCollection</span>(<span class="py-src-variable">application</span>)
979 <span class="py-src-variable">i</span> = <span class="py-src-variable">internet</span>.<span class="py-src-variable">TCPServer</span>(<span class="py-src-number">80</span>, <span class="py-src-variable">site</span>)
980 <span class="py-src-variable">i</span>.<span class="py-src-variable">setServiceParent</span>(<span class="py-src-variable">sc</span>)
983 <h2>Rewriting URLs<a name="auto22"/></h2>
985 <p>Sometimes it is convenient to modify the content of
986 the <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.server.Request.html" title="twisted.web.server.Request">Request</a></code> object
987 before passing it on. Because this is most often used to rewrite
988 either the URL, the similarity to Apache's <code>mod_rewrite</code>
989 has inspired the <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.rewrite.html" title="twisted.web.rewrite">twisted.web.rewrite</a></code>
990 module. Using this module is done via wrapping a resource with
991 a <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.rewrite.RewriterResource.html" title="twisted.web.rewrite.RewriterResource">twisted.web.rewrite.RewriterResource</a></code> which
992 then has rewrite rules. Rewrite rules are functions which accept a
993 request object, and possible modify it. After all rewrite rules run,
994 the child resolution chain continues as if the wrapped resource,
995 rather than the <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.rewrite.RewriterResource.html" title="twisted.web.rewrite.RewriterResource">RewriterResource</a></code>, was the child.</p>
997 <p>Here is an example, using the only rule currently supplied by Twisted
1000 <pre class="python"><p class="py-linenumber">1
1001 </p><span class="py-src-variable">default_root</span> = <span class="py-src-variable">rewrite</span>.<span class="py-src-variable">RewriterResource</span>(<span class="py-src-variable">default</span>, <span class="py-src-variable">rewrite</span>.<span class="py-src-variable">tildeToUsers</span>)
1004 <p>This causes the URL <code>/~foo/bar.html</code> to be treated
1005 like <code>/users/foo/bar.html</code>. If done after setting
1006 default's <code>users</code> child to a <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.distrib.UserDirectory.html" title="twisted.web.distrib.UserDirectory">distrib.UserDirectory</a></code>, it gives a
1007 configuration similar to the classical configuration of web server,
1008 common since the first NCSA servers.</p>
1010 <h2>Knowing When We're Not Wanted<a name="auto23"/></h2>
1012 <p>Sometimes it is useful to know when the other side has broken the connection.
1013 Here is an example which does that:</p>
1015 <pre class="python"><p class="py-linenumber"> 1
1032 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span>.<span class="py-src-variable">resource</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">Resource</span>
1033 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">server</span>
1034 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">internet</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">reactor</span>
1035 <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">python</span>.<span class="py-src-variable">util</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">println</span>
1038 <span class="py-src-keyword">class</span> <span class="py-src-identifier">ExampleResource</span>(<span class="py-src-parameter">Resource</span>):
1040 <span class="py-src-keyword">def</span> <span class="py-src-identifier">render_GET</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">request</span>):
1041 <span class="py-src-variable">request</span>.<span class="py-src-variable">write</span>(<span class="py-src-string">"hello world"</span>)
1042 <span class="py-src-variable">d</span> = <span class="py-src-variable">request</span>.<span class="py-src-variable">notifyFinish</span>()
1043 <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-keyword">lambda</span> <span class="py-src-variable">_</span>: <span class="py-src-variable">println</span>(<span class="py-src-string">"finished normally"</span>))
1044 <span class="py-src-variable">d</span>.<span class="py-src-variable">addErrback</span>(<span class="py-src-variable">println</span>, <span class="py-src-string">"error"</span>)
1045 <span class="py-src-variable">reactor</span>.<span class="py-src-variable">callLater</span>(<span class="py-src-number">10</span>, <span class="py-src-variable">request</span>.<span class="py-src-variable">finish</span>)
1046 <span class="py-src-keyword">return</span> <span class="py-src-variable">server</span>.<span class="py-src-variable">NOT_DONE_YET</span>
1048 <span class="py-src-variable">resource</span> = <span class="py-src-variable">ExampleResource</span>()
1051 <p>This will allow us to run statistics on the log-file to see how many users
1052 are frustrated after merely 10 seconds.</p>
1054 <h2>As-Is Serving<a name="auto24"/></h2>
1056 <p>Sometimes, you want to be able to send headers and status
1057 directly. While you can do this with a <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.script.ResourceScript.html" title="twisted.web.script.ResourceScript">ResourceScript</a></code>, an easier way is to
1058 use <code class="API"><a href="http://twistedmatrix.com/documents/12.1.0/api/twisted.web.static.ASISProcessor.html" title="twisted.web.static.ASISProcessor">ASISProcessor</a></code>.
1059 Use it by, for example, adding it as a processor for
1060 the <code>.asis</code> extension. Here is a sample file:</p>
1062 <pre xml:space="preserve">
1064 Content-Type: text/html
1071 <p><a href="index.html">Index</a></p>
1072 <span class="version">Version: 12.1.0</span>