/usr/share/doc/python-cherrypy3-doc/html/advanced.html is in python-cherrypy3-doc 8.9.1-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 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 | <!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>Advanced — CherryPy 8.9.1 documentation</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '8.9.1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</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="next" title="Configure" href="config.html" />
<link rel="prev" title="Basics" href="basics.html" />
</head>
<body>
<div class="related" role="navigation" aria-label="related navigation">
<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="config.html" title="Configure"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="basics.html" title="Basics"
accesskey="P">previous</a> |</li>
<li class="nav-item nav-item-0"><a href="index.html">CherryPy 8.9.1 documentation</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="advanced">
<span id="id1"></span><h1><a class="toc-backref" href="#id3">Advanced</a><a class="headerlink" href="#advanced" title="Permalink to this headline">¶</a></h1>
<p>CherryPy has support for more advanced features that these sections
will describe.</p>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#advanced" id="id3">Advanced</a><ul>
<li><a class="reference internal" href="#set-aliases-to-page-handlers" id="id4">Set aliases to page handlers</a></li>
<li><a class="reference internal" href="#restful-style-dispatching" id="id5">RESTful-style dispatching</a><ul>
<li><a class="reference internal" href="#the-special-cp-dispatch-method" id="id6">The special _cp_dispatch method</a></li>
<li><a class="reference internal" href="#the-popargs-decorator" id="id7">The popargs decorator</a></li>
</ul>
</li>
<li><a class="reference internal" href="#error-handling" id="id8">Error handling</a></li>
<li><a class="reference internal" href="#streaming-the-response-body" id="id9">Streaming the response body</a><ul>
<li><a class="reference internal" href="#the-normal-cherrypy-response-process" id="id10">The “normal” CherryPy response process</a></li>
<li><a class="reference internal" href="#how-streaming-output-works-with-cherrypy" id="id11">How “streaming output” works with CherryPy</a></li>
</ul>
</li>
<li><a class="reference internal" href="#response-timeouts" id="id12">Response timeouts</a><ul>
<li><a class="reference internal" href="#timeout-monitor" id="id13">Timeout Monitor</a></li>
</ul>
</li>
<li><a class="reference internal" href="#deal-with-signals" id="id14">Deal with signals</a><ul>
<li><a class="reference internal" href="#windows-console-events" id="id15">Windows Console Events</a></li>
</ul>
</li>
<li><a class="reference internal" href="#securing-your-server" id="id16">Securing your server</a></li>
<li><a class="reference internal" href="#multiple-http-servers-support" id="id17">Multiple HTTP servers support</a></li>
<li><a class="reference internal" href="#wsgi-support" id="id18">WSGI support</a><ul>
<li><a class="reference internal" href="#make-your-cherrypy-application-a-wsgi-application" id="id19">Make your CherryPy application a WSGI application</a></li>
<li><a class="reference internal" href="#host-a-foreign-wsgi-application-in-cherrypy" id="id20">Host a foreign WSGI application in CherryPy</a></li>
<li><a class="reference internal" href="#no-need-for-the-wsgi-interface" id="id21">No need for the WSGI interface?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#websocket-support" id="id22">WebSocket support</a></li>
<li><a class="reference internal" href="#database-support" id="id23">Database support</a></li>
<li><a class="reference internal" href="#html-templating-support" id="id24">HTML Templating support</a></li>
<li><a class="reference internal" href="#testing-your-application" id="id25">Testing your application</a></li>
</ul>
</li>
</ul>
</div>
<div class="section" id="set-aliases-to-page-handlers">
<span id="aliases"></span><h2><a class="toc-backref" href="#id4">Set aliases to page handlers</a><a class="headerlink" href="#set-aliases-to-page-handlers" title="Permalink to this headline">¶</a></h2>
<p>A fairly unknown, yet useful, feature provided by the <code class="xref py py-func docutils literal"><span class="pre">cherrypy.expose()</span></code>
decorator is to support aliases.</p>
<p>Let’s use the template provided by <a class="reference internal" href="tutorials.html#tut03"><span class="std std-ref">tutorial 03</span></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">random</span>
<span class="kn">import</span> <span class="nn">string</span>
<span class="kn">import</span> <span class="nn">cherrypy</span>
<span class="k">class</span> <span class="nc">StringGenerator</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="nd">@cherrypy.expose</span><span class="p">([</span><span class="s1">'generer'</span><span class="p">,</span> <span class="s1">'generar'</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">generate</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">length</span><span class="o">=</span><span class="mi">8</span><span class="p">):</span>
<span class="k">return</span> <span class="s1">''</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">string</span><span class="o">.</span><span class="n">hexdigits</span><span class="p">,</span> <span class="nb">int</span><span class="p">(</span><span class="n">length</span><span class="p">)))</span>
<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">'__main__'</span><span class="p">:</span>
<span class="n">cherrypy</span><span class="o">.</span><span class="n">quickstart</span><span class="p">(</span><span class="n">StringGenerator</span><span class="p">())</span>
</pre></div>
</div>
<p>In this example, we create localized aliases for
the page handler. This means the page handler will be
accessible via:</p>
<ul class="simple">
<li>/generate</li>
<li>/generer (French)</li>
<li>/generar (Spanish)</li>
</ul>
<p>Obviously, your aliases may be whatever suits your needs.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The alias may be a single string or a list of them.</p>
</div>
</div>
<div class="section" id="restful-style-dispatching">
<span id="restful"></span><h2><a class="toc-backref" href="#id5">RESTful-style dispatching</a><a class="headerlink" href="#restful-style-dispatching" title="Permalink to this headline">¶</a></h2>
<p>The term <cite>RESTful URL</cite> is sometimes used to talk about friendly URLs
that nicely map to the entities an application exposes.</p>
<div class="admonition important">
<p class="first admonition-title">Important</p>
<p class="last">We will not enter the debate around what is restful or not but we will
showcase two mechanisms to implement the usual idea in your
CherryPy application.</p>
</div>
<p>Let’s assume you wish to create an application that exposes
music bands and their records. Your application will probably have
the following URLs:</p>
<ul class="simple">
<li><a class="reference external" href="http://hostname">http://hostname</a>/<artist>/</li>
<li><a class="reference external" href="http://hostname">http://hostname</a>/<artist>/albums/<album_title>/</li>
</ul>
<p>It’s quite clear you would not create a page handler named after
every possible band in the world. This means you will need a page handler
that acts as a proxy for all of them.</p>
<p>The default dispatcher cannot deal with that scenario on its own
because it expects page handlers to be explicitely declared in your
source code. Luckily, CherryPy provides ways to support those use cases.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">This section extends from this <a class="reference external" href="http://stackoverflow.com/a/15789415/1363905">stackoverflow response</a>.</p>
</div>
<div class="section" id="the-special-cp-dispatch-method">
<h3><a class="toc-backref" href="#id6">The special _cp_dispatch method</a><a class="headerlink" href="#the-special-cp-dispatch-method" title="Permalink to this headline">¶</a></h3>
<p><code class="docutils literal"><span class="pre">_cp_dispatch</span></code> is a special method you declare in any of your <a class="reference internal" href="glossary.html#term-controller"><span class="xref std std-term">controller</span></a>
to massage the remaining segments before CherryPy gets to process them.
This offers you the capacity to remove, add or otherwise handle any segment
you wish and, even, entirely change the remaining parts.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cherrypy</span>
<span class="k">class</span> <span class="nc">Band</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">albums</span> <span class="o">=</span> <span class="n">Album</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">_cp_dispatch</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">vpath</span><span class="p">):</span>
<span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">vpath</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
<span class="n">cherrypy</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="o">=</span> <span class="n">vpath</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="k">return</span> <span class="bp">self</span>
<span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">vpath</span><span class="p">)</span> <span class="o">==</span> <span class="mi">3</span><span class="p">:</span>
<span class="n">cherrypy</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">'artist'</span><span class="p">]</span> <span class="o">=</span> <span class="n">vpath</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="c1"># /band name/</span>
<span class="n">vpath</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="c1"># /albums/</span>
<span class="n">cherrypy</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">'title'</span><span class="p">]</span> <span class="o">=</span> <span class="n">vpath</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="c1"># /album title/</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">albums</span>
<span class="k">return</span> <span class="n">vpath</span>
<span class="nd">@cherrypy.expose</span>
<span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
<span class="k">return</span> <span class="s1">'About </span><span class="si">%s</span><span class="s1">...'</span> <span class="o">%</span> <span class="n">name</span>
<span class="k">class</span> <span class="nc">Album</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="nd">@cherrypy.expose</span>
<span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">artist</span><span class="p">,</span> <span class="n">title</span><span class="p">):</span>
<span class="k">return</span> <span class="s1">'About </span><span class="si">%s</span><span class="s1"> by </span><span class="si">%s</span><span class="s1">...'</span> <span class="o">%</span> <span class="p">(</span><span class="n">title</span><span class="p">,</span> <span class="n">artist</span><span class="p">)</span>
<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">'__main__'</span><span class="p">:</span>
<span class="n">cherrypy</span><span class="o">.</span><span class="n">quickstart</span><span class="p">(</span><span class="n">Band</span><span class="p">())</span>
</pre></div>
</div>
<p>Notice how the controller defines <cite>_cp_dispatch</cite>, it takes
a single argument, the URL path info broken into its segments.</p>
<p>The method can inspect and manipulate the list of segments,
removing any or adding new segments at any position. The new list of
segments is then sent to the dispatcher which will use it
to locate the appropriate resource.</p>
<p>In the above example, you should be able to go to the following URLs:</p>
<ul class="simple">
<li><a class="reference external" href="http://localhost:8080/nirvana/">http://localhost:8080/nirvana/</a></li>
<li><a class="reference external" href="http://localhost:8080/nirvana/albums/nevermind/">http://localhost:8080/nirvana/albums/nevermind/</a></li>
</ul>
<p>The <code class="docutils literal"><span class="pre">/nirvana/</span></code> segment is associated to the band and
the <code class="docutils literal"><span class="pre">/nevermind/</span></code> segment relates to the album.</p>
<p>To achieve this, our <cite>_cp_dispatch</cite> method works on the idea
that the default dispatcher matches URLs against page handler
signatures and their position in the tree of handlers.</p>
<p>In this case, we take the dynamic segments in the URL (band and record names),
we inject them into the request parameters and we remove them
from the segment lists as if they had never been there in the first place.</p>
<p>In other words, <cite>_cp_dispatch</cite> makes it as if we were
working on the following URLs:</p>
<ul class="simple">
<li><a class="reference external" href="http://localhost:8080/?artist=nirvana">http://localhost:8080/?artist=nirvana</a></li>
<li><a class="reference external" href="http://localhost:8080/albums/?artist=nirvana&title=nevermind">http://localhost:8080/albums/?artist=nirvana&title=nevermind</a></li>
</ul>
</div>
<div class="section" id="the-popargs-decorator">
<h3><a class="toc-backref" href="#id7">The popargs decorator</a><a class="headerlink" href="#the-popargs-decorator" title="Permalink to this headline">¶</a></h3>
<p><code class="xref py py-func docutils literal"><span class="pre">cherrypy.popargs()</span></code> is more straightforward as it gives a name to any segment
that CherryPy wouldn’t be able to interpret otherwise. This makes the
matching of segments with page handler signatures easier and helps CherryPy
understand the structure of your URL.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cherrypy</span>
<span class="nd">@cherrypy.popargs</span><span class="p">(</span><span class="s1">'band_name'</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Band</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">albums</span> <span class="o">=</span> <span class="n">Album</span><span class="p">()</span>
<span class="nd">@cherrypy.expose</span>
<span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">band_name</span><span class="p">):</span>
<span class="k">return</span> <span class="s1">'About </span><span class="si">%s</span><span class="s1">...'</span> <span class="o">%</span> <span class="n">band_name</span>
<span class="nd">@cherrypy.popargs</span><span class="p">(</span><span class="s1">'album_title'</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Album</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="nd">@cherrypy.expose</span>
<span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">band_name</span><span class="p">,</span> <span class="n">album_title</span><span class="p">):</span>
<span class="k">return</span> <span class="s1">'About </span><span class="si">%s</span><span class="s1"> by </span><span class="si">%s</span><span class="s1">...'</span> <span class="o">%</span> <span class="p">(</span><span class="n">album_title</span><span class="p">,</span> <span class="n">band_name</span><span class="p">)</span>
<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">'__main__'</span><span class="p">:</span>
<span class="n">cherrypy</span><span class="o">.</span><span class="n">quickstart</span><span class="p">(</span><span class="n">Band</span><span class="p">())</span>
</pre></div>
</div>
<p>This works similarly to <cite>_cp_dispatch</cite> but, as said above, is more
explicit and localized. It says:</p>
<ul class="simple">
<li>take the first segment and store it into a parameter named <cite>band_name</cite></li>
<li>take again the first segment (since we removed the previous first)
and store it into a parameter named <cite>album_title</cite></li>
</ul>
<p>Note that the decorator accepts more than a single binding. For instance:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="nd">@cherrypy.popargs</span><span class="p">(</span><span class="s1">'album_title'</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Album</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">tracks</span> <span class="o">=</span> <span class="n">Track</span><span class="p">()</span>
<span class="nd">@cherrypy.popargs</span><span class="p">(</span><span class="s1">'track_num'</span><span class="p">,</span> <span class="s1">'track_title'</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Track</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="nd">@cherrypy.expose</span>
<span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">band_name</span><span class="p">,</span> <span class="n">album_title</span><span class="p">,</span> <span class="n">track_num</span><span class="p">,</span> <span class="n">track_title</span><span class="p">):</span>
<span class="o">...</span>
</pre></div>
</div>
<p>This would handle the following URL:</p>
<ul class="simple">
<li><a class="reference external" href="http://localhost:8080/nirvana/albums/nevermind/tracks/06/polly">http://localhost:8080/nirvana/albums/nevermind/tracks/06/polly</a></li>
</ul>
<p>Notice finally how the whole stack of segments is passed to each
page handler so that you have the full context.</p>
</div>
</div>
<div class="section" id="error-handling">
<h2><a class="toc-backref" href="#id8">Error handling</a><a class="headerlink" href="#error-handling" title="Permalink to this headline">¶</a></h2>
<p>CherryPy’s <code class="docutils literal"><span class="pre">HTTPError</span></code> class supports raising immediate responses in the case of
errors.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Root</span><span class="p">:</span>
<span class="nd">@cherrypy.expose</span>
<span class="k">def</span> <span class="nf">thing</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">path</span><span class="p">):</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">authorized</span><span class="p">():</span>
<span class="k">raise</span> <span class="n">cherrypy</span><span class="o">.</span><span class="n">HTTPError</span><span class="p">(</span><span class="mi">401</span><span class="p">,</span> <span class="s1">'Unauthorized'</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="nb">file</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
<span class="k">except</span> <span class="n">FileNotFoundError</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">cherrypy</span><span class="o">.</span><span class="n">HTTPError</span><span class="p">(</span><span class="mi">404</span><span class="p">)</span>
</pre></div>
</div>
<p><code class="docutils literal"><span class="pre">HTTPError.handle</span></code> is a context manager which supports translating exceptions
raised in the app into an appropriate HTTP response, as in the second example.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Root</span><span class="p">:</span>
<span class="nd">@cherrypy.expose</span>
<span class="k">def</span> <span class="nf">thing</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">path</span><span class="p">):</span>
<span class="k">with</span> <span class="n">cherrypy</span><span class="o">.</span><span class="n">HTTPError</span><span class="o">.</span><span class="n">handle</span><span class="p">(</span><span class="n">FileNotFoundError</span><span class="p">,</span> <span class="mi">404</span><span class="p">):</span>
<span class="nb">file</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="streaming-the-response-body">
<h2><a class="toc-backref" href="#id9">Streaming the response body</a><a class="headerlink" href="#streaming-the-response-body" title="Permalink to this headline">¶</a></h2>
<p>CherryPy handles HTTP requests, packing and unpacking the low-level details,
then passing control to your application’s <a class="reference internal" href="glossary.html#term-page-handler"><span class="xref std std-term">page handler</span></a>, which produce
the body of the response. CherryPy allows you to return body content in a
variety of types: a string, a list of strings, a file. CherryPy also allows you
to <em>yield</em> content, rather than <em>return</em> content. When you use “yield”, you also
have the option of streaming the output.</p>
<p><strong>In general, it is safer and easier to not stream output.</strong> Therefore,
streaming output is off by default. Streaming output and also using sessions
requires a good understanding of <code class="xref py py-mod docutils literal"><span class="pre">how</span> <span class="pre">session</span> <span class="pre">locks</span> <span class="pre">work</span></code>.</p>
<div class="section" id="the-normal-cherrypy-response-process">
<h3><a class="toc-backref" href="#id10">The “normal” CherryPy response process</a><a class="headerlink" href="#the-normal-cherrypy-response-process" title="Permalink to this headline">¶</a></h3>
<p>When you provide content from your page handler, CherryPy manages the
conversation between the HTTP server and your code like this:</p>
<img alt="_images/cpreturn.gif" src="_images/cpreturn.gif" />
<p>Notice that the HTTP server gathers all output first and then writes everything
to the client at once: status, headers, and body. This works well for static or
simple pages, since the entire response can be changed at any time, either in
your application code, or by the CherryPy framework.</p>
</div>
<div class="section" id="how-streaming-output-works-with-cherrypy">
<h3><a class="toc-backref" href="#id11">How “streaming output” works with CherryPy</a><a class="headerlink" href="#how-streaming-output-works-with-cherrypy" title="Permalink to this headline">¶</a></h3>
<p>When you set the config entry “response.stream” to True (and use “yield”),
CherryPy manages the conversation between the HTTP server and your code like this:</p>
<img alt="_images/cpyield.gif" src="_images/cpyield.gif" />
<p>When you stream, your application doesn’t immediately pass raw body content
back to CherryPy or to the HTTP server. Instead, it passes back a generator.
At that point, CherryPy finalizes the status and headers, <strong>before</strong> the
generator has been consumed, or has produced any output. This is necessary to
allow the HTTP server to send the headers and pieces of the body as they become
available.</p>
<p>Once CherryPy has set the status and headers, it sends them to the HTTP server,
which then writes them out to the client. From that point on, the CherryPy
framework mostly steps out of the way, and the HTTP server essentially requests
content directly from your application code (your page handler method).</p>
<p>Therefore, when streaming, if an error occurs within your page handler,
CherryPy will not catch it–the HTTP server will catch it. Because the headers
(and potentially some of the body) have already been written to the client,
the server <em>cannot</em> know a safe means of handling the error, and will therefore
simply close the connection (the current, builtin servers actually write out a
short error message in the body, but this may be changed, and is not guaranteed
behavior for all HTTP servers you might use with CherryPy).</p>
<p>In addition, you cannot manually modify the status or headers within your page
handler if that handler method is a streaming generator, because the method will
not be iterated over until after the headers have been written to the client.
<strong>This includes raising exceptions like HTTPError, NotFound, InternalRedirect
and HTTPRedirect.</strong> To use a streaming generator while modifying headers, you
would have to return a generator that is separate from (or embedded in) your
page handler. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Root</span><span class="p">:</span>
<span class="nd">@cherrypy.expose</span>
<span class="k">def</span> <span class="nf">thing</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">cherrypy</span><span class="o">.</span><span class="n">response</span><span class="o">.</span><span class="n">headers</span><span class="p">[</span><span class="s1">'Content-Type'</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'text/plain'</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">authorized</span><span class="p">():</span>
<span class="k">raise</span> <span class="n">cherrypy</span><span class="o">.</span><span class="n">NotFound</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">content</span><span class="p">():</span>
<span class="k">yield</span> <span class="s2">"Hello, "</span>
<span class="k">yield</span> <span class="s2">"world"</span>
<span class="k">return</span> <span class="n">content</span><span class="p">()</span>
<span class="n">thing</span><span class="o">.</span><span class="n">_cp_config</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'response.stream'</span><span class="p">:</span> <span class="bp">True</span><span class="p">}</span>
</pre></div>
</div>
<p>Streaming generators are sexy, but they play havoc with HTTP. CherryPy allows
you to stream output for specific situations: pages which take many minutes to
produce, or pages which need a portion of their content immediately output to
the client. Because of the issues outlined above, <strong>it is usually better to
flatten (buffer) content rather than stream content</strong>. Do otherwise only when
the benefits of streaming outweigh the risks.</p>
</div>
</div>
<div class="section" id="response-timeouts">
<h2><a class="toc-backref" href="#id12">Response timeouts</a><a class="headerlink" href="#response-timeouts" title="Permalink to this headline">¶</a></h2>
<p>CherryPy responses include 3 attributes related to time:</p>
<blockquote>
<div><ul class="simple">
<li><code class="docutils literal"><span class="pre">response.time</span></code>: the <code class="xref py py-func docutils literal"><span class="pre">time.time()</span></code> at which the response began</li>
<li><code class="docutils literal"><span class="pre">response.timeout</span></code>: the number of seconds to allow responses to run</li>
<li><code class="docutils literal"><span class="pre">response.timed_out</span></code>: a boolean indicating whether the response has
timed out (default False).</li>
</ul>
</div></blockquote>
<p>The request processing logic inspects the value of <code class="docutils literal"><span class="pre">response.timed_out</span></code> at
various stages; if it is ever True, then <code class="xref py py-class docutils literal"><span class="pre">TimeoutError</span></code> is raised.
You are free to do the same within your own code.</p>
<p>Rather than calculate the difference by hand, you can call
<code class="docutils literal"><span class="pre">response.check_timeout</span></code> to set <code class="docutils literal"><span class="pre">timed_out</span></code> for you.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The default response timeout is 300 seconds.</p>
</div>
<div class="section" id="timeout-monitor">
<span id="timeoutmonitor"></span><h3><a class="toc-backref" href="#id13">Timeout Monitor</a><a class="headerlink" href="#timeout-monitor" title="Permalink to this headline">¶</a></h3>
<p>In addition, CherryPy includes a <code class="docutils literal"><span class="pre">cherrypy.engine.timeout_monitor</span></code> which
monitors all active requests in a separate thread; periodically, it calls
<code class="docutils literal"><span class="pre">check_timeout</span></code> on them all. It is subscribed by default. To turn it off:</p>
<div class="highlight-ini"><div class="highlight"><pre><span></span><span class="k">[global]</span>
<span class="na">engine.timeout_monitor.on: False</span>
</pre></div>
</div>
<p>or:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="n">cherrypy</span><span class="o">.</span><span class="n">engine</span><span class="o">.</span><span class="n">timeout_monitor</span><span class="o">.</span><span class="n">unsubscribe</span><span class="p">()</span>
</pre></div>
</div>
<p>You can also change the interval (in seconds) at which the timeout monitor runs:</p>
<div class="highlight-ini"><div class="highlight"><pre><span></span><span class="k">[global]</span>
<span class="na">engine.timeout_monitor.frequency: 60 * 60</span>
</pre></div>
</div>
<p>The default is once per minute. The above example changes that to once per hour.</p>
</div>
</div>
<div class="section" id="deal-with-signals">
<h2><a class="toc-backref" href="#id14">Deal with signals</a><a class="headerlink" href="#deal-with-signals" title="Permalink to this headline">¶</a></h2>
<p>This <a class="reference internal" href="extend.html#busplugins"><span class="std std-ref">engine plugin</span></a> is instantiated automatically as
<cite>cherrypy.engine.signal_handler</cite>.
However, it is only <em>subscribed</em> automatically by <code class="xref py py-func docutils literal"><span class="pre">cherrypy.quickstart()</span></code>.
So if you want signal handling and you’re calling:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="n">tree</span><span class="o">.</span><span class="n">mount</span><span class="p">()</span>
<span class="n">engine</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
<span class="n">engine</span><span class="o">.</span><span class="n">block</span><span class="p">()</span>
</pre></div>
</div>
<p>on your own, be sure to add before you start the engine:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="n">engine</span><span class="o">.</span><span class="n">signals</span><span class="o">.</span><span class="n">subscribe</span><span class="p">()</span>
</pre></div>
</div>
<div class="section" id="windows-console-events">
<span id="windows-console"></span><span id="index-0"></span><h3><a class="toc-backref" href="#id15">Windows Console Events</a><a class="headerlink" href="#windows-console-events" title="Permalink to this headline">¶</a></h3>
<p>Microsoft Windows uses console events to communicate some signals, like Ctrl-C.
Deploying CherryPy on Windows platforms requires <a class="reference external" href="http://sourceforge.net/projects/pywin32/">Python for Windows Extensions</a>, which are installed automatically,
being provided an extra dependency with environment marker. With that
installed, CherryPy will handle Ctrl-C and other
console events (CTRL_C_EVENT, CTRL_LOGOFF_EVENT, CTRL_BREAK_EVENT,
CTRL_SHUTDOWN_EVENT, and CTRL_CLOSE_EVENT) automatically, shutting down the
bus in preparation for process exit.</p>
</div>
</div>
<div class="section" id="securing-your-server">
<h2><a class="toc-backref" href="#id16">Securing your server</a><a class="headerlink" href="#securing-your-server" title="Permalink to this headline">¶</a></h2>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This section is not meant as a complete guide to securing
a web application or ecosystem. Please review the various
guides provided at <a class="reference external" href="https://www.owasp.org/index.php/Main_Page">OWASP</a>.</p>
</div>
<p>There are several settings that can be enabled to make CherryPy pages more secure. These include:</p>
<blockquote>
<div><p>Transmitting data:</p>
<blockquote>
<div><ol class="arabic simple">
<li>Use Secure Cookies</li>
</ol>
</div></blockquote>
<p>Rendering pages:</p>
<blockquote>
<div><ol class="arabic simple">
<li>Set HttpOnly cookies</li>
<li>Set XFrame options</li>
<li>Enable XSS Protection</li>
<li>Set the Content Security Policy</li>
</ol>
</div></blockquote>
</div></blockquote>
<p>An easy way to accomplish this is to set headers with a tool
and wrap your entire CherryPy application with it:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cherrypy</span>
<span class="c1"># set the priority according to your needs if you are hooking something</span>
<span class="c1"># else on the 'before_finalize' hook point.</span>
<span class="nd">@cherrypy.tools.register</span><span class="p">(</span><span class="s1">'before_finalize'</span><span class="p">,</span> <span class="n">priority</span><span class="o">=</span><span class="mi">60</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">secureheaders</span><span class="p">():</span>
<span class="n">headers</span> <span class="o">=</span> <span class="n">cherrypy</span><span class="o">.</span><span class="n">response</span><span class="o">.</span><span class="n">headers</span>
<span class="n">headers</span><span class="p">[</span><span class="s1">'X-Frame-Options'</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'DENY'</span>
<span class="n">headers</span><span class="p">[</span><span class="s1">'X-XSS-Protection'</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'1; mode=block'</span>
<span class="n">headers</span><span class="p">[</span><span class="s1">'Content-Security-Policy'</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"default-src='self'"</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Read more about <a class="reference external" href="https://www.owasp.org/index.php/List_of_useful_HTTP_headers">those headers</a>.</p>
</div>
<p>Then, in the <a class="reference internal" href="basics.html#config"><span class="std std-ref">configuration file</span></a> (or any other place that you want to enable the tool):</p>
<div class="highlight-ini"><div class="highlight"><pre><span></span><span class="k">[/]</span>
<span class="na">tools.secureheaders.on</span> <span class="o">=</span> <span class="s">True</span>
</pre></div>
</div>
<p>If you use <a class="reference internal" href="basics.html#basicsession"><span class="std std-ref">sessions</span></a> you can also enable these settings:</p>
<div class="highlight-ini"><div class="highlight"><pre><span></span><span class="k">[/]</span>
<span class="na">tools.sessions.on</span> <span class="o">=</span> <span class="s">True</span>
<span class="c1"># increase security on sessions</span>
<span class="na">tools.sessions.secure</span> <span class="o">=</span> <span class="s">True</span>
<span class="na">tools.sessions.httponly</span> <span class="o">=</span> <span class="s">True</span>
</pre></div>
</div>
<p>If you use SSL you can also enable Strict Transport Security:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span> <span class="c1"># add this to secureheaders():</span>
<span class="c1"># only add Strict-Transport headers if we're actually using SSL; see the ietf spec</span>
<span class="c1"># "An HSTS Host MUST NOT include the STS header field in HTTP responses</span>
<span class="c1"># conveyed over non-secure transport"</span>
<span class="c1"># http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-14#section-7.2</span>
<span class="k">if</span> <span class="p">(</span><span class="n">cherrypy</span><span class="o">.</span><span class="n">server</span><span class="o">.</span><span class="n">ssl_certificate</span> <span class="o">!=</span> <span class="bp">None</span> <span class="ow">and</span> <span class="n">cherrypy</span><span class="o">.</span><span class="n">server</span><span class="o">.</span><span class="n">ssl_private_key</span> <span class="o">!=</span> <span class="bp">None</span><span class="p">):</span>
<span class="n">headers</span><span class="p">[</span><span class="s1">'Strict-Transport-Security'</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'max-age=31536000'</span> <span class="c1"># one year</span>
</pre></div>
</div>
<p>Next, you should probably use <a class="reference internal" href="deploy.html#ssl"><span class="std std-ref">SSL</span></a>.</p>
</div>
<div class="section" id="multiple-http-servers-support">
<h2><a class="toc-backref" href="#id17">Multiple HTTP servers support</a><a class="headerlink" href="#multiple-http-servers-support" title="Permalink to this headline">¶</a></h2>
<p>CherryPy starts its own HTTP server whenever you start the
engine. In some cases, you may wish to host your application
on more than a single port. This is easily achieved:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">cherrypy._cpserver</span> <span class="kn">import</span> <span class="n">Server</span>
<span class="n">server</span> <span class="o">=</span> <span class="n">Server</span><span class="p">()</span>
<span class="n">server</span><span class="o">.</span><span class="n">socket_port</span> <span class="o">=</span> <span class="mi">8090</span>
<span class="n">server</span><span class="o">.</span><span class="n">subscribe</span><span class="p">()</span>
</pre></div>
</div>
<p>You can create as many <code class="xref py py-class docutils literal"><span class="pre">server</span></code>
server instances as you need, once <a class="reference internal" href="extend.html#busplugins"><span class="std std-ref">subscribed</span></a>,
they will follow the CherryPy engine’s life-cycle.</p>
</div>
<div class="section" id="wsgi-support">
<h2><a class="toc-backref" href="#id18">WSGI support</a><a class="headerlink" href="#wsgi-support" title="Permalink to this headline">¶</a></h2>
<p>CherryPy supports the WSGI interface defined in <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a>
as well as its updates in <span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3333"><strong>PEP 3333</strong></a>. It means the following:</p>
<ul class="simple">
<li>You can host a foreign WSGI application with the CherryPy server</li>
<li>A CherryPy application can be hosted by another WSGI server</li>
</ul>
<div class="section" id="make-your-cherrypy-application-a-wsgi-application">
<h3><a class="toc-backref" href="#id19">Make your CherryPy application a WSGI application</a><a class="headerlink" href="#make-your-cherrypy-application-a-wsgi-application" title="Permalink to this headline">¶</a></h3>
<p>A WSGI application can be obtained from your application as follows:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cherrypy</span>
<span class="n">wsgiapp</span> <span class="o">=</span> <span class="n">cherrypy</span><span class="o">.</span><span class="n">Application</span><span class="p">(</span><span class="n">StringGenerator</span><span class="p">(),</span> <span class="s1">'/'</span><span class="p">,</span> <span class="n">config</span><span class="o">=</span><span class="n">myconf</span><span class="p">)</span>
</pre></div>
</div>
<p>Simply use the <cite>wsgiapp</cite> instance in any WSGI-aware server.</p>
</div>
<div class="section" id="host-a-foreign-wsgi-application-in-cherrypy">
<span id="hostwsgiapp"></span><h3><a class="toc-backref" href="#id20">Host a foreign WSGI application in CherryPy</a><a class="headerlink" href="#host-a-foreign-wsgi-application-in-cherrypy" title="Permalink to this headline">¶</a></h3>
<p>Assuming you have a WSGI-aware application, you can host it
in your CherryPy server using the <code class="xref py py-meth docutils literal"><span class="pre">cherrypy.tree.graft</span></code>
facility.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">raw_wsgi_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="n">status</span> <span class="o">=</span> <span class="s1">'200 OK'</span>
<span class="n">response_headers</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">'Content-type'</span><span class="p">,</span><span class="s1">'text/plain'</span><span class="p">)]</span>
<span class="n">start_response</span><span class="p">(</span><span class="n">status</span><span class="p">,</span> <span class="n">response_headers</span><span class="p">)</span>
<span class="k">return</span> <span class="p">[</span><span class="s1">'Hello world!'</span><span class="p">]</span>
<span class="n">cherrypy</span><span class="o">.</span><span class="n">tree</span><span class="o">.</span><span class="n">graft</span><span class="p">(</span><span class="n">raw_wsgi_app</span><span class="p">,</span> <span class="s1">'/'</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition important">
<p class="first admonition-title">Important</p>
<p class="last">You cannot use tools with a foreign WSGI application.
However, you can still benefit from the
<a class="reference internal" href="extend.html#buspattern"><span class="std std-ref">CherryPy bus</span></a>.</p>
</div>
</div>
<div class="section" id="no-need-for-the-wsgi-interface">
<h3><a class="toc-backref" href="#id21">No need for the WSGI interface?</a><a class="headerlink" href="#no-need-for-the-wsgi-interface" title="Permalink to this headline">¶</a></h3>
<p>The default CherryPy HTTP server supports the WSGI interfaces
defined in <span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a> and <span class="target" id="index-4"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3333"><strong>PEP 3333</strong></a>. However, if your application
is a pure CherryPy application, you can switch to a HTTP
server that by-passes the WSGI layer altogether. It will provide
a slight performance increase.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cherrypy</span>
<span class="k">class</span> <span class="nc">Root</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="nd">@cherrypy.expose</span>
<span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">"Hello World!"</span>
<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">'__main__'</span><span class="p">:</span>
<span class="kn">from</span> <span class="nn">cherrypy._cpnative_server</span> <span class="kn">import</span> <span class="n">CPHTTPServer</span>
<span class="n">cherrypy</span><span class="o">.</span><span class="n">server</span><span class="o">.</span><span class="n">httpserver</span> <span class="o">=</span> <span class="n">CPHTTPServer</span><span class="p">(</span><span class="n">cherrypy</span><span class="o">.</span><span class="n">server</span><span class="p">)</span>
<span class="n">cherrypy</span><span class="o">.</span><span class="n">quickstart</span><span class="p">(</span><span class="n">Root</span><span class="p">(),</span> <span class="s1">'/'</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition important">
<p class="first admonition-title">Important</p>
<p class="last">Using the native server, you will not be able to
graft a WSGI application as shown in the previous section.
Doing so will result in a server error at runtime.</p>
</div>
</div>
</div>
<div class="section" id="websocket-support">
<h2><a class="toc-backref" href="#id22">WebSocket support</a><a class="headerlink" href="#websocket-support" title="Permalink to this headline">¶</a></h2>
<p><a class="reference external" href="http://tools.ietf.org/html/rfc6455">WebSocket</a>
is a recent application protocol that came to life
from the HTML5 working-group in response to the needs for
bi-directional communication. Various hacks had been proposed
such as Comet, polling, etc.</p>
<p>WebSocket is a socket that starts its life from a HTTP upgrade request.
Once the upgrade is performed, the underlying socket is
kept opened but not used in a HTTP context any longer.
Instead, both connected endpoints may use the socket
to push data to the other end.</p>
<p>CherryPy itself does not support WebSocket, but the feature
is provided by an external library called
<a class="reference external" href="https://github.com/Lawouach/WebSocket-for-Python">ws4py</a>.</p>
</div>
<div class="section" id="database-support">
<h2><a class="toc-backref" href="#id23">Database support</a><a class="headerlink" href="#database-support" title="Permalink to this headline">¶</a></h2>
<p>CherryPy does not bundle any database access but its architecture
makes it easy to integrate common database interfaces such as
the DB-API specified in <span class="target" id="index-5"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a>. Alternatively, you can also
use an <a class="reference external" href="en.wikipedia.org/wiki/Object-relational_mapping">ORM</a>
such as <a class="reference external" href="http://sqlalchemy.readthedocs.org">SQLAlchemy</a>
or <a class="reference external" href="https://pypi.python.org/pypi/SQLObject/">SQLObject</a>.</p>
<p>You will find <a class="reference external" href="https://bitbucket.org/Lawouach/cherrypy-recipes/src/tip/web/database/sql_alchemy/">here</a>
a recipe on how integrating SQLAlchemy using a mix of
<a class="reference internal" href="extend.html#busplugins"><span class="std std-ref">plugins</span></a> and <a class="reference internal" href="extend.html#tools"><span class="std std-ref">tools</span></a>.</p>
</div>
<div class="section" id="html-templating-support">
<h2><a class="toc-backref" href="#id24">HTML Templating support</a><a class="headerlink" href="#html-templating-support" title="Permalink to this headline">¶</a></h2>
<p>CherryPy does not provide any HTML template but its architecture
makes it easy to integrate one. Popular ones are <a class="reference external" href="http://www.makotemplates.org">Mako</a>
or <a class="reference external" href="http://jinja.pocoo.org/docs/">Jinja2</a>.</p>
<p>You will find <a class="reference external" href="https://bitbucket.org/Lawouach/cherrypy-recipes/src/tip/web/templating/">here</a>
a recipe on how to integrate them using a mix
<a class="reference internal" href="extend.html#busplugins"><span class="std std-ref">plugins</span></a> and <a class="reference internal" href="extend.html#tools"><span class="std std-ref">tools</span></a>.</p>
</div>
<div class="section" id="testing-your-application">
<h2><a class="toc-backref" href="#id25">Testing your application</a><a class="headerlink" href="#testing-your-application" title="Permalink to this headline">¶</a></h2>
<p>Web applications, like any other kind of code, must be tested. CherryPy provides
a <code class="xref py py-class docutils literal"><span class="pre">helper</span> <span class="pre">class</span></code> to ease writing
functional tests.</p>
<p>Here is a simple example for a basic echo application:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cherrypy</span>
<span class="kn">from</span> <span class="nn">cherrypy.test</span> <span class="kn">import</span> <span class="n">helper</span>
<span class="k">class</span> <span class="nc">SimpleCPTest</span><span class="p">(</span><span class="n">helper</span><span class="o">.</span><span class="n">CPWebCase</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">setup_server</span><span class="p">():</span>
<span class="k">class</span> <span class="nc">Root</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="nd">@cherrypy.expose</span>
<span class="k">def</span> <span class="nf">echo</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">message</span><span class="p">):</span>
<span class="k">return</span> <span class="n">message</span>
<span class="n">cherrypy</span><span class="o">.</span><span class="n">tree</span><span class="o">.</span><span class="n">mount</span><span class="p">(</span><span class="n">Root</span><span class="p">())</span>
<span class="n">setup_server</span> <span class="o">=</span> <span class="nb">staticmethod</span><span class="p">(</span><span class="n">setup_server</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_message_should_be_returned_as_is</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">getPage</span><span class="p">(</span><span class="s2">"/echo?message=Hello%20world"</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertStatus</span><span class="p">(</span><span class="s1">'200 OK'</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertHeader</span><span class="p">(</span><span class="s1">'Content-Type'</span><span class="p">,</span> <span class="s1">'text/html;charset=utf-8'</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertBody</span><span class="p">(</span><span class="s1">'Hello world'</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_non_utf8_message_will_fail</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""</span>
<span class="sd"> CherryPy defaults to decode the query-string</span>
<span class="sd"> using UTF-8, trying to send a query-string with</span>
<span class="sd"> a different encoding will raise a 404 since</span>
<span class="sd"> it considers it's a different URL.</span>
<span class="sd"> """</span>
<span class="bp">self</span><span class="o">.</span><span class="n">getPage</span><span class="p">(</span><span class="s2">"/echo?message=A+bient</span><span class="si">%F</span><span class="s2">4t"</span><span class="p">,</span>
<span class="n">headers</span><span class="o">=</span><span class="p">[</span>
<span class="p">(</span><span class="s1">'Accept-Charset'</span><span class="p">,</span> <span class="s1">'ISO-8859-1,utf-8'</span><span class="p">),</span>
<span class="p">(</span><span class="s1">'Content-Type'</span><span class="p">,</span> <span class="s1">'text/html;charset=ISO-8859-1'</span><span class="p">)</span>
<span class="p">]</span>
<span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertStatus</span><span class="p">(</span><span class="s1">'404 Not Found'</span><span class="p">)</span>
</pre></div>
</div>
<p>As you can see the, test inherits from that helper class. You should
setup your application and mount it as per-usual. Then, define your various
tests and call the helper <code class="xref py py-meth docutils literal"><span class="pre">getPage()</span></code>
method to perform a request. Simply use the various specialized
assert* methods to validate your workflow and data.</p>
<p>You can then run the test using <a class="reference external" href="http://pytest.org/latest/">py.test</a> as follows:</p>
<div class="highlight-bash"><div class="highlight"><pre><span></span>$ py.test -s test_echo_app.py
</pre></div>
</div>
<p>The <code class="docutils literal"><span class="pre">-s</span></code> is necessary because the CherryPy class also wraps stdin and stdout.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Although they are written using the typical pattern the
<code class="xref py py-mod docutils literal"><span class="pre">unittest</span></code> module supports, they are not bare unit tests.
Indeed, a whole CherryPy stack is started for you and runs your application.
If you want to really unit test your CherryPy application, meaning without
having to start a server, you may want to have a look at
this <a class="reference external" href="https://bitbucket.org/Lawouach/cherrypy-recipes/src/tip/testing/unit/serverless/">recipe</a>.</p>
</div>
</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="#">Advanced</a><ul>
<li><a class="reference internal" href="#set-aliases-to-page-handlers">Set aliases to page handlers</a></li>
<li><a class="reference internal" href="#restful-style-dispatching">RESTful-style dispatching</a><ul>
<li><a class="reference internal" href="#the-special-cp-dispatch-method">The special _cp_dispatch method</a></li>
<li><a class="reference internal" href="#the-popargs-decorator">The popargs decorator</a></li>
</ul>
</li>
<li><a class="reference internal" href="#error-handling">Error handling</a></li>
<li><a class="reference internal" href="#streaming-the-response-body">Streaming the response body</a><ul>
<li><a class="reference internal" href="#the-normal-cherrypy-response-process">The “normal” CherryPy response process</a></li>
<li><a class="reference internal" href="#how-streaming-output-works-with-cherrypy">How “streaming output” works with CherryPy</a></li>
</ul>
</li>
<li><a class="reference internal" href="#response-timeouts">Response timeouts</a><ul>
<li><a class="reference internal" href="#timeout-monitor">Timeout Monitor</a></li>
</ul>
</li>
<li><a class="reference internal" href="#deal-with-signals">Deal with signals</a><ul>
<li><a class="reference internal" href="#windows-console-events">Windows Console Events</a></li>
</ul>
</li>
<li><a class="reference internal" href="#securing-your-server">Securing your server</a></li>
<li><a class="reference internal" href="#multiple-http-servers-support">Multiple HTTP servers support</a></li>
<li><a class="reference internal" href="#wsgi-support">WSGI support</a><ul>
<li><a class="reference internal" href="#make-your-cherrypy-application-a-wsgi-application">Make your CherryPy application a WSGI application</a></li>
<li><a class="reference internal" href="#host-a-foreign-wsgi-application-in-cherrypy">Host a foreign WSGI application in CherryPy</a></li>
<li><a class="reference internal" href="#no-need-for-the-wsgi-interface">No need for the WSGI interface?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#websocket-support">WebSocket support</a></li>
<li><a class="reference internal" href="#database-support">Database support</a></li>
<li><a class="reference internal" href="#html-templating-support">HTML Templating support</a></li>
<li><a class="reference internal" href="#testing-your-application">Testing your application</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="basics.html"
title="previous chapter">Basics</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="config.html"
title="next chapter">Configure</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/advanced.rst.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="related" role="navigation" aria-label="related navigation">
<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="config.html" title="Configure"
>next</a> |</li>
<li class="right" >
<a href="basics.html" title="Basics"
>previous</a> |</li>
<li class="nav-item nav-item-0"><a href="index.html">CherryPy 8.9.1 documentation</a> »</li>
</ul>
</div>
<div class="footer" role="contentinfo">
© Copyright 2001-2018 CherryPy Team.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.6.
</div>
</body>
</html>
|