/usr/share/doc/python-webob-doc/do-it-yourself.html is in python-webob-doc 1.3.1-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Another Do-It-Yourself Framework — WebOb 1.2.3 documentation</title>
<link rel="stylesheet" href="_static/default.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1.2.3',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<link rel="top" title="WebOb 1.2.3 documentation" href="index.html" />
<link rel="next" title="News" href="news.html" />
<link rel="prev" title="JSON-RPC Example" href="jsonrpc-example.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="news.html" title="News"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="jsonrpc-example.html" title="JSON-RPC Example"
accesskey="P">previous</a> |</li>
<li><a href="index.html">WebOb 1.2.3 documentation</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="another-do-it-yourself-framework">
<h1><a class="toc-backref" href="#id1">Another Do-It-Yourself Framework</a></h1>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#another-do-it-yourself-framework" id="id1">Another Do-It-Yourself Framework</a><ul>
<li><a class="reference internal" href="#introduction-and-audience" id="id2">Introduction and Audience</a></li>
<li><a class="reference internal" href="#what-is-wsgi" id="id3">What Is WSGI?</a></li>
<li><a class="reference internal" href="#about-webob" id="id4">About WebOb</a></li>
<li><a class="reference internal" href="#serving-your-application" id="id5">Serving Your Application</a></li>
<li><a class="reference internal" href="#making-a-framework" id="id6">Making A Framework</a></li>
<li><a class="reference internal" href="#routing" id="id7">Routing</a><ul>
<li><a class="reference internal" href="#routing-templates" id="id8">Routing: Templates</a></li>
<li><a class="reference internal" href="#routing-controller-loading" id="id9">Routing: controller loading</a></li>
<li><a class="reference internal" href="#routing-putting-it-together" id="id10">Routing: putting it together</a></li>
</ul>
</li>
<li><a class="reference internal" href="#controllers" id="id11">Controllers</a></li>
<li><a class="reference internal" href="#putting-it-together" id="id12">Putting It Together</a></li>
<li><a class="reference internal" href="#another-controller" id="id13">Another Controller</a></li>
<li><a class="reference internal" href="#url-generation-and-request-access" id="id14">URL Generation and Request Access</a></li>
<li><a class="reference internal" href="#templating" id="id15">Templating</a></li>
<li><a class="reference internal" href="#conclusion" id="id16">Conclusion</a></li>
</ul>
</li>
</ul>
</div>
<div class="section" id="introduction-and-audience">
<h2><a class="toc-backref" href="#id2">Introduction and Audience</a></h2>
<p>It’s been over two years since I wrote the <a class="reference external" href="http://pythonpaste.org/do-it-yourself-framework.html">first version of this tutorial</a>. I decided to give it another run with some of the tools that have come about since then (particularly <a class="reference external" href="http://webob.org/">WebOb</a>).</p>
<p>Sometimes Python is accused of having too many web frameworks. And it’s true, there are a lot. That said, I think writing a framework is a useful exercise. It doesn’t let you skip over too much without understanding it. It removes the magic. So even if you go on to use another existing framework (which I’d probably advise you do), you’ll be able to understand it better if you’ve written something like it on your own.</p>
<p>This tutorial shows you how to create a web framework of your own, using WSGI and WebOb. No other libraries will be used.</p>
<p>For the longer sections I will try to explain any tricky parts on a line-by line basis following the example.</p>
</div>
<div class="section" id="what-is-wsgi">
<h2><a class="toc-backref" href="#id3">What Is WSGI?</a></h2>
<p>At its simplest WSGI is an interface between web servers and web applications. We’ll explain the mechanics of WSGI below, but a higher level view is to say that WSGI lets code pass around web requests in a fairly formal way. That’s the simplest summary, but there is more – WSGI lets you add annotation to the request, and adds some more metadata to the request.</p>
<p>WSGI more specifically is made up of an <em>application</em> and a <em>server</em>. The application is a function that receives the request and produces the response. The server is the thing that calls the application function.</p>
<p>A very simple application looks like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="k">def</span> <span class="nf">application</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">start_response</span><span class="p">(</span><span class="s">'200 OK'</span><span class="p">,</span> <span class="p">[(</span><span class="s">'Content-Type'</span><span class="p">,</span> <span class="s">'text/html'</span><span class="p">)])</span>
<span class="gp">... </span> <span class="k">return</span> <span class="p">[</span><span class="s">'Hello World!'</span><span class="p">]</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">environ</span></tt> argument is a dictionary with values like the environment in a CGI request. The header <tt class="docutils literal"><span class="pre">Host:</span></tt>, for instance, goes in <tt class="docutils literal"><span class="pre">environ['HTTP_HOST']</span></tt>. The path is in <tt class="docutils literal"><span class="pre">environ['SCRIPT_NAME']</span></tt> (which is the path leading <em>up to</em> the application), and <tt class="docutils literal"><span class="pre">environ['PATH_INFO']</span></tt> (the remaining path that the application should interpret).</p>
<p>We won’t focus much on the server, but we will use WebOb to handle the application. WebOb in a way has a simple server interface. To use it you create a new request with <tt class="docutils literal"><span class="pre">req</span> <span class="pre">=</span> <span class="pre">webob.Request.blank('http://localhost/test')</span></tt>, and then call the application with <tt class="docutils literal"><span class="pre">resp</span> <span class="pre">=</span> <span class="pre">req.get_response(app)</span></tt>. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">webob</span> <span class="kn">import</span> <span class="n">Request</span>
<span class="gp">>>> </span><span class="n">req</span> <span class="o">=</span> <span class="n">Request</span><span class="o">.</span><span class="n">blank</span><span class="p">(</span><span class="s">'http://localhost/test'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">resp</span> <span class="o">=</span> <span class="n">req</span><span class="o">.</span><span class="n">get_response</span><span class="p">(</span><span class="n">application</span><span class="p">)</span>
<span class="gp">>>> </span><span class="k">print</span> <span class="n">resp</span>
<span class="go">200 OK</span>
<span class="go">Content-Type: text/html</span>
<span class="go">Hello World!</span>
</pre></div>
</div>
<p>This is an easy way to test applications, and we’ll use it to test the framework we’re creating.</p>
</div>
<div class="section" id="about-webob">
<h2><a class="toc-backref" href="#id4">About WebOb</a></h2>
<p>WebOb is a library to create a request and response object. It’s centered around the WSGI model. Requests are wrappers around the environment. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">req</span> <span class="o">=</span> <span class="n">Request</span><span class="o">.</span><span class="n">blank</span><span class="p">(</span><span class="s">'http://localhost/test'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">req</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s">'HTTP_HOST'</span><span class="p">]</span>
<span class="go">'localhost:80'</span>
<span class="gp">>>> </span><span class="n">req</span><span class="o">.</span><span class="n">host</span>
<span class="go">'localhost:80'</span>
<span class="gp">>>> </span><span class="n">req</span><span class="o">.</span><span class="n">path_info</span>
<span class="go">'/test'</span>
</pre></div>
</div>
<p>Responses are objects that represent the... well, response. The status, headers, and body:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">webob</span> <span class="kn">import</span> <span class="n">Response</span>
<span class="gp">>>> </span><span class="n">resp</span> <span class="o">=</span> <span class="n">Response</span><span class="p">(</span><span class="n">body</span><span class="o">=</span><span class="s">'Hello World!'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">resp</span><span class="o">.</span><span class="n">content_type</span>
<span class="go">'text/html'</span>
<span class="gp">>>> </span><span class="n">resp</span><span class="o">.</span><span class="n">content_type</span> <span class="o">=</span> <span class="s">'text/plain'</span>
<span class="gp">>>> </span><span class="k">print</span> <span class="n">resp</span>
<span class="go">200 OK</span>
<span class="go">Content-Length: 12</span>
<span class="go">Content-Type: text/plain; charset=UTF-8</span>
<span class="go">Hello World!</span>
</pre></div>
</div>
<p>Responses also happen to be WSGI applications. That means you can call <tt class="docutils literal"><span class="pre">resp(environ,</span> <span class="pre">start_response)</span></tt>. Of course it’s much less <em>dynamic</em> than a normal WSGI application.</p>
<p>These two pieces solve a lot of the more tedious parts of making a framework. They deal with parsing most HTTP headers, generating valid responses, and a number of unicode issues.</p>
</div>
<div class="section" id="serving-your-application">
<h2><a class="toc-backref" href="#id5">Serving Your Application</a></h2>
<p>While we can test the application using WebOb, you might want to serve the application. Here’s the basic recipe, using the <a class="reference external" href="http://pythonpaste.org">Paste</a> HTTP server:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">'__main__'</span><span class="p">:</span>
<span class="kn">from</span> <span class="nn">paste</span> <span class="kn">import</span> <span class="n">httpserver</span>
<span class="n">httpserver</span><span class="o">.</span><span class="n">serve</span><span class="p">(</span><span class="n">app</span><span class="p">,</span> <span class="n">host</span><span class="o">=</span><span class="s">'127.0.0.1'</span><span class="p">,</span> <span class="n">port</span><span class="o">=</span><span class="mi">8080</span><span class="p">)</span>
</pre></div>
</div>
<p>you could also use <a class="reference external" href="http://python.org/doc/current/lib/module-wsgiref.simpleserver.html">wsgiref</a> from the standard library, but this is mostly appropriate for testing as it is single-threaded:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">'__main__'</span><span class="p">:</span>
<span class="kn">from</span> <span class="nn">wsgiref.simple_server</span> <span class="kn">import</span> <span class="n">make_server</span>
<span class="n">server</span> <span class="o">=</span> <span class="n">make_server</span><span class="p">(</span><span class="s">'127.0.0.1'</span><span class="p">,</span> <span class="mi">8080</span><span class="p">,</span> <span class="n">app</span><span class="p">)</span>
<span class="n">server</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="making-a-framework">
<h2><a class="toc-backref" href="#id6">Making A Framework</a></h2>
<p>Well, now we need to start work on our framework.</p>
<p>Here’s the basic model we’ll be creating:</p>
<ul class="simple">
<li>We’ll define routes that point to controllers</li>
<li>We’ll create a simple framework for creating controllers</li>
</ul>
</div>
<div class="section" id="routing">
<h2><a class="toc-backref" href="#id7">Routing</a></h2>
<p>We’ll use explicit routes using URI templates (minus the domains) to match paths. We’ll add a little extension that you can use <tt class="docutils literal"><span class="pre">{name:regular</span> <span class="pre">expression}</span></tt>, where the named segment must then match that regular expression. The matches will include a “controller” variable, which will be a string like “module_name:function_name”. For our examples we’ll use a simple blog.</p>
<p>So here’s what a route would look like:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">app</span> <span class="o">=</span> <span class="n">Router</span><span class="p">()</span>
<span class="n">app</span><span class="o">.</span><span class="n">add_route</span><span class="p">(</span><span class="s">'/'</span><span class="p">,</span> <span class="n">controller</span><span class="o">=</span><span class="s">'controllers:index'</span><span class="p">)</span>
<span class="n">app</span><span class="o">.</span><span class="n">add_route</span><span class="p">(</span><span class="s">'/{year:\d\d\d\d}/'</span><span class="p">,</span>
<span class="n">controller</span><span class="o">=</span><span class="s">'controllers:archive'</span><span class="p">)</span>
<span class="n">app</span><span class="o">.</span><span class="n">add_route</span><span class="p">(</span><span class="s">'/{year:\d\d\d\d}/{month:\d\d}/'</span><span class="p">,</span>
<span class="n">controller</span><span class="o">=</span><span class="s">'controllers:archive'</span><span class="p">)</span>
<span class="n">app</span><span class="o">.</span><span class="n">add_route</span><span class="p">(</span><span class="s">'/{year:\d\d\d\d}/{month:\d\d}/{slug}'</span><span class="p">,</span>
<span class="n">controller</span><span class="o">=</span><span class="s">'controllers:view'</span><span class="p">)</span>
<span class="n">app</span><span class="o">.</span><span class="n">add_route</span><span class="p">(</span><span class="s">'/post'</span><span class="p">,</span> <span class="n">controller</span><span class="o">=</span><span class="s">'controllers:post'</span><span class="p">)</span>
</pre></div>
</div>
<p>To do this we’ll need a couple pieces:</p>
<ul class="simple">
<li>Something to match those URI template things.</li>
<li>Something to load the controller</li>
<li>The object to patch them together (<tt class="docutils literal"><span class="pre">Router</span></tt>)</li>
</ul>
<div class="section" id="routing-templates">
<h3><a class="toc-backref" href="#id8">Routing: Templates</a></h3>
<p>To do the matching, we’ll compile those templates to regular expressions.</p>
<div class="highlight-python"><table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20</pre></div></td><td class="code"><div class="highlight"><pre> <span class="o">>>></span> <span class="kn">import</span> <span class="nn">re</span>
<span class="o">>>></span> <span class="n">var_regex</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s">r'''</span>
<span class="s"> ... \{ # The exact character "{"</span>
<span class="s"> ... (\w+) # The variable name (restricted to a-z, 0-9, _)</span>
<span class="s"> ... (?::([^}]+))? # The optional :regex part</span>
<span class="s"> ... \} # The exact character "}"</span>
<span class="s"> ... '''</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">VERBOSE</span><span class="p">)</span>
<span class="o">>>></span> <span class="k">def</span> <span class="nf">template_to_regex</span><span class="p">(</span><span class="n">template</span><span class="p">):</span>
<span class="o">...</span> <span class="n">regex</span> <span class="o">=</span> <span class="s">''</span>
<span class="o">...</span> <span class="n">last_pos</span> <span class="o">=</span> <span class="mi">0</span>
<span class="o">...</span> <span class="k">for</span> <span class="n">match</span> <span class="ow">in</span> <span class="n">var_regex</span><span class="o">.</span><span class="n">finditer</span><span class="p">(</span><span class="n">template</span><span class="p">):</span>
<span class="o">...</span> <span class="n">regex</span> <span class="o">+=</span> <span class="n">re</span><span class="o">.</span><span class="n">escape</span><span class="p">(</span><span class="n">template</span><span class="p">[</span><span class="n">last_pos</span><span class="p">:</span><span class="n">match</span><span class="o">.</span><span class="n">start</span><span class="p">()])</span>
<span class="o">...</span> <span class="n">var_name</span> <span class="o">=</span> <span class="n">match</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="o">...</span> <span class="n">expr</span> <span class="o">=</span> <span class="n">match</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="ow">or</span> <span class="s">'[^/]+'</span>
<span class="o">...</span> <span class="n">expr</span> <span class="o">=</span> <span class="s">'(?P<</span><span class="si">%s</span><span class="s">></span><span class="si">%s</span><span class="s">)'</span> <span class="o">%</span> <span class="p">(</span><span class="n">var_name</span><span class="p">,</span> <span class="n">expr</span><span class="p">)</span>
<span class="o">...</span> <span class="n">regex</span> <span class="o">+=</span> <span class="n">expr</span>
<span class="o">...</span> <span class="n">last_pos</span> <span class="o">=</span> <span class="n">match</span><span class="o">.</span><span class="n">end</span><span class="p">()</span>
<span class="o">...</span> <span class="n">regex</span> <span class="o">+=</span> <span class="n">re</span><span class="o">.</span><span class="n">escape</span><span class="p">(</span><span class="n">template</span><span class="p">[</span><span class="n">last_pos</span><span class="p">:])</span>
<span class="o">...</span> <span class="n">regex</span> <span class="o">=</span> <span class="s">'^</span><span class="si">%s</span><span class="s">$'</span> <span class="o">%</span> <span class="n">regex</span>
<span class="o">...</span> <span class="k">return</span> <span class="n">regex</span>
</pre></div>
</td></tr></table></div>
<p><strong>line 2:</strong> Here we create the regular expression. The <tt class="docutils literal"><span class="pre">re.VERBOSE</span></tt> flag makes the regular expression parser ignore whitespace and allow comments, so we can avoid some of the feel of line-noise. This matches any variables, i.e., <tt class="docutils literal"><span class="pre">{var:regex}</span></tt> (where <tt class="docutils literal"><span class="pre">:regex</span></tt> is optional). Note that there are two groups we capture: <tt class="docutils literal"><span class="pre">match.group(1)</span></tt> will be the variable name, and <tt class="docutils literal"><span class="pre">match.group(2)</span></tt> will be the regular expression (or None when there is no regular expression). Note that <tt class="docutils literal"><span class="pre">(?:...)?</span></tt> means that the section is optional.</p>
<p><strong>line 10</strong>: This variable will hold the regular expression that we are creating.</p>
<p><strong>line 11</strong>: This contains the position of the end of the last match.</p>
<p><strong>line 12</strong>: The <tt class="docutils literal"><span class="pre">finditer</span></tt> method yields all the matches.</p>
<p><strong>line 13</strong>: We’re getting all the non-<tt class="docutils literal"><span class="pre">{}</span></tt> text from after the last match, up to the beginning of this match. We call <tt class="docutils literal"><span class="pre">re.escape</span></tt> on that text, which escapes any characters that have special meaning. So <tt class="docutils literal"><span class="pre">.html</span></tt> will be escaped as <tt class="docutils literal"><span class="pre">\.html</span></tt>.</p>
<p><strong>line 14</strong>: The first match is the variable name.</p>
<p><strong>line 15</strong>: <tt class="docutils literal"><span class="pre">expr</span></tt> is the regular expression we’ll match against, the optional second match. The default is <tt class="docutils literal"><span class="pre">[^/]+</span></tt>, which matches any non-empty, non-/ string. Which seems like a reasonable default to me.</p>
<p><strong>line 16</strong>: Here we create the actual regular expression. <tt class="docutils literal"><span class="pre">(?P<name>...)</span></tt> is a grouped expression that is named. When you get a match, you can look at <tt class="docutils literal"><span class="pre">match.groupdict()</span></tt> and get the names and values.</p>
<p><strong>line 17, 18</strong>: We add the expression on to the complete regular expression and save the last position.</p>
<p><strong>line 19</strong>: We add remaining non-variable text to the regular expression.</p>
<p><strong>line 20</strong>: And then we make the regular expression match the complete string (<tt class="docutils literal"><span class="pre">^</span></tt> to force it to match from the start, <tt class="docutils literal"><span class="pre">$</span></tt> to make sure it matches up to the end).</p>
<p>To test it we can try some translations. You could put these directly in the docstring of the <tt class="docutils literal"><span class="pre">template_to_regex</span></tt> function and use <a class="reference external" href="http://python.org/doc/current/lib/module-doctest.html">doctest</a> to test that. But I’m using doctest to test <em>this</em> document, so I can’t put a docstring doctest inside the doctest itself. Anyway, here’s what a test looks like:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="k">print</span> <span class="n">template_to_regex</span><span class="p">(</span><span class="s">'/a/static/path'</span><span class="p">)</span>
<span class="go">^\/a\/static\/path$</span>
<span class="gp">>>> </span><span class="k">print</span> <span class="n">template_to_regex</span><span class="p">(</span><span class="s">'/{year:\d\d\d\d}/{month:\d\d}/{slug}'</span><span class="p">)</span>
<span class="go">^\/(?P<year>\d\d\d\d)\/(?P<month>\d\d)\/(?P<slug>[^/]+)$</span>
</pre></div>
</div>
</div>
<div class="section" id="routing-controller-loading">
<h3><a class="toc-backref" href="#id9">Routing: controller loading</a></h3>
<p>To load controllers we have to import the module, then get the function out of it. We’ll use the <tt class="docutils literal"><span class="pre">__import__</span></tt> builtin to import the module. The return value of <tt class="docutils literal"><span class="pre">__import__</span></tt> isn’t very useful, but it puts the module into <tt class="docutils literal"><span class="pre">sys.modules</span></tt>, a dictionary of all the loaded modules.</p>
<p>Also, some people don’t know how exactly the string method <tt class="docutils literal"><span class="pre">split</span></tt> works. It takes two arguments – the first is the character to split on, and the second is the maximum number of splits to do. We want to split on just the first <tt class="docutils literal"><span class="pre">:</span></tt> character, so we’ll use a maximum number of splits of 1.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">sys</span>
<span class="gp">>>> </span><span class="k">def</span> <span class="nf">load_controller</span><span class="p">(</span><span class="n">string</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">module_name</span><span class="p">,</span> <span class="n">func_name</span> <span class="o">=</span> <span class="n">string</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">':'</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="gp">... </span> <span class="nb">__import__</span><span class="p">(</span><span class="n">module_name</span><span class="p">)</span>
<span class="gp">... </span> <span class="n">module</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">modules</span><span class="p">[</span><span class="n">module_name</span><span class="p">]</span>
<span class="gp">... </span> <span class="n">func</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">module</span><span class="p">,</span> <span class="n">func_name</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">return</span> <span class="n">func</span>
</pre></div>
</div>
</div>
<div class="section" id="routing-putting-it-together">
<h3><a class="toc-backref" href="#id10">Routing: putting it together</a></h3>
<p>Now, the <tt class="docutils literal"><span class="pre">Router</span></tt> class. The class has the <tt class="docutils literal"><span class="pre">add_route</span></tt> method, and also a <tt class="docutils literal"><span class="pre">__call__</span></tt> method. That <tt class="docutils literal"><span class="pre">__call__</span></tt> method makes the Router object itself a WSGI application. So when a request comes in, it looks at <tt class="docutils literal"><span class="pre">PATH_INFO</span></tt> (also known as <tt class="docutils literal"><span class="pre">req.path_info</span></tt>) and hands off the request to the controller that matches that path.</p>
<div class="highlight-python"><table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22</pre></div></td><td class="code"><div class="highlight"><pre> <span class="o">>>></span> <span class="kn">from</span> <span class="nn">webob</span> <span class="kn">import</span> <span class="n">Request</span>
<span class="o">>>></span> <span class="kn">from</span> <span class="nn">webob</span> <span class="kn">import</span> <span class="n">exc</span>
<span class="o">>>></span> <span class="k">class</span> <span class="nc">Router</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="o">...</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="o">...</span> <span class="bp">self</span><span class="o">.</span><span class="n">routes</span> <span class="o">=</span> <span class="p">[]</span>
<span class="o">...</span>
<span class="o">...</span> <span class="k">def</span> <span class="nf">add_route</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">template</span><span class="p">,</span> <span class="n">controller</span><span class="p">,</span> <span class="o">**</span><span class="nb">vars</span><span class="p">):</span>
<span class="o">...</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">controller</span><span class="p">,</span> <span class="nb">basestring</span><span class="p">):</span>
<span class="o">...</span> <span class="n">controller</span> <span class="o">=</span> <span class="n">load_controller</span><span class="p">(</span><span class="n">controller</span><span class="p">)</span>
<span class="o">...</span> <span class="bp">self</span><span class="o">.</span><span class="n">routes</span><span class="o">.</span><span class="n">append</span><span class="p">((</span><span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="n">template_to_regex</span><span class="p">(</span><span class="n">template</span><span class="p">)),</span>
<span class="o">...</span> <span class="n">controller</span><span class="p">,</span>
<span class="o">...</span> <span class="nb">vars</span><span class="p">))</span>
<span class="o">...</span>
<span class="o">...</span> <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
<span class="o">...</span> <span class="n">req</span> <span class="o">=</span> <span class="n">Request</span><span class="p">(</span><span class="n">environ</span><span class="p">)</span>
<span class="o">...</span> <span class="k">for</span> <span class="n">regex</span><span class="p">,</span> <span class="n">controller</span><span class="p">,</span> <span class="nb">vars</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">routes</span><span class="p">:</span>
<span class="o">...</span> <span class="n">match</span> <span class="o">=</span> <span class="n">regex</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="n">req</span><span class="o">.</span><span class="n">path_info</span><span class="p">)</span>
<span class="o">...</span> <span class="k">if</span> <span class="n">match</span><span class="p">:</span>
<span class="o">...</span> <span class="n">req</span><span class="o">.</span><span class="n">urlvars</span> <span class="o">=</span> <span class="n">match</span><span class="o">.</span><span class="n">groupdict</span><span class="p">()</span>
<span class="o">...</span> <span class="n">req</span><span class="o">.</span><span class="n">urlvars</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="nb">vars</span><span class="p">)</span>
<span class="o">...</span> <span class="k">return</span> <span class="n">controller</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">)</span>
<span class="o">...</span> <span class="k">return</span> <span class="n">exc</span><span class="o">.</span><span class="n">HTTPNotFound</span><span class="p">()(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">)</span>
</pre></div>
</td></tr></table></div>
<p><strong>line 5</strong>: We are going to keep the route options in an ordered list. Each item will be <tt class="docutils literal"><span class="pre">(regex,</span> <span class="pre">controller,</span> <span class="pre">vars)</span></tt>: <tt class="docutils literal"><span class="pre">regex</span></tt> is the regular expression object to match against, <tt class="docutils literal"><span class="pre">controller</span></tt> is the controller to run, and <tt class="docutils literal"><span class="pre">vars</span></tt> are any extra (constant) variables.</p>
<p><strong>line 8, 9</strong>: We will allow you to call <tt class="docutils literal"><span class="pre">add_route</span></tt> with a string (that will be imported) or a controller object. We test for a string here, and then import it if necessary.</p>
<p><strong>line 13</strong>: Here we add a <tt class="docutils literal"><span class="pre">__call__</span></tt> method. This is the method used when you call an object like a function. You should recognize this as the WSGI signature.</p>
<p><strong>line 14</strong>: We create a request object. Note we’ll only use this request object in this function; if the controller wants a request object it’ll have to make on of its own.</p>
<p><strong>line 16</strong>: We test the regular expression against <tt class="docutils literal"><span class="pre">req.path_info</span></tt>. This is the same as <tt class="docutils literal"><span class="pre">environ['PATH_INFO']</span></tt>. That’s all the request path left to be processed.</p>
<p><strong>line 18</strong>: We set <tt class="docutils literal"><span class="pre">req.urlvars</span></tt> to the dictionary of matches in the regular expression. This variable actually maps to <tt class="docutils literal"><span class="pre">environ['wsgiorg.routing_args']</span></tt>. Any attributes you set on a request will, in one way or another, map to the environment dictionary: the request holds no state of its own.</p>
<p><strong>line 19</strong>: We also add in any explicit variables passed in through <tt class="docutils literal"><span class="pre">add_route()</span></tt>.</p>
<p><strong>line 20</strong>: Then we call the controller as a WSGI application itself. Any fancy framework stuff the controller wants to do, it’ll have to do itself.</p>
<p><strong>line 21</strong>: If nothing matches, we return a 404 Not Found response. <tt class="docutils literal"><span class="pre">webob.exc.HTTPNotFound()</span></tt> is a WSGI application that returns 404 responses. You could add a message too, like <tt class="docutils literal"><span class="pre">webob.exc.HTTPNotFound('No</span> <span class="pre">route</span> <span class="pre">matched')</span></tt>. Then, of course, we call the application.</p>
</div>
</div>
<div class="section" id="controllers">
<h2><a class="toc-backref" href="#id11">Controllers</a></h2>
<p>The router just passes the request on to the controller, so the controllers are themselves just WSGI applications. But we’ll want to set up something to make those applications friendlier to write.</p>
<p>To do that we’ll write a <a class="reference external" href="http://www.ddj.com/web-development/184406073">decorator</a>. A decorator is a function that wraps another function. After decoration the function will be a WSGI application, but it will be decorating a function with a signature like <tt class="docutils literal"><span class="pre">controller_func(req,</span> <span class="pre">**urlvars)</span></tt>. The controller function will return a response object (which, remember, is a WSGI application on its own).</p>
<div class="highlight-python"><table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10
11
12
13</pre></div></td><td class="code"><div class="highlight"><pre> <span class="o">>>></span> <span class="kn">from</span> <span class="nn">webob</span> <span class="kn">import</span> <span class="n">Request</span><span class="p">,</span> <span class="n">Response</span>
<span class="o">>>></span> <span class="kn">from</span> <span class="nn">webob</span> <span class="kn">import</span> <span class="n">exc</span>
<span class="o">>>></span> <span class="k">def</span> <span class="nf">controller</span><span class="p">(</span><span class="n">func</span><span class="p">):</span>
<span class="o">...</span> <span class="k">def</span> <span class="nf">replacement</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
<span class="o">...</span> <span class="n">req</span> <span class="o">=</span> <span class="n">Request</span><span class="p">(</span><span class="n">environ</span><span class="p">)</span>
<span class="o">...</span> <span class="k">try</span><span class="p">:</span>
<span class="o">...</span> <span class="n">resp</span> <span class="o">=</span> <span class="n">func</span><span class="p">(</span><span class="n">req</span><span class="p">,</span> <span class="o">**</span><span class="n">req</span><span class="o">.</span><span class="n">urlvars</span><span class="p">)</span>
<span class="o">...</span> <span class="k">except</span> <span class="n">exc</span><span class="o">.</span><span class="n">HTTPException</span><span class="p">,</span> <span class="n">e</span><span class="p">:</span>
<span class="o">...</span> <span class="n">resp</span> <span class="o">=</span> <span class="n">e</span>
<span class="o">...</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">resp</span><span class="p">,</span> <span class="nb">basestring</span><span class="p">):</span>
<span class="o">...</span> <span class="n">resp</span> <span class="o">=</span> <span class="n">Response</span><span class="p">(</span><span class="n">body</span><span class="o">=</span><span class="n">resp</span><span class="p">)</span>
<span class="o">...</span> <span class="k">return</span> <span class="n">resp</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">)</span>
<span class="o">...</span> <span class="k">return</span> <span class="n">replacement</span>
</pre></div>
</td></tr></table></div>
<p><strong>line 3</strong>: This is the typical signature for a decorator – it takes one function as an argument, and returns a wrapped function.</p>
<p><strong>line 4</strong>: This is the replacement function we’ll return. This is called a <a class="reference external" href="http://en.wikipedia.org/wiki/Closure_(computer_science)">closure</a> – this function will have access to <tt class="docutils literal"><span class="pre">func</span></tt>, and everytime you decorate a new function there will be a new <tt class="docutils literal"><span class="pre">replacement</span></tt> function with its own value of <tt class="docutils literal"><span class="pre">func</span></tt>. As you can see, this is a WSGI application.</p>
<p><strong>line 5</strong>: We create a request.</p>
<p><strong>line 6</strong>: Here we catch any <tt class="docutils literal"><span class="pre">webob.exc.HTTPException</span></tt> exceptions. This is so you can do <tt class="docutils literal"><span class="pre">raise</span> <span class="pre">webob.exc.HTTPNotFound()</span></tt> in your function. These exceptions are themselves WSGI applications.</p>
<p><strong>line 7</strong>: We call the function with the request object, any any variables in <tt class="docutils literal"><span class="pre">req.urlvars</span></tt>. And we get back a response.</p>
<p><strong>line 10</strong>: We’ll allow the function to return a full response object, or just a string. If they return a string, we’ll create a <tt class="docutils literal"><span class="pre">Response</span></tt> object with that (and with the standard <tt class="docutils literal"><span class="pre">200</span> <span class="pre">OK</span></tt> status, <tt class="docutils literal"><span class="pre">text/html</span></tt> content type, and <tt class="docutils literal"><span class="pre">utf8</span></tt> charset/encoding).</p>
<p><strong>line 12</strong>: We pass the request on to the response. Which <em>also</em> happens to be a WSGI application. WSGI applications are falling from the sky!</p>
<p><strong>line 13</strong>: We return the function object itself, which will take the place of the function.</p>
<p>You use this controller like:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="nd">@controller</span>
<span class="gp">... </span><span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="n">req</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">return</span> <span class="s">'This is the index'</span>
</pre></div>
</div>
</div>
<div class="section" id="putting-it-together">
<h2><a class="toc-backref" href="#id12">Putting It Together</a></h2>
<p>Now we’ll show a basic application. Just a hello world application for now. Note that this document is the module <tt class="docutils literal"><span class="pre">__main__</span></tt>.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="nd">@controller</span>
<span class="gp">... </span><span class="k">def</span> <span class="nf">hello</span><span class="p">(</span><span class="n">req</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">if</span> <span class="n">req</span><span class="o">.</span><span class="n">method</span> <span class="o">==</span> <span class="s">'POST'</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">return</span> <span class="s">'Hello </span><span class="si">%s</span><span class="s">!'</span> <span class="o">%</span> <span class="n">req</span><span class="o">.</span><span class="n">params</span><span class="p">[</span><span class="s">'name'</span><span class="p">]</span>
<span class="gp">... </span> <span class="k">elif</span> <span class="n">req</span><span class="o">.</span><span class="n">method</span> <span class="o">==</span> <span class="s">'GET'</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">return</span> <span class="s">'''<form method="POST"></span>
<span class="gp">... </span><span class="s"> You're name: <input type="text" name="name"></span>
<span class="gp">... </span><span class="s"> <input type="submit"></span>
<span class="gp">... </span><span class="s"> </form>'''</span>
<span class="gp">>>> </span><span class="n">hello_world</span> <span class="o">=</span> <span class="n">Router</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">hello_world</span><span class="o">.</span><span class="n">add_route</span><span class="p">(</span><span class="s">'/'</span><span class="p">,</span> <span class="n">controller</span><span class="o">=</span><span class="n">hello</span><span class="p">)</span>
</pre></div>
</div>
<p>Now let’s test that application:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">req</span> <span class="o">=</span> <span class="n">Request</span><span class="o">.</span><span class="n">blank</span><span class="p">(</span><span class="s">'/'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">resp</span> <span class="o">=</span> <span class="n">req</span><span class="o">.</span><span class="n">get_response</span><span class="p">(</span><span class="n">hello_world</span><span class="p">)</span>
<span class="gp">>>> </span><span class="k">print</span> <span class="n">resp</span>
<span class="go">200 OK</span>
<span class="go">Content-Type: text/html; charset=UTF-8</span>
<span class="go">Content-Length: 131</span>
<span class="go"><form method="POST"></span>
<span class="go"> You're name: <input type="text" name="name"></span>
<span class="go"> <input type="submit"></span>
<span class="go"> </form></span>
<span class="gp">>>> </span><span class="n">req</span><span class="o">.</span><span class="n">method</span> <span class="o">=</span> <span class="s">'POST'</span>
<span class="gp">>>> </span><span class="n">req</span><span class="o">.</span><span class="n">body</span> <span class="o">=</span> <span class="s">'name=Ian'</span>
<span class="gp">>>> </span><span class="n">resp</span> <span class="o">=</span> <span class="n">req</span><span class="o">.</span><span class="n">get_response</span><span class="p">(</span><span class="n">hello_world</span><span class="p">)</span>
<span class="gp">>>> </span><span class="k">print</span> <span class="n">resp</span>
<span class="go">200 OK</span>
<span class="go">Content-Type: text/html; charset=UTF-8</span>
<span class="go">Content-Length: 10</span>
<span class="go">Hello Ian!</span>
</pre></div>
</div>
</div>
<div class="section" id="another-controller">
<h2><a class="toc-backref" href="#id13">Another Controller</a></h2>
<p>There’s another pattern that might be interesting to try for a controller. Instead of a function, we can make a class with methods like <tt class="docutils literal"><span class="pre">get</span></tt>, <tt class="docutils literal"><span class="pre">post</span></tt>, etc. The <tt class="docutils literal"><span class="pre">urlvars</span></tt> will be used to instantiate the class.</p>
<p>We could do this as a superclass, but the implementation will be more elegant as a wrapper, like the decorator is a wrapper. Python 3.0 will add <a class="reference external" href="http://www.python.org/dev/peps/pep-3129/">class decorators</a> which will work like this.</p>
<p>We’ll allow an extra <tt class="docutils literal"><span class="pre">action</span></tt> variable, which will define the method (actually <tt class="docutils literal"><span class="pre">action_method</span></tt>, where <tt class="docutils literal"><span class="pre">_method</span></tt> is the request method). If no action is given, we’ll use just the method (i.e., <tt class="docutils literal"><span class="pre">get</span></tt>, <tt class="docutils literal"><span class="pre">post</span></tt>, etc).</p>
<div class="highlight-python"><table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21</pre></div></td><td class="code"><div class="highlight"><pre> <span class="o">>>></span> <span class="k">def</span> <span class="nf">rest_controller</span><span class="p">(</span><span class="n">cls</span><span class="p">):</span>
<span class="o">...</span> <span class="k">def</span> <span class="nf">replacement</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
<span class="o">...</span> <span class="n">req</span> <span class="o">=</span> <span class="n">Request</span><span class="p">(</span><span class="n">environ</span><span class="p">)</span>
<span class="o">...</span> <span class="k">try</span><span class="p">:</span>
<span class="o">...</span> <span class="n">instance</span> <span class="o">=</span> <span class="n">cls</span><span class="p">(</span><span class="n">req</span><span class="p">,</span> <span class="o">**</span><span class="n">req</span><span class="o">.</span><span class="n">urlvars</span><span class="p">)</span>
<span class="o">...</span> <span class="n">action</span> <span class="o">=</span> <span class="n">req</span><span class="o">.</span><span class="n">urlvars</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'action'</span><span class="p">)</span>
<span class="o">...</span> <span class="k">if</span> <span class="n">action</span><span class="p">:</span>
<span class="o">...</span> <span class="n">action</span> <span class="o">+=</span> <span class="s">'_'</span> <span class="o">+</span> <span class="n">req</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>
<span class="o">...</span> <span class="k">else</span><span class="p">:</span>
<span class="o">...</span> <span class="n">action</span> <span class="o">=</span> <span class="n">req</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>
<span class="o">...</span> <span class="k">try</span><span class="p">:</span>
<span class="o">...</span> <span class="n">method</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">instance</span><span class="p">,</span> <span class="n">action</span><span class="p">)</span>
<span class="o">...</span> <span class="k">except</span> <span class="ne">AttributeError</span><span class="p">:</span>
<span class="o">...</span> <span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">HTTPNotFound</span><span class="p">(</span><span class="s">"No action </span><span class="si">%s</span><span class="s">"</span> <span class="o">%</span> <span class="n">action</span><span class="p">)</span>
<span class="o">...</span> <span class="n">resp</span> <span class="o">=</span> <span class="n">method</span><span class="p">()</span>
<span class="o">...</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">resp</span><span class="p">,</span> <span class="nb">basestring</span><span class="p">):</span>
<span class="o">...</span> <span class="n">resp</span> <span class="o">=</span> <span class="n">Response</span><span class="p">(</span><span class="n">body</span><span class="o">=</span><span class="n">resp</span><span class="p">)</span>
<span class="o">...</span> <span class="k">except</span> <span class="n">exc</span><span class="o">.</span><span class="n">HTTPException</span><span class="p">,</span> <span class="n">e</span><span class="p">:</span>
<span class="o">...</span> <span class="n">resp</span> <span class="o">=</span> <span class="n">e</span>
<span class="o">...</span> <span class="k">return</span> <span class="n">resp</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">)</span>
<span class="o">...</span> <span class="k">return</span> <span class="n">replacement</span>
</pre></div>
</td></tr></table></div>
<p><strong>line 1</strong>: Here we’re kind of decorating a class. But really we’ll just create a WSGI application wrapper.</p>
<p><strong>line 2-4</strong>: The replacement WSGI application, also a closure. And we create a request and catch exceptions, just like in the decorator.</p>
<p><strong>line 5</strong>: We instantiate the class with both the request and <tt class="docutils literal"><span class="pre">req.urlvars</span></tt> to initialize it. The instance will only be used for one request. (Note that the <em>instance</em> then doesn’t have to be thread safe.)</p>
<p><strong>line 6</strong>: We get the action variable out, if there is one.</p>
<p><strong>line 7, 8</strong>: If there was one, we’ll use the method name <tt class="docutils literal"><span class="pre">{action}_{method}</span></tt>...</p>
<p><strong>line 8, 9</strong>: ... otherwise we’ll use just the method for the method name.</p>
<p><strong>line 10-13</strong>: We’ll get the method from the instance, or respond with a 404 error if there is not such method.</p>
<p><strong>line 14</strong>: Call the method, get the response</p>
<p><strong>line 15, 16</strong>: If the response is just a string, create a full response object from it.</p>
<p><strong>line 19</strong>: and then we forward the request...</p>
<p><strong>line 20</strong>: ... and return the wrapper object we’ve created.</p>
<p>Here’s the hello world:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="k">class</span> <span class="nc">Hello</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">req</span><span class="p">):</span>
<span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">request</span> <span class="o">=</span> <span class="n">req</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">get</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">return</span> <span class="s">'''<form method="POST"></span>
<span class="gp">... </span><span class="s"> You're name: <input type="text" name="name"></span>
<span class="gp">... </span><span class="s"> <input type="submit"></span>
<span class="gp">... </span><span class="s"> </form>'''</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">post</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">return</span> <span class="s">'Hello </span><span class="si">%s</span><span class="s">!'</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">params</span><span class="p">[</span><span class="s">'name'</span><span class="p">]</span>
<span class="gp">>>> </span><span class="n">hello</span> <span class="o">=</span> <span class="n">rest_controller</span><span class="p">(</span><span class="n">Hello</span><span class="p">)</span>
</pre></div>
</div>
<p>We’ll run the same test as before:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">hello_world</span> <span class="o">=</span> <span class="n">Router</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">hello_world</span><span class="o">.</span><span class="n">add_route</span><span class="p">(</span><span class="s">'/'</span><span class="p">,</span> <span class="n">controller</span><span class="o">=</span><span class="n">hello</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">req</span> <span class="o">=</span> <span class="n">Request</span><span class="o">.</span><span class="n">blank</span><span class="p">(</span><span class="s">'/'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">resp</span> <span class="o">=</span> <span class="n">req</span><span class="o">.</span><span class="n">get_response</span><span class="p">(</span><span class="n">hello_world</span><span class="p">)</span>
<span class="gp">>>> </span><span class="k">print</span> <span class="n">resp</span>
<span class="go">200 OK</span>
<span class="go">Content-Type: text/html; charset=UTF-8</span>
<span class="go">Content-Length: 131</span>
<span class="go"><form method="POST"></span>
<span class="go"> You're name: <input type="text" name="name"></span>
<span class="go"> <input type="submit"></span>
<span class="go"> </form></span>
<span class="gp">>>> </span><span class="n">req</span><span class="o">.</span><span class="n">method</span> <span class="o">=</span> <span class="s">'POST'</span>
<span class="gp">>>> </span><span class="n">req</span><span class="o">.</span><span class="n">body</span> <span class="o">=</span> <span class="s">'name=Ian'</span>
<span class="gp">>>> </span><span class="n">resp</span> <span class="o">=</span> <span class="n">req</span><span class="o">.</span><span class="n">get_response</span><span class="p">(</span><span class="n">hello_world</span><span class="p">)</span>
<span class="gp">>>> </span><span class="k">print</span> <span class="n">resp</span>
<span class="go">200 OK</span>
<span class="go">Content-Type: text/html; charset=UTF-8</span>
<span class="go">Content-Length: 10</span>
<span class="go">Hello Ian!</span>
</pre></div>
</div>
</div>
<div class="section" id="url-generation-and-request-access">
<h2><a class="toc-backref" href="#id14">URL Generation and Request Access</a></h2>
<p>You can use hard-coded links in your HTML, but this can have problems. Relative links are hard to manage, and absolute links presume that your application lives at a particular location. WSGI gives a variable <tt class="docutils literal"><span class="pre">SCRIPT_NAME</span></tt>, which is the portion of the path that led up to this application. If you are writing a blog application, for instance, someone might want to install it at <tt class="docutils literal"><span class="pre">/blog/</span></tt>, and then SCRIPT_NAME would be <tt class="docutils literal"><span class="pre">"/blog"</span></tt>. We should generate links with that in mind.</p>
<p>The base URL using SCRIPT_NAME is <tt class="docutils literal"><span class="pre">req.application_url</span></tt>. So, if we have access to the request we can make a URL. But what if we don’t have access?</p>
<p>We can use thread-local variables to make it easy for any function to get access to the currect request. A “thread-local” variable is a variable whose value is tracked separately for each thread, so if there are multiple requests in different threads, their requests won’t clobber each other.</p>
<p>The basic means of using a thread-local variable is <tt class="docutils literal"><span class="pre">threading.local()</span></tt>. This creates a blank object that can have thread-local attributes assigned to it. I find the best way to get <em>at</em> a thread-local value is with a function, as this makes it clear that you are fetching the object, as opposed to getting at some global object.</p>
<p>Here’s the basic structure for the local:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">threading</span>
<span class="gp">>>> </span><span class="k">class</span> <span class="nc">Localized</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">local</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">local</span><span class="p">()</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">register</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">local</span><span class="o">.</span><span class="n">object</span> <span class="o">=</span> <span class="nb">object</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">unregister</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">del</span> <span class="bp">self</span><span class="o">.</span><span class="n">local</span><span class="o">.</span><span class="n">object</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">local</span><span class="o">.</span><span class="n">object</span>
<span class="gp">... </span> <span class="k">except</span> <span class="ne">AttributeError</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s">"No object has been registered for this thread"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">get_request</span> <span class="o">=</span> <span class="n">Localized</span><span class="p">()</span>
</pre></div>
</div>
<p>Now we need some <em>middleware</em> to register the request object. Middleware is something that wraps an application, possibly modifying the request on the way in or the way out. In a sense the <tt class="docutils literal"><span class="pre">Router</span></tt> object was middleware, though not exactly because it didn’t wrap a single application.</p>
<p>This registration middleware looks like:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="k">class</span> <span class="nc">RegisterRequest</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">app</span><span class="p">):</span>
<span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">app</span> <span class="o">=</span> <span class="n">app</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">req</span> <span class="o">=</span> <span class="n">Request</span><span class="p">(</span><span class="n">environ</span><span class="p">)</span>
<span class="gp">... </span> <span class="n">get_request</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">app</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">get_request</span><span class="o">.</span><span class="n">unregister</span><span class="p">()</span>
</pre></div>
</div>
<p>Now if we do:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">hello_world</span> <span class="o">=</span> <span class="n">RegisterRequest</span><span class="p">(</span><span class="n">hello_world</span><span class="p">)</span>
</pre></div>
</div>
<p>then the request will be registered each time. Now, lets create a URL generation function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">urllib</span>
<span class="gp">>>> </span><span class="k">def</span> <span class="nf">url</span><span class="p">(</span><span class="o">*</span><span class="n">segments</span><span class="p">,</span> <span class="o">**</span><span class="nb">vars</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">base_url</span> <span class="o">=</span> <span class="n">get_request</span><span class="p">()</span><span class="o">.</span><span class="n">application_url</span>
<span class="gp">... </span> <span class="n">path</span> <span class="o">=</span> <span class="s">'/'</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">segments</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">if</span> <span class="ow">not</span> <span class="n">path</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s">'/'</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">path</span> <span class="o">=</span> <span class="s">'/'</span> <span class="o">+</span> <span class="n">path</span>
<span class="gp">... </span> <span class="k">if</span> <span class="nb">vars</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">path</span> <span class="o">+=</span> <span class="s">'?'</span> <span class="o">+</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlencode</span><span class="p">(</span><span class="nb">vars</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">return</span> <span class="n">base_url</span> <span class="o">+</span> <span class="n">path</span>
</pre></div>
</div>
<p>Now, to test:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">get_request</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">Request</span><span class="o">.</span><span class="n">blank</span><span class="p">(</span><span class="s">'http://localhost/'</span><span class="p">))</span>
<span class="gp">>>> </span><span class="n">url</span><span class="p">(</span><span class="s">'article'</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">'http://localhost/article/1'</span>
<span class="gp">>>> </span><span class="n">url</span><span class="p">(</span><span class="s">'search'</span><span class="p">,</span> <span class="n">q</span><span class="o">=</span><span class="s">'some query'</span><span class="p">)</span>
<span class="go">'http://localhost/search?q=some+query'</span>
</pre></div>
</div>
</div>
<div class="section" id="templating">
<h2><a class="toc-backref" href="#id15">Templating</a></h2>
<p>Well, we don’t <em>really</em> need to factor templating into our framework. After all, you return a string from your controller, and you can figure out on your own how to get a rendered string from a template.</p>
<p>But we’ll add a little helper, because I think it shows a clever trick.</p>
<p>We’ll use <a class="reference external" href="http://pythonpaste.org/tempita/">Tempita</a> for templating, mostly because it’s very simplistic about how it does loading. The basic form is:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">tempita</span>
<span class="n">template</span> <span class="o">=</span> <span class="n">tempita</span><span class="o">.</span><span class="n">HTMLTemplate</span><span class="o">.</span><span class="n">from_filename</span><span class="p">(</span><span class="s">'some-file.html'</span><span class="p">)</span>
</pre></div>
</div>
<p>But we’ll be implementing a function <tt class="docutils literal"><span class="pre">render(template_name,</span> <span class="pre">**vars)</span></tt> that will render the named template, treating it as a path <em>relative to the location of the render() call</em>. That’s the trick.</p>
<p>To do that we use <tt class="docutils literal"><span class="pre">sys._getframe</span></tt>, which is a way to look at information in the calling scope. Generally this is frowned upon, but I think this case is justifiable.</p>
<p>We’ll also let you pass an instantiated template in instead of a template name, which will be useful in places like a doctest where there aren’t other files easily accessible.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">os</span>
<span class="gp">>>> </span><span class="kn">import</span> <span class="nn">tempita</span>
<span class="gp">>>> </span><span class="k">def</span> <span class="nf">render</span><span class="p">(</span><span class="n">template</span><span class="p">,</span> <span class="o">**</span><span class="nb">vars</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">template</span><span class="p">,</span> <span class="nb">basestring</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">caller_location</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">_getframe</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">f_globals</span><span class="p">[</span><span class="s">'__file__'</span><span class="p">]</span>
<span class="gp">... </span> <span class="n">filename</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">dirname</span><span class="p">(</span><span class="n">caller_location</span><span class="p">),</span> <span class="n">template</span><span class="p">)</span>
<span class="gp">... </span> <span class="n">template</span> <span class="o">=</span> <span class="n">tempita</span><span class="o">.</span><span class="n">HTMLTemplate</span><span class="o">.</span><span class="n">from_filename</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
<span class="gp">... </span> <span class="nb">vars</span><span class="o">.</span><span class="n">setdefault</span><span class="p">(</span><span class="s">'request'</span><span class="p">,</span> <span class="n">get_request</span><span class="p">())</span>
<span class="gp">... </span> <span class="k">return</span> <span class="n">template</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="nb">vars</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="conclusion">
<h2><a class="toc-backref" href="#id16">Conclusion</a></h2>
<p>Well, that’s a framework. Ta-da!</p>
<p>Of course, this doesn’t deal with some other stuff. In particular:</p>
<ul class="simple">
<li>Configuration</li>
<li>Making your routes debuggable</li>
<li>Exception catching and other basic infrastructure</li>
<li>Database connections</li>
<li>Form handling</li>
<li>Authentication</li>
</ul>
<p>But, for now, that’s outside the scope of this document.</p>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h3><a href="index.html">Table Of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">Another Do-It-Yourself Framework</a><ul>
<li><a class="reference internal" href="#introduction-and-audience">Introduction and Audience</a></li>
<li><a class="reference internal" href="#what-is-wsgi">What Is WSGI?</a></li>
<li><a class="reference internal" href="#about-webob">About WebOb</a></li>
<li><a class="reference internal" href="#serving-your-application">Serving Your Application</a></li>
<li><a class="reference internal" href="#making-a-framework">Making A Framework</a></li>
<li><a class="reference internal" href="#routing">Routing</a><ul>
<li><a class="reference internal" href="#routing-templates">Routing: Templates</a></li>
<li><a class="reference internal" href="#routing-controller-loading">Routing: controller loading</a></li>
<li><a class="reference internal" href="#routing-putting-it-together">Routing: putting it together</a></li>
</ul>
</li>
<li><a class="reference internal" href="#controllers">Controllers</a></li>
<li><a class="reference internal" href="#putting-it-together">Putting It Together</a></li>
<li><a class="reference internal" href="#another-controller">Another Controller</a></li>
<li><a class="reference internal" href="#url-generation-and-request-access">URL Generation and Request Access</a></li>
<li><a class="reference internal" href="#templating">Templating</a></li>
<li><a class="reference internal" href="#conclusion">Conclusion</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="jsonrpc-example.html"
title="previous chapter">JSON-RPC Example</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="news.html"
title="next chapter">News</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/do-it-yourself.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="news.html" title="News"
>next</a> |</li>
<li class="right" >
<a href="jsonrpc-example.html" title="JSON-RPC Example"
>previous</a> |</li>
<li><a href="index.html">WebOb 1.2.3 documentation</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2011, Ian Bicking and contributors.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2.1.
</div>
</body>
</html>
|