/usr/share/doc/python-webob-doc/do-it-yourself.html is in python-webob-doc 1:1.6.2-2.
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 | <!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.6.2 documentation</title>
<link rel="stylesheet" href="_static/alabaster.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.6.2',
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="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="top" title="WebOb 1.6.2 documentation" href="index.html" />
<link rel="next" title="What’s New in WebOb 1.5" href="whatsnew-1.5.html" />
<link rel="prev" title="JSON-RPC Example" href="jsonrpc-example.html" />
<link rel="stylesheet" href="_static/custom.css" type="text/css" />
<meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
</head>
<body role="document">
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="another-do-it-yourself-framework">
<h1><a class="toc-backref" href="#id1">Another Do-It-Yourself Framework</a><a class="headerlink" href="#another-do-it-yourself-framework" title="Permalink to this headline">¶</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><a class="headerlink" href="#introduction-and-audience" title="Permalink to this headline">¶</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><a class="headerlink" href="#what-is-wsgi" title="Permalink to this headline">¶</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></span><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="s1">'200 OK'</span><span class="p">,</span> <span class="p">[(</span><span class="s1">'Content-Type'</span><span class="p">,</span> <span class="s1">'text/html'</span><span class="p">)])</span>
<span class="gp">... </span> <span class="k">return</span> <span class="p">[</span><span class="s1">'Hello World!'</span><span class="p">]</span>
</pre></div>
</div>
<p>The <code class="docutils literal"><span class="pre">environ</span></code> argument is a dictionary with values like the environment in a CGI request. The header <code class="docutils literal"><span class="pre">Host:</span></code>, for instance, goes in <code class="docutils literal"><span class="pre">environ['HTTP_HOST']</span></code>. The path is in <code class="docutils literal"><span class="pre">environ['SCRIPT_NAME']</span></code> (which is the path leading <em>up to</em> the application), and <code class="docutils literal"><span class="pre">environ['PATH_INFO']</span></code> (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 <code class="docutils literal"><span class="pre">req</span> <span class="pre">=</span> <span class="pre">webob.Request.blank('http://localhost/test')</span></code>, and then call the application with <code class="docutils literal"><span class="pre">resp</span> <span class="pre">=</span> <span class="pre">req.get_response(app)</span></code>. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><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="s1">'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><a class="headerlink" href="#about-webob" title="Permalink to this headline">¶</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></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="s1">'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="s1">'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></span><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="s1">'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="s1">'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 <code class="docutils literal"><span class="pre">resp(environ,</span> <span class="pre">start_response)</span></code>. 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><a class="headerlink" href="#serving-your-application" title="Permalink to this headline">¶</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></span><span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s1">'__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="s1">'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="https://docs.python.org/3/library/wsgiref.html#module-wsgiref.simple_server">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></span><span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s1">'__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="s1">'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><a class="headerlink" href="#making-a-framework" title="Permalink to this headline">¶</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><a class="headerlink" href="#routing" title="Permalink to this headline">¶</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 <code class="docutils literal"><span class="pre">{name:regular</span> <span class="pre">expression}</span></code>, 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></span><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="s1">'/'</span><span class="p">,</span> <span class="n">controller</span><span class="o">=</span><span class="s1">'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="s1">'/{year:\d\d\d\d}/'</span><span class="p">,</span>
<span class="n">controller</span><span class="o">=</span><span class="s1">'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="s1">'/{year:\d\d\d\d}/{month:\d\d}/'</span><span class="p">,</span>
<span class="n">controller</span><span class="o">=</span><span class="s1">'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="s1">'/{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="s1">'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="s1">'/post'</span><span class="p">,</span> <span class="n">controller</span><span class="o">=</span><span class="s1">'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 (<code class="docutils literal"><span class="pre">Router</span></code>)</li>
</ul>
<div class="section" id="routing-templates">
<h3><a class="toc-backref" href="#id8">Routing: Templates</a><a class="headerlink" href="#routing-templates" title="Permalink to this headline">¶</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></span> <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="s1">r'''</span>
<span class="s1"> ... \{ # The exact character "{"</span>
<span class="s1"> ... (\w+) # The variable name (restricted to a-z, 0-9, _)</span>
<span class="s1"> ... (?::([^}]+))? # The optional :regex part</span>
<span class="s1"> ... \} # The exact character "}"</span>
<span class="s1"> ... '''</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="s1">''</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="s1">'[^/]+'</span>
<span class="o">...</span> <span class="n">expr</span> <span class="o">=</span> <span class="s1">'(?P<</span><span class="si">%s</span><span class="s1">></span><span class="si">%s</span><span class="s1">)'</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="s1">'^</span><span class="si">%s</span><span class="s1">$'</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 <code class="docutils literal"><span class="pre">re.VERBOSE</span></code> 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., <code class="docutils literal"><span class="pre">{var:regex}</span></code> (where <code class="docutils literal"><span class="pre">:regex</span></code> is optional). Note that there are two groups we capture: <code class="docutils literal"><span class="pre">match.group(1)</span></code> will be the variable name, and <code class="docutils literal"><span class="pre">match.group(2)</span></code> will be the regular expression (or None when there is no regular expression). Note that <code class="docutils literal"><span class="pre">(?:...)?</span></code> means that the section is optional.</p>
<p><strong>line 9</strong>: This variable will hold the regular expression that we are creating.</p>
<p><strong>line 10</strong>: This contains the position of the end of the last match.</p>
<p><strong>line 11</strong>: The <code class="docutils literal"><span class="pre">finditer</span></code> method yields all the matches.</p>
<p><strong>line 12</strong>: We’re getting all the non-<code class="docutils literal"><span class="pre">{}</span></code> text from after the last match, up to the beginning of this match. We call <code class="docutils literal"><span class="pre">re.escape</span></code> on that text, which escapes any characters that have special meaning. So <code class="docutils literal"><span class="pre">.html</span></code> will be escaped as <code class="docutils literal"><span class="pre">\.html</span></code>.</p>
<p><strong>line 13</strong>: The first match is the variable name.</p>
<p><strong>line 14</strong>: <code class="docutils literal"><span class="pre">expr</span></code> is the regular expression we’ll match against, the optional second match. The default is <code class="docutils literal"><span class="pre">[^/]+</span></code>, which matches any non-empty, non-/ string. Which seems like a reasonable default to me.</p>
<p><strong>line 15</strong>: Here we create the actual regular expression. <code class="docutils literal"><span class="pre">(?P<name>...)</span></code> is a grouped expression that is named. When you get a match, you can look at <code class="docutils literal"><span class="pre">match.groupdict()</span></code> and get the names and values.</p>
<p><strong>line 16, 17</strong>: We add the expression on to the complete regular expression and save the last position.</p>
<p><strong>line 18</strong>: We add remaining non-variable text to the regular expression.</p>
<p><strong>line 19</strong>: And then we make the regular expression match the complete string (<code class="docutils literal"><span class="pre">^</span></code> to force it to match from the start, <code class="docutils literal"><span class="pre">$</span></code> 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 <code class="docutils literal"><span class="pre">template_to_regex</span></code> 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></span><span class="gp">>>> </span><span class="k">print</span> <span class="n">template_to_regex</span><span class="p">(</span><span class="s1">'/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="s1">'/{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><a class="headerlink" href="#routing-controller-loading" title="Permalink to this headline">¶</a></h3>
<p>To load controllers we have to import the module, then get the function out of it. We’ll use the <code class="docutils literal"><span class="pre">__import__</span></code> builtin to import the module. The return value of <code class="docutils literal"><span class="pre">__import__</span></code> isn’t very useful, but it puts the module into <code class="docutils literal"><span class="pre">sys.modules</span></code>, a dictionary of all the loaded modules.</p>
<p>Also, some people don’t know how exactly the string method <code class="docutils literal"><span class="pre">split</span></code> 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 <code class="docutils literal"><span class="pre">:</span></code> character, so we’ll use a maximum number of splits of 1.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><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="s1">':'</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><a class="headerlink" href="#routing-putting-it-together" title="Permalink to this headline">¶</a></h3>
<p>Now, the <code class="docutils literal"><span class="pre">Router</span></code> class. The class has the <code class="docutils literal"><span class="pre">add_route</span></code> method, and also a <code class="docutils literal"><span class="pre">__call__</span></code> method. That <code class="docutils literal"><span class="pre">__call__</span></code> method makes the Router object itself a WSGI application. So when a request comes in, it looks at <code class="docutils literal"><span class="pre">PATH_INFO</span></code> (also known as <code class="docutils literal"><span class="pre">req.path_info</span></code>) 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></span> <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 <code class="docutils literal"><span class="pre">(regex,</span> <span class="pre">controller,</span> <span class="pre">vars)</span></code>: <code class="docutils literal"><span class="pre">regex</span></code> is the regular expression object to match against, <code class="docutils literal"><span class="pre">controller</span></code> is the controller to run, and <code class="docutils literal"><span class="pre">vars</span></code> are any extra (constant) variables.</p>
<p><strong>line 8, 9</strong>: We will allow you to call <code class="docutils literal"><span class="pre">add_route</span></code> 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 14</strong>: Here we add a <code class="docutils literal"><span class="pre">__call__</span></code> 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 15</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 17</strong>: We test the regular expression against <code class="docutils literal"><span class="pre">req.path_info</span></code>. This is the same as <code class="docutils literal"><span class="pre">environ['PATH_INFO']</span></code>. That’s all the request path left to be processed.</p>
<p><strong>line 19</strong>: We set <code class="docutils literal"><span class="pre">req.urlvars</span></code> to the dictionary of matches in the regular expression. This variable actually maps to <code class="docutils literal"><span class="pre">environ['wsgiorg.routing_args']</span></code>. 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 20</strong>: We also add in any explicit variables passed in through <code class="docutils literal"><span class="pre">add_route()</span></code>.</p>
<p><strong>line 21</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 22</strong>: If nothing matches, we return a 404 Not Found response. <code class="docutils literal"><span class="pre">webob.exc.HTTPNotFound()</span></code> is a WSGI application that returns 404 responses. You could add a message too, like <code class="docutils literal"><span class="pre">webob.exc.HTTPNotFound('No</span> <span class="pre">route</span> <span class="pre">matched')</span></code>. Then, of course, we call the application.</p>
</div>
</div>
<div class="section" id="controllers">
<h2><a class="toc-backref" href="#id11">Controllers</a><a class="headerlink" href="#controllers" title="Permalink to this headline">¶</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 <code class="docutils literal"><span class="pre">controller_func(req,</span> <span class="pre">**urlvars)</span></code>. 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></span> <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 <code class="docutils literal"><span class="pre">func</span></code>, and everytime you decorate a new function there will be a new <code class="docutils literal"><span class="pre">replacement</span></code> function with its own value of <code class="docutils literal"><span class="pre">func</span></code>. 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 <code class="docutils literal"><span class="pre">webob.exc.HTTPException</span></code> exceptions. This is so you can do <code class="docutils literal"><span class="pre">raise</span> <span class="pre">webob.exc.HTTPNotFound()</span></code> 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 <code class="docutils literal"><span class="pre">req.urlvars</span></code>. 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 <code class="docutils literal"><span class="pre">Response</span></code> object with that (and with the standard <code class="docutils literal"><span class="pre">200</span> <span class="pre">OK</span></code> status, <code class="docutils literal"><span class="pre">text/html</span></code> content type, and <code class="docutils literal"><span class="pre">utf8</span></code> 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></span><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="s1">'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><a class="headerlink" href="#putting-it-together" title="Permalink to this headline">¶</a></h2>
<p>Now we’ll show a basic application. Just a hello world application for now. Note that this document is the module <code class="docutils literal"><span class="pre">__main__</span></code>.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><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="s1">'POST'</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">return</span> <span class="s1">'Hello </span><span class="si">%s</span><span class="s1">!'</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="s1">'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="s1">'GET'</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">return</span> <span class="s1">'''<form method="POST"></span>
<span class="gp">... </span><span class="s1"> Your name: <input type="text" name="name"></span>
<span class="gp">... </span><span class="s1"> <input type="submit"></span>
<span class="gp">... </span><span class="s1"> </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="s1">'/'</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></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="s1">'/'</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"> Your 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="s1">'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="s1">'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><a class="headerlink" href="#another-controller" title="Permalink to this headline">¶</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 <code class="docutils literal"><span class="pre">get</span></code>, <code class="docutils literal"><span class="pre">post</span></code>, etc. The <code class="docutils literal"><span class="pre">urlvars</span></code> 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 <code class="docutils literal"><span class="pre">action</span></code> variable, which will define the method (actually <code class="docutils literal"><span class="pre">action_method</span></code>, where <code class="docutils literal"><span class="pre">_method</span></code> is the request method). If no action is given, we’ll use just the method (i.e., <code class="docutils literal"><span class="pre">get</span></code>, <code class="docutils literal"><span class="pre">post</span></code>, 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></span> <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="s1">'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="s1">'_'</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="s2">"No action </span><span class="si">%s</span><span class="s2">"</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 <code class="docutils literal"><span class="pre">req.urlvars</span></code> 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 <code class="docutils literal"><span class="pre">{action}_{method}</span></code>...</p>
<p><strong>line 9, 10</strong>: ... otherwise we’ll use just the method for the method name.</p>
<p><strong>line 11-14</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 15</strong>: Call the method, get the response</p>
<p><strong>line 16, 17</strong>: If the response is just a string, create a full response object from it.</p>
<p><strong>line 20</strong>: and then we forward the request...</p>
<p><strong>line 21</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></span><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="s1">'''<form method="POST"></span>
<span class="gp">... </span><span class="s1"> Your name: <input type="text" name="name"></span>
<span class="gp">... </span><span class="s1"> <input type="submit"></span>
<span class="gp">... </span><span class="s1"> </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="s1">'Hello </span><span class="si">%s</span><span class="s1">!'</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="s1">'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></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="s1">'/'</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="s1">'/'</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"> Your 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="s1">'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="s1">'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><a class="headerlink" href="#url-generation-and-request-access" title="Permalink to this headline">¶</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 <code class="docutils literal"><span class="pre">SCRIPT_NAME</span></code>, 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 <code class="docutils literal"><span class="pre">/blog/</span></code>, and then SCRIPT_NAME would be <code class="docutils literal"><span class="pre">"/blog"</span></code>. We should generate links with that in mind.</p>
<p>The base URL using SCRIPT_NAME is <code class="docutils literal"><span class="pre">req.application_url</span></code>. 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 current 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 <code class="docutils literal"><span class="pre">threading.local()</span></code>. 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></span><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="s2">"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 <code class="docutils literal"><span class="pre">Router</span></code> 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></span><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-default"><div class="highlight"><pre><span></span><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></span><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="s1">'/'</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="s1">'/'</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">path</span> <span class="o">=</span> <span class="s1">'/'</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="s1">'?'</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></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">Request</span><span class="o">.</span><span class="n">blank</span><span class="p">(</span><span class="s1">'http://localhost/'</span><span class="p">))</span>
<span class="gp">>>> </span><span class="n">url</span><span class="p">(</span><span class="s1">'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="s1">'search'</span><span class="p">,</span> <span class="n">q</span><span class="o">=</span><span class="s1">'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><a class="headerlink" href="#templating" title="Permalink to this headline">¶</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></span><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="s1">'some-file.html'</span><span class="p">)</span>
</pre></div>
</div>
<p>But we’ll be implementing a function <code class="docutils literal"><span class="pre">render(template_name,</span> <span class="pre">**vars)</span></code> 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 <code class="docutils literal"><span class="pre">sys._getframe</span></code>, 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></span><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="s1">'__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="s1">'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><a class="headerlink" href="#conclusion" title="Permalink to this headline">¶</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" role="navigation" aria-label="main navigation">
<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>
<div class="relations">
<h3>Related Topics</h3>
<ul>
<li><a href="index.html">Documentation overview</a><ul>
<li>Previous: <a href="jsonrpc-example.html" title="previous chapter">JSON-RPC Example</a></li>
<li>Next: <a href="whatsnew-1.5.html" title="next chapter">What’s New in WebOb 1.5</a></li>
</ul></li>
</ul>
</div>
<div role="note" aria-label="source link">
<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>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<div><input type="text" name="q" /></div>
<div><input type="submit" value="Go" /></div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer">
©2017, Ian Bicking and contributors.
|
Powered by <a href="http://sphinx-doc.org/">Sphinx 1.4.9</a>
& <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.8</a>
|
<a href="_sources/do-it-yourself.txt"
rel="nofollow">Page source</a>
</div>
</body>
</html>
|