/usr/share/doc/python-cherrypy3-doc/html/tutorials.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 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 | <!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>Tutorials — 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="Basics" href="basics.html" />
<link rel="prev" title="Installation" href="install.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="basics.html" title="Basics"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="install.html" title="Installation"
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="tutorials">
<span id="id1"></span><h1><a class="toc-backref" href="#id2">Tutorials</a><a class="headerlink" href="#tutorials" title="Permalink to this headline">¶</a></h1>
<p>This tutorial will walk you through basic but complete CherryPy applications
that will show you common concepts as well as slightly more advanced ones.</p>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#tutorials" id="id2">Tutorials</a><ul>
<li><a class="reference internal" href="#tutorial-1-a-basic-web-application" id="id3">Tutorial 1: A basic web application</a></li>
<li><a class="reference internal" href="#tutorial-2-different-urls-lead-to-different-functions" id="id4">Tutorial 2: Different URLs lead to different functions</a></li>
<li><a class="reference internal" href="#tutorial-3-my-urls-have-parameters" id="id5">Tutorial 3: My URLs have parameters</a></li>
<li><a class="reference internal" href="#tutorial-4-submit-this-form" id="id6">Tutorial 4: Submit this form</a></li>
<li><a class="reference internal" href="#tutorial-5-track-my-end-user-s-activity" id="id7">Tutorial 5: Track my end-user’s activity</a></li>
<li><a class="reference internal" href="#tutorial-6-what-about-my-javascripts-css-and-images" id="id8">Tutorial 6: What about my javascripts, CSS and images?</a></li>
<li><a class="reference internal" href="#tutorial-7-give-us-a-rest" id="id9">Tutorial 7: Give us a REST</a></li>
<li><a class="reference internal" href="#tutorial-8-make-it-smoother-with-ajax" id="id10">Tutorial 8: Make it smoother with Ajax</a></li>
<li><a class="reference internal" href="#tutorial-9-data-is-all-my-life" id="id11">Tutorial 9: Data is all my life</a></li>
<li><a class="reference internal" href="#tutorial-10-make-it-a-modern-single-page-application-with-react-js" id="id12">Tutorial 10: Make it a modern single-page application with React.js</a></li>
<li><a class="reference internal" href="#tutorial-11-organize-my-code" id="id13">Tutorial 11: Organize my code</a><ul>
<li><a class="reference internal" href="#dispatchers" id="id14">Dispatchers</a></li>
<li><a class="reference internal" href="#tools" id="id15">Tools</a></li>
<li><a class="reference internal" href="#plugins" id="id16">Plugins</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="section" id="tutorial-1-a-basic-web-application">
<h2><a class="toc-backref" href="#id3">Tutorial 1: A basic web application</a><a class="headerlink" href="#tutorial-1-a-basic-web-application" title="Permalink to this headline">¶</a></h2>
<p>The following example demonstrates the most basic application
you could write with CherryPy. It starts a server and hosts
an application that will be served at request reaching
<a class="reference external" href="http://127.0.0.1:8080/">http://127.0.0.1:8080/</a></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</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cherrypy</span>
<span class="k">class</span> <span class="nc">HelloWorld</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="n">cherrypy</span><span class="o">.</span><span class="n">quickstart</span><span class="p">(</span><span class="n">HelloWorld</span><span class="p">())</span>
</pre></div>
</td></tr></table></div>
<p>Store this code snippet into a file named <cite>tut01.py</cite> and
execute it as follows:</p>
<div class="highlight-bash"><div class="highlight"><pre><span></span>$ python tut01.py
</pre></div>
</div>
<p>This will display something along the following:</p>
<div class="highlight-text"><table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10
11</pre></div></td><td class="code"><div class="highlight"><pre><span></span>[24/Feb/2014:21:01:46] ENGINE Listening for SIGHUP.
[24/Feb/2014:21:01:46] ENGINE Listening for SIGTERM.
[24/Feb/2014:21:01:46] ENGINE Listening for SIGUSR1.
[24/Feb/2014:21:01:46] ENGINE Bus STARTING
CherryPy Checker:
The Application mounted at '' has an empty config.
[24/Feb/2014:21:01:46] ENGINE Started monitor thread 'Autoreloader'.
[24/Feb/2014:21:01:46] ENGINE Started monitor thread '_TimeoutMonitor'.
[24/Feb/2014:21:01:46] ENGINE Serving on http://127.0.0.1:8080
[24/Feb/2014:21:01:46] ENGINE Bus STARTED
</pre></div>
</td></tr></table></div>
<p>This tells you several things. The first three lines indicate
the server will handle <code class="xref py py-mod docutils literal"><span class="pre">signal</span></code> for you. The next line tells you
the current state of the server, as that
point it is in <cite>STARTING</cite> stage. Then, you are notified your
application has no specific configuration set to it.
Next, the server starts a couple of internal utilities that
we will explain later. Finally, the server indicates it is now
ready to accept incoming communications as it listens on
the address <cite>127.0.0.1:8080</cite>. In other words, at that stage your
application is ready to be used.</p>
<p>Before moving on, let’s discuss the message
regarding the lack of configuration. By default, CherryPy has
a feature which will review the syntax correctness of settings
you could provide to configure the application. When none are
provided, a warning message is thus displayed in the logs. That
log is harmless and will not prevent CherryPy from working. You
can refer to <a class="reference internal" href="basics.html#perappconf"><span class="std std-ref">the documentation above</span></a> to
understand how to set the configuration.</p>
</div>
<div class="section" id="tutorial-2-different-urls-lead-to-different-functions">
<h2><a class="toc-backref" href="#id4">Tutorial 2: Different URLs lead to different functions</a><a class="headerlink" href="#tutorial-2-different-urls-lead-to-different-functions" title="Permalink to this headline">¶</a></h2>
<p>Your applications will obviously handle more than a single URL.
Let’s imagine you have an application that generates a random
string each time it is called:</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</pre></div></td><td class="code"><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="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="nd">@cherrypy.expose</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="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="mi">8</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>
</td></tr></table></div>
<p>Save this into a file named <cite>tut02.py</cite> and run it as follows:</p>
<div class="highlight-bash"><div class="highlight"><pre><span></span>$ python tut02.py
</pre></div>
</div>
<p>Go now to <a class="reference external" href="http://localhost:8080/generate">http://localhost:8080/generate</a> and your browser
will display a random string.</p>
<p>Let’s take a minute to decompose what’s happening here. This is the
URL that you have typed into your browser: <a class="reference external" href="http://localhost:8080/generate">http://localhost:8080/generate</a></p>
<p>This URL contains various parts:</p>
<ul class="simple">
<li><cite>http://</cite> which roughly indicates it’s a URL using the HTTP protocol (see <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2616.html"><strong>RFC 2616</strong></a>).</li>
<li><cite>localhost:8080</cite> is the server’s address. It’s made of a hostname and a port.</li>
<li><cite>/generate</cite> which is the path segment of the URL. This is what CherryPy uses to
locate an <a class="reference internal" href="glossary.html#term-exposed"><span class="xref std std-term">exposed</span></a> function or method to respond.</li>
</ul>
<p>Here CherryPy uses the <cite>index()</cite> method to handle <cite>/</cite> and the
<cite>generate()</cite> method to handle <cite>/generate</cite></p>
</div>
<div class="section" id="tutorial-3-my-urls-have-parameters">
<span id="tut03"></span><h2><a class="toc-backref" href="#id5">Tutorial 3: My URLs have parameters</a><a class="headerlink" href="#tutorial-3-my-urls-have-parameters" title="Permalink to this headline">¶</a></h2>
<p>In the previous tutorial, we have seen how to create an application
that could generate a random string. Let’s now assume you wish
to indicate the length of that string dynamically.</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</pre></div></td><td class="code"><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="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="nd">@cherrypy.expose</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>
</td></tr></table></div>
<p>Save this into a file named <cite>tut03.py</cite> and run it as follows:</p>
<div class="highlight-bash"><div class="highlight"><pre><span></span>$ python tut03.py
</pre></div>
</div>
<p>Go now to <a class="reference external" href="http://localhost:8080/generate?length=16">http://localhost:8080/generate?length=16</a> and your browser
will display a generated string of length 16. Notice how
we benefit from Python’s default arguments’ values to support
URLs such as <a class="reference external" href="http://localhost:8080/generate">http://localhost:8080/generate</a> still.</p>
<p>In a URL such as this one, the section after <cite>?</cite> is called a
query-string. Traditionally, the query-string is used to
contextualize the URL by passing a set of (key, value) pairs. The
format for those pairs is <cite>key=value</cite>. Each pair being
separated by a <cite>&</cite> character.</p>
<p>Notice how we have to convert the given <cite>length</cite> value to
an integer. Indeed, values are sent out from the client
to our server as strings.</p>
<p>Much like CherryPy maps URL path segments to exposed functions,
query-string keys are mapped to those exposed function parameters.</p>
</div>
<div class="section" id="tutorial-4-submit-this-form">
<span id="tut04"></span><h2><a class="toc-backref" href="#id6">Tutorial 4: Submit this form</a><a class="headerlink" href="#tutorial-4-submit-this-form" title="Permalink to this headline">¶</a></h2>
<p>CherryPy is a web framework upon which you build web applications.
The most traditional shape taken by applications is through
an HTML user-interface speaking to your CherryPy server.</p>
<p>Let’s see how to handle HTML forms via the following
example.</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
23
24
25
26</pre></div></td><td class="code"><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="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">"""<html></span>
<span class="s2"> <head></head></span>
<span class="s2"> <body></span>
<span class="s2"> <form method="get" action="generate"></span>
<span class="s2"> <input type="text" value="8" name="length" /></span>
<span class="s2"> <button type="submit">Give it now!</button></span>
<span class="s2"> </form></span>
<span class="s2"> </body></span>
<span class="s2"> </html>"""</span>
<span class="nd">@cherrypy.expose</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>
</td></tr></table></div>
<p>Save this into a file named <cite>tut04.py</cite> and run it as follows:</p>
<div class="highlight-bash"><div class="highlight"><pre><span></span>$ python tut04.py
</pre></div>
</div>
<p>Go now to <a class="reference external" href="http://localhost:8080/">http://localhost:8080/</a> and your browser and this will
display a simple input field to indicate the length of the string
you want to generate.</p>
<p>Notice that in this example, the form uses the <cite>GET</cite> method and
when you pressed the <cite>Give it now!</cite> button, the form is sent using the
same URL as in the <a class="reference internal" href="#tut03"><span class="std std-ref">previous</span></a> tutorial. HTML forms also support the
<cite>POST</cite> method, in that case the query-string is not appended to the
URL but it sent as the body of the client’s request to the server.
However, this would not change your application’s exposed method because
CherryPy handles both the same way and uses the exposed’s handler
parameters to deal with the query-string (key, value) pairs.</p>
</div>
<div class="section" id="tutorial-5-track-my-end-user-s-activity">
<span id="tut05"></span><h2><a class="toc-backref" href="#id7">Tutorial 5: Track my end-user’s activity</a><a class="headerlink" href="#tutorial-5-track-my-end-user-s-activity" title="Permalink to this headline">¶</a></h2>
<p>It’s not uncommon that an application needs to follow the
user’s activity for a while. The usual mechanism is to use
a <a class="reference external" href="http://en.wikipedia.org/wiki/Session_(computer_science)#HTTP_session_token">session identifier</a>
that is carried during the conversation between the user and
your application.</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
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37</pre></div></td><td class="code"><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="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">"""<html></span>
<span class="s2"> <head></head></span>
<span class="s2"> <body></span>
<span class="s2"> <form method="get" action="generate"></span>
<span class="s2"> <input type="text" value="8" name="length" /></span>
<span class="s2"> <button type="submit">Give it now!</button></span>
<span class="s2"> </form></span>
<span class="s2"> </body></span>
<span class="s2"> </html>"""</span>
<span class="nd">@cherrypy.expose</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="n">some_string</span> <span class="o">=</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="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">'mystring'</span><span class="p">]</span> <span class="o">=</span> <span class="n">some_string</span>
<span class="k">return</span> <span class="n">some_string</span>
<span class="nd">@cherrypy.expose</span>
<span class="k">def</span> <span class="nf">display</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">'mystring'</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">conf</span> <span class="o">=</span> <span class="p">{</span>
<span class="s1">'/'</span><span class="p">:</span> <span class="p">{</span>
<span class="s1">'tools.sessions.on'</span><span class="p">:</span> <span class="bp">True</span>
<span class="p">}</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> <span class="s1">'/'</span><span class="p">,</span> <span class="n">conf</span><span class="p">)</span>
</pre></div>
</td></tr></table></div>
<p>Save this into a file named <cite>tut05.py</cite> and run it as follows:</p>
<div class="highlight-bash"><div class="highlight"><pre><span></span>$ python tut05.py
</pre></div>
</div>
<p>In this example, we generate the string as in the
<a class="reference internal" href="#tut04"><span class="std std-ref">previous</span></a> tutorial but also store it in the current
session. If you go to <a class="reference external" href="http://localhost:8080/">http://localhost:8080/</a>, generate a
random string, then go to <a class="reference external" href="http://localhost:8080/display">http://localhost:8080/display</a>, you
will see the string you just generated.</p>
<p>The lines 30-34 show you how to enable the session support
in your CherryPy application. By default, CherryPy will save
sessions in the process’s memory. It supports more persistent
<a class="reference internal" href="basics.html#basicsession"><span class="std std-ref">backends</span></a> as well.</p>
</div>
<div class="section" id="tutorial-6-what-about-my-javascripts-css-and-images">
<h2><a class="toc-backref" href="#id8">Tutorial 6: What about my javascripts, CSS and images?</a><a class="headerlink" href="#tutorial-6-what-about-my-javascripts-css-and-images" title="Permalink to this headline">¶</a></h2>
<p>Web applications are usually also made of static content such
as javascript, CSS files or images. CherryPy provides support
to serve static content to end-users.</p>
<p>Let’s assume, you want to associate a stylesheet with your
application to display a blue background color (why not?).</p>
<p>First, save the following stylesheet into a file named <cite>style.css</cite>
and stored into a local directory <cite>public/css</cite>.</p>
<div class="highlight-css"><table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="nt">body</span> <span class="p">{</span>
<span class="k">background-color</span><span class="p">:</span> <span class="kc">blue</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</td></tr></table></div>
<p>Now let’s update the HTML code so that we link to the stylesheet
using the <a class="reference external" href="http://localhost:8080/static/css/style.css">http://localhost:8080/static/css/style.css</a> URL.</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
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span><span class="o">,</span> <span class="nn">os.path</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="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">"""<html></span>
<span class="s2"> <head></span>
<span class="s2"> <link href="/static/css/style.css" rel="stylesheet"></span>
<span class="s2"> </head></span>
<span class="s2"> <body></span>
<span class="s2"> <form method="get" action="generate"></span>
<span class="s2"> <input type="text" value="8" name="length" /></span>
<span class="s2"> <button type="submit">Give it now!</button></span>
<span class="s2"> </form></span>
<span class="s2"> </body></span>
<span class="s2"> </html>"""</span>
<span class="nd">@cherrypy.expose</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="n">some_string</span> <span class="o">=</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="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">'mystring'</span><span class="p">]</span> <span class="o">=</span> <span class="n">some_string</span>
<span class="k">return</span> <span class="n">some_string</span>
<span class="nd">@cherrypy.expose</span>
<span class="k">def</span> <span class="nf">display</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">'mystring'</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">conf</span> <span class="o">=</span> <span class="p">{</span>
<span class="s1">'/'</span><span class="p">:</span> <span class="p">{</span>
<span class="s1">'tools.sessions.on'</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
<span class="s1">'tools.staticdir.root'</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">abspath</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">getcwd</span><span class="p">())</span>
<span class="p">},</span>
<span class="s1">'/static'</span><span class="p">:</span> <span class="p">{</span>
<span class="s1">'tools.staticdir.on'</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
<span class="s1">'tools.staticdir.dir'</span><span class="p">:</span> <span class="s1">'./public'</span>
<span class="p">}</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> <span class="s1">'/'</span><span class="p">,</span> <span class="n">conf</span><span class="p">)</span>
</pre></div>
</td></tr></table></div>
<p>Save this into a file named <cite>tut06.py</cite> and run it as follows:</p>
<div class="highlight-bash"><div class="highlight"><pre><span></span>$ python tut06.py
</pre></div>
</div>
<p>Going to <a class="reference external" href="http://localhost:8080/">http://localhost:8080/</a>, you should be greeted by a flashy blue color.</p>
<p>CherryPy provides support to serve a single file or a complete
directory structure. Most of the time, this is what you’ll end
up doing so this is what the code above demonstrates. First, we
indicate the <cite>root</cite> directory of all of our static content. This
must be an absolute path for security reason. CherryPy will
complain if you provide only relative paths when looking for a
match to your URLs.</p>
<p>Then we indicate that all URLs which path segment starts with <cite>/static</cite>
will be served as static content. We map that URL to the <cite>public</cite>
directory, a direct child of the <cite>root</cite> directory. The entire
sub-tree of the <cite>public</cite> directory will be served as static content.
CherryPy will map URLs to path within that directory. This is why
<cite>/static/css/style.css</cite> is found in <cite>public/css/style.css</cite>.</p>
</div>
<div class="section" id="tutorial-7-give-us-a-rest">
<h2><a class="toc-backref" href="#id9">Tutorial 7: Give us a REST</a><a class="headerlink" href="#tutorial-7-give-us-a-rest" title="Permalink to this headline">¶</a></h2>
<p>It’s not unusual nowadays that web applications expose some sort
of datamodel or computation functions. Without going into
its details, one strategy is to follow the <a class="reference external" href="http://www.ibm.com/developerworks/library/ws-restful/index.html">REST principles
edicted by Roy T. Fielding</a>.</p>
<p>Roughly speaking, it assumes that you can identify a resource
and that you can address that resource through that identifier.</p>
<p>“What for?” you may ask. Well, mostly, these principles are there
to ensure that you decouple, as best as you can, the entities
your application expose from the way they are manipulated or
consumed. To embrace this point of view, developers will
usually design a web API that expose pairs of <cite>(URL, HTTP method, data, constraints)</cite>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">You will often hear REST and web API together. The former is
one strategy to provide the latter. This tutorial will not go
deeper in that whole web API concept as it’s a much more
engaging subject, but you ought to read more about it online.</p>
</div>
<p>Lets go through a small example of a very basic web API
mildly following REST principles.</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
23
24
25
26
27
28
29
30
31
32
33
34
35</pre></div></td><td class="code"><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="nd">@cherrypy.expose</span>
<span class="k">class</span> <span class="nc">StringGeneratorWebService</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="nd">@cherrypy.tools.accept</span><span class="p">(</span><span class="n">media</span><span class="o">=</span><span class="s1">'text/plain'</span><span class="p">)</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="k">return</span> <span class="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">'mystring'</span><span class="p">]</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="n">length</span><span class="o">=</span><span class="mi">8</span><span class="p">):</span>
<span class="n">some_string</span> <span class="o">=</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="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">'mystring'</span><span class="p">]</span> <span class="o">=</span> <span class="n">some_string</span>
<span class="k">return</span> <span class="n">some_string</span>
<span class="k">def</span> <span class="nf">PUT</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">another_string</span><span class="p">):</span>
<span class="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">'mystring'</span><span class="p">]</span> <span class="o">=</span> <span class="n">another_string</span>
<span class="k">def</span> <span class="nf">DELETE</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">session</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'mystring'</span><span class="p">,</span> <span class="bp">None</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">conf</span> <span class="o">=</span> <span class="p">{</span>
<span class="s1">'/'</span><span class="p">:</span> <span class="p">{</span>
<span class="s1">'request.dispatch'</span><span class="p">:</span> <span class="n">cherrypy</span><span class="o">.</span><span class="n">dispatch</span><span class="o">.</span><span class="n">MethodDispatcher</span><span class="p">(),</span>
<span class="s1">'tools.sessions.on'</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
<span class="s1">'tools.response_headers.on'</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
<span class="s1">'tools.response_headers.headers'</span><span class="p">:</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="p">}</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">StringGeneratorWebService</span><span class="p">(),</span> <span class="s1">'/'</span><span class="p">,</span> <span class="n">conf</span><span class="p">)</span>
</pre></div>
</td></tr></table></div>
<p>Save this into a file named <cite>tut07.py</cite> and run it as follows:</p>
<div class="highlight-bash"><div class="highlight"><pre><span></span>$ python tut07.py
</pre></div>
</div>
<p>Before we see it in action, let’s explain a few things. Until now,
CherryPy was creating a tree of exposed methods that were used to
match URLs. In the case of our web API, we want to stress the role
played by the actual requests’ HTTP methods. So we created
methods that are named after them and they are all exposed at once
by decorating the class itself with <cite>cherrypy.expose</cite>.</p>
<p>However, we must then switch from the default mechanism of matching
URLs to method for one that is aware of the whole HTTP method
shenanigan. This is what goes on line 27 where we create
a <code class="xref py py-class docutils literal"><span class="pre">MethodDispatcher</span></code> instance.</p>
<p>Then we force the responses <cite>content-type</cite> to be <cite>text/plain</cite> and
we finally ensure that <cite>GET</cite> requests will only be responded to clients
that accept that <cite>content-type</cite> by having a <cite>Accept: text/plain</cite>
header set in their request. However, we do this only for that
HTTP method as it wouldn’t have much meaning on the other methods.</p>
<p>For the purpose of this tutorial, we will be using a Python client
rather than your browser as we wouldn’t be able to actually try
our web API otherwise.</p>
<p>Please install <a class="reference external" href="http://www.python-requests.org/en/latest/">requests</a>
through the following command:</p>
<div class="highlight-bash"><div class="highlight"><pre><span></span>$ pip install requests
</pre></div>
</div>
<p>Then fire up a Python terminal and try the following commands:</p>
<div class="highlight-pycon"><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="gp">>>> </span><span class="kn">import</span> <span class="nn">requests</span>
<span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">Session</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">'http://127.0.0.1:8080/'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">status_code</span>
<span class="go">500</span>
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s1">'http://127.0.0.1:8080/'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="n">r</span><span class="o">.</span><span class="n">text</span>
<span class="go">(200, u'04A92138')</span>
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">'http://127.0.0.1:8080/'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="n">r</span><span class="o">.</span><span class="n">text</span>
<span class="go">(200, u'04A92138')</span>
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">'http://127.0.0.1:8080/'</span><span class="p">,</span> <span class="n">headers</span><span class="o">=</span><span class="p">{</span><span class="s1">'Accept'</span><span class="p">:</span> <span class="s1">'application/json'</span><span class="p">})</span>
<span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">status_code</span>
<span class="go">406</span>
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="s1">'http://127.0.0.1:8080/'</span><span class="p">,</span> <span class="n">params</span><span class="o">=</span><span class="p">{</span><span class="s1">'another_string'</span><span class="p">:</span> <span class="s1">'hello'</span><span class="p">})</span>
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">'http://127.0.0.1:8080/'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="n">r</span><span class="o">.</span><span class="n">text</span>
<span class="go">(200, u'hello')</span>
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="s1">'http://127.0.0.1:8080/'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">'http://127.0.0.1:8080/'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">r</span><span class="o">.</span><span class="n">status_code</span>
<span class="go">500</span>
</pre></div>
</td></tr></table></div>
<p>The first and last <cite>500</cite> responses stem from the fact that, in
the first case, we haven’t yet generated a string through <cite>POST</cite> and,
on the latter case, that it doesn’t exist after we’ve deleted it.</p>
<p>Lines 12-14 show you how the application reacted when our client requested
the generated string as a JSON format. Since we configured the
web API to only support plain text, it returns the appropriate
<a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.7">HTTP error code</a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">We use the <a class="reference external" href="http://www.python-requests.org/en/latest/user/advanced/#session-objects">Session</a>
interface of <cite>requests</cite> so that it takes care of carrying the
session id stored in the request cookie in each subsequent
request. That is handy.</p>
</div>
<div class="admonition important">
<p class="first admonition-title">Important</p>
<p>It’s all about RESTful URLs these days, isn’t it?</p>
<p>It is likely your URL will be made of dynamic parts that you
will not be able to match to page handlers. For example,
<code class="docutils literal"><span class="pre">/library/12/book/15</span></code> cannot be directly handled by the
default CherryPy dispatcher since the segments <code class="docutils literal"><span class="pre">12</span></code> and
<code class="docutils literal"><span class="pre">15</span></code> will not be matched to any Python callable.</p>
<p class="last">This can be easily workaround with two handy CherryPy features
explained in the <a class="reference internal" href="advanced.html#restful"><span class="std std-ref">advanced section</span></a>.</p>
</div>
</div>
<div class="section" id="tutorial-8-make-it-smoother-with-ajax">
<span id="tut08"></span><h2><a class="toc-backref" href="#id10">Tutorial 8: Make it smoother with Ajax</a><a class="headerlink" href="#tutorial-8-make-it-smoother-with-ajax" title="Permalink to this headline">¶</a></h2>
<p>In the recent years, web applications have moved away from the
simple pattern of “HTML forms + refresh the whole page”. This
traditional scheme still works very well but users have become used
to web applications that don’t refresh the entire page.
Broadly speaking, web applications carry code performed
client-side that can speak with the backend without having to
refresh the whole page.</p>
<p>This tutorial will involve a little more code this time around. First,
let’s see our CSS stylesheet located in <cite>public/css/style.css</cite>.</p>
<div class="highlight-css"><table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5
6
7</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="nt">body</span> <span class="p">{</span>
<span class="k">background-color</span><span class="p">:</span> <span class="kc">blue</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">#</span><span class="nn">the-string</span> <span class="p">{</span>
<span class="k">display</span><span class="p">:</span> <span class="kc">none</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</td></tr></table></div>
<p>We’re adding a simple rule about the element that will display
the generated string. By default, let’s not show it up.
Save the following HTML code into a file named <cite>index.html</cite>.</p>
<div class="highlight-html"><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
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</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="cp"><!DOCTYPE html></span>
<span class="p"><</span><span class="nt">html</span><span class="p">></span>
<span class="p"><</span><span class="nt">head</span><span class="p">></span>
<span class="p"><</span><span class="nt">link</span> <span class="na">href</span><span class="o">=</span><span class="s">"/static/css/style.css"</span> <span class="na">rel</span><span class="o">=</span><span class="s">"stylesheet"</span><span class="p">></span>
<span class="p"><</span><span class="nt">script</span> <span class="na">src</span><span class="o">=</span><span class="s">"http://code.jquery.com/jquery-2.0.3.min.js"</span><span class="p">></</span><span class="nt">script</span><span class="p">></span>
<span class="p"><</span><span class="nt">script</span> <span class="na">type</span><span class="o">=</span><span class="s">"text/javascript"</span><span class="p">></span>
<span class="nx">$</span><span class="p">(</span><span class="nb">document</span><span class="p">).</span><span class="nx">ready</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">$</span><span class="p">(</span><span class="s2">"#generate-string"</span><span class="p">).</span><span class="nx">click</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">$</span><span class="p">.</span><span class="nx">post</span><span class="p">(</span><span class="s2">"/generator"</span><span class="p">,</span> <span class="p">{</span><span class="s2">"length"</span><span class="o">:</span> <span class="nx">$</span><span class="p">(</span><span class="s2">"input[name='length']"</span><span class="p">).</span><span class="nx">val</span><span class="p">()})</span>
<span class="p">.</span><span class="nx">done</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">string</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">$</span><span class="p">(</span><span class="s2">"#the-string"</span><span class="p">).</span><span class="nx">show</span><span class="p">();</span>
<span class="nx">$</span><span class="p">(</span><span class="s2">"#the-string input"</span><span class="p">).</span><span class="nx">val</span><span class="p">(</span><span class="nx">string</span><span class="p">);</span>
<span class="p">});</span>
<span class="nx">e</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
<span class="p">});</span>
<span class="nx">$</span><span class="p">(</span><span class="s2">"#replace-string"</span><span class="p">).</span><span class="nx">click</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">$</span><span class="p">.</span><span class="nx">ajax</span><span class="p">({</span>
<span class="nx">type</span><span class="o">:</span> <span class="s2">"PUT"</span><span class="p">,</span>
<span class="nx">url</span><span class="o">:</span> <span class="s2">"/generator"</span><span class="p">,</span>
<span class="nx">data</span><span class="o">:</span> <span class="p">{</span><span class="s2">"another_string"</span><span class="o">:</span> <span class="nx">$</span><span class="p">(</span><span class="s2">"#the-string input"</span><span class="p">).</span><span class="nx">val</span><span class="p">()}</span>
<span class="p">})</span>
<span class="p">.</span><span class="nx">done</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">alert</span><span class="p">(</span><span class="s2">"Replaced!"</span><span class="p">);</span>
<span class="p">});</span>
<span class="nx">e</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
<span class="p">});</span>
<span class="nx">$</span><span class="p">(</span><span class="s2">"#delete-string"</span><span class="p">).</span><span class="nx">click</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">$</span><span class="p">.</span><span class="nx">ajax</span><span class="p">({</span>
<span class="nx">type</span><span class="o">:</span> <span class="s2">"DELETE"</span><span class="p">,</span>
<span class="nx">url</span><span class="o">:</span> <span class="s2">"/generator"</span>
<span class="p">})</span>
<span class="p">.</span><span class="nx">done</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">$</span><span class="p">(</span><span class="s2">"#the-string"</span><span class="p">).</span><span class="nx">hide</span><span class="p">();</span>
<span class="p">});</span>
<span class="nx">e</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
<span class="p">});</span>
<span class="p">});</span>
<span class="p"></</span><span class="nt">script</span><span class="p">></span>
<span class="p"></</span><span class="nt">head</span><span class="p">></span>
<span class="p"><</span><span class="nt">body</span><span class="p">></span>
<span class="p"><</span><span class="nt">input</span> <span class="na">type</span><span class="o">=</span><span class="s">"text"</span> <span class="na">value</span><span class="o">=</span><span class="s">"8"</span> <span class="na">name</span><span class="o">=</span><span class="s">"length"</span><span class="p">/></span>
<span class="p"><</span><span class="nt">button</span> <span class="na">id</span><span class="o">=</span><span class="s">"generate-string"</span><span class="p">></span>Give it now!<span class="p"></</span><span class="nt">button</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">id</span><span class="o">=</span><span class="s">"the-string"</span><span class="p">></span>
<span class="p"><</span><span class="nt">input</span> <span class="na">type</span><span class="o">=</span><span class="s">"text"</span> <span class="p">/></span>
<span class="p"><</span><span class="nt">button</span> <span class="na">id</span><span class="o">=</span><span class="s">"replace-string"</span><span class="p">></span>Replace<span class="p"></</span><span class="nt">button</span><span class="p">></span>
<span class="p"><</span><span class="nt">button</span> <span class="na">id</span><span class="o">=</span><span class="s">"delete-string"</span><span class="p">></span>Delete it<span class="p"></</span><span class="nt">button</span><span class="p">></span>
<span class="p"></</span><span class="nt">div</span><span class="p">></span>
<span class="p"></</span><span class="nt">body</span><span class="p">></span>
<span class="p"></</span><span class="nt">html</span><span class="p">></span>
</pre></div>
</td></tr></table></div>
<p>We’ll be using the <a class="reference external" href="http://jquery.com/">jQuery framework</a>
out of simplicity but feel free to replace it with your
favourite tool. The page is composed of simple HTML elements
to get user input and display the generated string. It also
contains client-side code to talk to the backend API that
actually performs the hard work.</p>
<p>Finally, here’s the application’s code that serves the
HTML page above and responds to requests to generate strings.
Both are hosted by the same application server.</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
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</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span><span class="o">,</span> <span class="nn">os.path</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="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="nb">open</span><span class="p">(</span><span class="s1">'index.html'</span><span class="p">)</span>
<span class="nd">@cherrypy.expose</span>
<span class="k">class</span> <span class="nc">StringGeneratorWebService</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="nd">@cherrypy.tools.accept</span><span class="p">(</span><span class="n">media</span><span class="o">=</span><span class="s1">'text/plain'</span><span class="p">)</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="k">return</span> <span class="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">'mystring'</span><span class="p">]</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="n">length</span><span class="o">=</span><span class="mi">8</span><span class="p">):</span>
<span class="n">some_string</span> <span class="o">=</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="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">'mystring'</span><span class="p">]</span> <span class="o">=</span> <span class="n">some_string</span>
<span class="k">return</span> <span class="n">some_string</span>
<span class="k">def</span> <span class="nf">PUT</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">another_string</span><span class="p">):</span>
<span class="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">'mystring'</span><span class="p">]</span> <span class="o">=</span> <span class="n">another_string</span>
<span class="k">def</span> <span class="nf">DELETE</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">session</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'mystring'</span><span class="p">,</span> <span class="bp">None</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">conf</span> <span class="o">=</span> <span class="p">{</span>
<span class="s1">'/'</span><span class="p">:</span> <span class="p">{</span>
<span class="s1">'tools.sessions.on'</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
<span class="s1">'tools.staticdir.root'</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">abspath</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">getcwd</span><span class="p">())</span>
<span class="p">},</span>
<span class="s1">'/generator'</span><span class="p">:</span> <span class="p">{</span>
<span class="s1">'request.dispatch'</span><span class="p">:</span> <span class="n">cherrypy</span><span class="o">.</span><span class="n">dispatch</span><span class="o">.</span><span class="n">MethodDispatcher</span><span class="p">(),</span>
<span class="s1">'tools.response_headers.on'</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
<span class="s1">'tools.response_headers.headers'</span><span class="p">:</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="p">},</span>
<span class="s1">'/static'</span><span class="p">:</span> <span class="p">{</span>
<span class="s1">'tools.staticdir.on'</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
<span class="s1">'tools.staticdir.dir'</span><span class="p">:</span> <span class="s1">'./public'</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="n">webapp</span> <span class="o">=</span> <span class="n">StringGenerator</span><span class="p">()</span>
<span class="n">webapp</span><span class="o">.</span><span class="n">generator</span> <span class="o">=</span> <span class="n">StringGeneratorWebService</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">webapp</span><span class="p">,</span> <span class="s1">'/'</span><span class="p">,</span> <span class="n">conf</span><span class="p">)</span>
</pre></div>
</td></tr></table></div>
<p>Save this into a file named <cite>tut08.py</cite> and run it as follows:</p>
<div class="highlight-bash"><div class="highlight"><pre><span></span>$ python tut08.py
</pre></div>
</div>
<p>Go to <a class="reference external" href="http://127.0.0.1:8080/">http://127.0.0.1:8080/</a> and play with the input and buttons
to generate, replace or delete the strings. Notice how the page
isn’t refreshed, simply part of its content.</p>
<p>Notice as well how your frontend converses with the backend using
a straightfoward, yet clean, web service API. That same API
could easily be used by non-HTML clients.</p>
</div>
<div class="section" id="tutorial-9-data-is-all-my-life">
<span id="tut09"></span><h2><a class="toc-backref" href="#id11">Tutorial 9: Data is all my life</a><a class="headerlink" href="#tutorial-9-data-is-all-my-life" title="Permalink to this headline">¶</a></h2>
<p>Until now, all the generated strings were saved in the
session, which by default is stored in the process memory. Though,
you can persist sessions on disk or in a distributed memory store,
this is not the right way of keeping your data on the long run.
Sessions are there to identify your user and carry as little
amount of data as necessary for the operation carried by the user.</p>
<p>To store, persist and query data you need a proper database server.
There exist many to choose from with various paradigm support:</p>
<ul class="simple">
<li>relational: PostgreSQL, SQLite, MariaDB, Firebird</li>
<li>column-oriented: HBase, Cassandra</li>
<li>key-store: redis, memcached</li>
<li>document oriented: Couchdb, MongoDB</li>
<li>graph-oriented: neo4j</li>
</ul>
<p>Let’s focus on the relational ones since they are the most common
and probably what you will want to learn first.</p>
<p>For the sake of reducing the number of dependencies for these
tutorials, we will go for the <code class="xref py py-mod docutils literal"><span class="pre">sqlite</span></code> database which
is directly supported by Python.</p>
<p>Our application will replace the storage of the generated
string from the session to a SQLite database. The application
will have the same HTML code as <a class="reference internal" href="#tut08"><span class="std std-ref">tutorial 08</span></a>.
So let’s simply focus on the application code itself:</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
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</pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span><span class="o">,</span> <span class="nn">os.path</span>
<span class="kn">import</span> <span class="nn">random</span>
<span class="kn">import</span> <span class="nn">sqlite3</span>
<span class="kn">import</span> <span class="nn">string</span>
<span class="kn">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">cherrypy</span>
<span class="n">DB_STRING</span> <span class="o">=</span> <span class="s2">"my.db"</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="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="nb">open</span><span class="p">(</span><span class="s1">'index.html'</span><span class="p">)</span>
<span class="nd">@cherrypy.expose</span>
<span class="k">class</span> <span class="nc">StringGeneratorWebService</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="nd">@cherrypy.tools.accept</span><span class="p">(</span><span class="n">media</span><span class="o">=</span><span class="s1">'text/plain'</span><span class="p">)</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="k">with</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">DB_STRING</span><span class="p">)</span> <span class="k">as</span> <span class="n">c</span><span class="p">:</span>
<span class="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">'ts'</span><span class="p">]</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">"SELECT value FROM user_string WHERE session_id=?"</span><span class="p">,</span>
<span class="p">[</span><span class="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">id</span><span class="p">])</span>
<span class="k">return</span> <span class="n">r</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</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="n">length</span><span class="o">=</span><span class="mi">8</span><span class="p">):</span>
<span class="n">some_string</span> <span class="o">=</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">with</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">DB_STRING</span><span class="p">)</span> <span class="k">as</span> <span class="n">c</span><span class="p">:</span>
<span class="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">'ts'</span><span class="p">]</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">"INSERT INTO user_string VALUES (?, ?)"</span><span class="p">,</span>
<span class="p">[</span><span class="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">id</span><span class="p">,</span> <span class="n">some_string</span><span class="p">])</span>
<span class="k">return</span> <span class="n">some_string</span>
<span class="k">def</span> <span class="nf">PUT</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">another_string</span><span class="p">):</span>
<span class="k">with</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">DB_STRING</span><span class="p">)</span> <span class="k">as</span> <span class="n">c</span><span class="p">:</span>
<span class="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">'ts'</span><span class="p">]</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">"UPDATE user_string SET value=? WHERE session_id=?"</span><span class="p">,</span>
<span class="p">[</span><span class="n">another_string</span><span class="p">,</span> <span class="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">id</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">DELETE</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">session</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'ts'</span><span class="p">,</span> <span class="bp">None</span><span class="p">)</span>
<span class="k">with</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">DB_STRING</span><span class="p">)</span> <span class="k">as</span> <span class="n">c</span><span class="p">:</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">"DELETE FROM user_string WHERE session_id=?"</span><span class="p">,</span>
<span class="p">[</span><span class="n">cherrypy</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">id</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">setup_database</span><span class="p">():</span>
<span class="sd">"""</span>
<span class="sd"> Create the `user_string` table in the database</span>
<span class="sd"> on server startup</span>
<span class="sd"> """</span>
<span class="k">with</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">DB_STRING</span><span class="p">)</span> <span class="k">as</span> <span class="n">con</span><span class="p">:</span>
<span class="n">con</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">"CREATE TABLE user_string (session_id, value)"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">cleanup_database</span><span class="p">():</span>
<span class="sd">"""</span>
<span class="sd"> Destroy the `user_string` table from the database</span>
<span class="sd"> on server shutdown.</span>
<span class="sd"> """</span>
<span class="k">with</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">DB_STRING</span><span class="p">)</span> <span class="k">as</span> <span class="n">con</span><span class="p">:</span>
<span class="n">con</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">"DROP TABLE user_string"</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">conf</span> <span class="o">=</span> <span class="p">{</span>
<span class="s1">'/'</span><span class="p">:</span> <span class="p">{</span>
<span class="s1">'tools.sessions.on'</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
<span class="s1">'tools.staticdir.root'</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">abspath</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">getcwd</span><span class="p">())</span>
<span class="p">},</span>
<span class="s1">'/generator'</span><span class="p">:</span> <span class="p">{</span>
<span class="s1">'request.dispatch'</span><span class="p">:</span> <span class="n">cherrypy</span><span class="o">.</span><span class="n">dispatch</span><span class="o">.</span><span class="n">MethodDispatcher</span><span class="p">(),</span>
<span class="s1">'tools.response_headers.on'</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
<span class="s1">'tools.response_headers.headers'</span><span class="p">:</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="p">},</span>
<span class="s1">'/static'</span><span class="p">:</span> <span class="p">{</span>
<span class="s1">'tools.staticdir.on'</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
<span class="s1">'tools.staticdir.dir'</span><span class="p">:</span> <span class="s1">'./public'</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="n">cherrypy</span><span class="o">.</span><span class="n">engine</span><span class="o">.</span><span class="n">subscribe</span><span class="p">(</span><span class="s1">'start'</span><span class="p">,</span> <span class="n">setup_database</span><span class="p">)</span>
<span class="n">cherrypy</span><span class="o">.</span><span class="n">engine</span><span class="o">.</span><span class="n">subscribe</span><span class="p">(</span><span class="s1">'stop'</span><span class="p">,</span> <span class="n">cleanup_database</span><span class="p">)</span>
<span class="n">webapp</span> <span class="o">=</span> <span class="n">StringGenerator</span><span class="p">()</span>
<span class="n">webapp</span><span class="o">.</span><span class="n">generator</span> <span class="o">=</span> <span class="n">StringGeneratorWebService</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">webapp</span><span class="p">,</span> <span class="s1">'/'</span><span class="p">,</span> <span class="n">conf</span><span class="p">)</span>
</pre></div>
</td></tr></table></div>
<p>Save this into a file named <cite>tut09.py</cite> and run it as follows:</p>
<div class="highlight-bash"><div class="highlight"><pre><span></span>$ python tut09.py
</pre></div>
</div>
<p>Let’s first see how we create two functions that create
and destroy the table within our database. These functions
are registered to the CherryPy’s server on lines 85-86,
so that they are called when the server starts and stops.</p>
<p>Next, notice how we replaced all the session code with calls
to the database. We use the session id to identify the
user’s string within our database. Since the session will go
away after a while, it’s probably not the right approach.
A better idea would be to associate the user’s login or
more resilient unique identifier. For the sake of our
demo, this should do.</p>
<div class="admonition important">
<p class="first admonition-title">Important</p>
<p class="last">In this example, we must still set the session to a dummy value
so that the session is not <a class="reference external" href="https://cherrypy.readthedocs.org/en/latest/pkg/cherrypy.lib.html?highlight=fixation#session-fixation-protection">discarded</a>
on each request by CherryPy. Since we now use the database
to store the generated string, we simply store a dummy
timestamp inside the session.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Unfortunately, sqlite in Python forbids us
to share a connection between threads. Since CherryPy is a
multi-threaded server, this would be an issue. This is the
reason why we open and close a connection to the database
on each call. This is clearly not really production friendly,
and it is probably advisable to either use a more capable
database engine or a higher level library, such as
<a class="reference external" href="http://sqlalchemy.readthedocs.org">SQLAlchemy</a>, to better
support your application’s needs.</p>
</div>
</div>
<div class="section" id="tutorial-10-make-it-a-modern-single-page-application-with-react-js">
<span id="tut10"></span><h2><a class="toc-backref" href="#id12">Tutorial 10: Make it a modern single-page application with React.js</a><a class="headerlink" href="#tutorial-10-make-it-a-modern-single-page-application-with-react-js" title="Permalink to this headline">¶</a></h2>
<p>In the recent years, client-side single-page applications (SPA) have
gradually eaten server-side generated content web applications’s lunch.</p>
<p>This tutorial demonstrates how to integrate with
<a class="reference external" href="https://facebook.github.io/react/">React.js</a>, a Javascript library
for SPA released by Facebook in 2013. Please refer to React.js
documentation to learn more about it.</p>
<p>To demonstrate it, let’s use the code from <a class="reference internal" href="#tut09"><span class="std std-ref">tutorial 09</span></a>.
However, we will be replacing the HTML and Javascript code.</p>
<p>First, let’s see how our HTML code has changed:</p>
<div class="highlight-html"><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="cp"><!DOCTYPE html></span>
<span class="p"><</span><span class="nt">html</span><span class="p">></span>
<span class="p"><</span><span class="nt">head</span><span class="p">></span>
<span class="p"><</span><span class="nt">link</span> <span class="na">href</span><span class="o">=</span><span class="s">"/static/css/style.css"</span> <span class="na">rel</span><span class="o">=</span><span class="s">"stylesheet"</span><span class="p">></span>
<span class="p"><</span><span class="nt">script</span> <span class="na">src</span><span class="o">=</span><span class="s">"https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"</span><span class="p">></</span><span class="nt">script</span><span class="p">></span>
<span class="p"><</span><span class="nt">script</span> <span class="na">src</span><span class="o">=</span><span class="s">"http://code.jquery.com/jquery-2.1.1.min.js"</span><span class="p">></</span><span class="nt">script</span><span class="p">></span>
<span class="p"><</span><span class="nt">script</span> <span class="na">src</span><span class="o">=</span><span class="s">"https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"</span><span class="p">></</span><span class="nt">script</span><span class="p">></span>
<span class="p"></</span><span class="nt">head</span><span class="p">></span>
<span class="p"><</span><span class="nt">body</span><span class="p">></span>
<span class="p"><</span><span class="nt">div</span> <span class="na">id</span><span class="o">=</span><span class="s">"generator"</span><span class="p">></</span><span class="nt">div</span><span class="p">></span>
<span class="p"><</span><span class="nt">script</span> <span class="na">type</span><span class="o">=</span><span class="s">"text/babel"</span> <span class="na">src</span><span class="o">=</span><span class="s">"static/js/gen.js"</span><span class="p">></</span><span class="nt">script</span><span class="p">></span>
<span class="p"></</span><span class="nt">body</span><span class="p">></span>
<span class="p"></</span><span class="nt">html</span><span class="p">></span>
</pre></div>
</td></tr></table></div>
<p>Basically, we have removed the entire Javascript code that was using jQuery.
Instead, we load the React.js library as well as a new, local,
Javascript module, named <code class="docutils literal"><span class="pre">gen.js</span></code> and located in the <code class="docutils literal"><span class="pre">public/js</span></code>
directory:</p>
<div class="highlight-javascript"><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
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</pre></div></td><td class="code"><div class="highlight"><pre><span></span>var StringGeneratorBox = React.createClass({
handleGenerate: function() {
var length = this.state.length;
this.setState(function() {
$.ajax({
url: this.props.url,
dataType: 'text',
type: 'POST',
data: {
"length": length
},
success: function(data) {
this.setState({
length: length,
string: data,
mode: "edit"
});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url,
status, err.toString()
);
}.bind(this)
});
});
},
handleEdit: function() {
var new_string = this.state.string;
this.setState(function() {
$.ajax({
url: this.props.url,
type: 'PUT',
data: {
"another_string": new_string
},
success: function() {
this.setState({
length: new_string.length,
string: new_string,
mode: "edit"
});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url,
status, err.toString()
);
}.bind(this)
});
});
},
handleDelete: function() {
this.setState(function() {
$.ajax({
url: this.props.url,
type: 'DELETE',
success: function() {
this.setState({
length: "8",
string: "",
mode: "create"
});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url,
status, err.toString()
);
}.bind(this)
});
});
},
handleLengthChange: function(length) {
this.setState({
length: length,
string: "",
mode: "create"
});
},
handleStringChange: function(new_string) {
this.setState({
length: new_string.length,
string: new_string,
mode: "edit"
});
},
getInitialState: function() {
return {
length: "8",
string: "",
mode: "create"
};
},
render: function() {
return (
<div className="stringGenBox">
<StringGeneratorForm onCreateString={this.handleGenerate}
onReplaceString={this.handleEdit}
onDeleteString={this.handleDelete}
onLengthChange={this.handleLengthChange}
onStringChange={this.handleStringChange}
mode={this.state.mode}
length={this.state.length}
string={this.state.string}/>
</div>
);
}
});
var StringGeneratorForm = React.createClass({
handleCreate: function(e) {
e.preventDefault();
this.props.onCreateString();
},
handleReplace: function(e) {
e.preventDefault();
this.props.onReplaceString();
},
handleDelete: function(e) {
e.preventDefault();
this.props.onDeleteString();
},
handleLengthChange: function(e) {
e.preventDefault();
var length = React.findDOMNode(this.refs.length).value.trim();
this.props.onLengthChange(length);
},
handleStringChange: function(e) {
e.preventDefault();
var string = React.findDOMNode(this.refs.string).value.trim();
this.props.onStringChange(string);
},
render: function() {
if (this.props.mode == "create") {
return (
<div>
<input type="text" ref="length" defaultValue="8" value={this.props.length} onChange={this.handleLengthChange} />
<button onClick={this.handleCreate}>Give it now!</button>
</div>
);
} else if (this.props.mode == "edit") {
return (
<div>
<input type="text" ref="string" value={this.props.string} onChange={this.handleStringChange} />
<button onClick={this.handleReplace}>Replace</button>
<button onClick={this.handleDelete}>Delete it</button>
</div>
);
}
return null;
}
});
React.render(
<StringGeneratorBox url="/generator" />,
document.getElementById('generator')
);
</pre></div>
</td></tr></table></div>
<p>Wow! What a lot of code for something so simple, isn’t it?
The entry point is the last few lines where we indicate that we
want to render the HTML code of the <code class="docutils literal"><span class="pre">StringGeneratorBox</span></code> React.js
class inside the <code class="docutils literal"><span class="pre">generator</span></code> div.</p>
<p>When the page is rendered, so is that component. Notice how it
is also made of another component that renders the form itself.</p>
<p>This might be a little over the top for such a simple example
but hopefully will get you started with React.js in the process.</p>
<p>There is not much to say and, hopefully, the meaning of that code
is rather clear. The component has an internal <a class="reference external" href="https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html">state</a>
in which we store the current string as generated/modified by the user.</p>
<p>When the user <a class="reference external" href="https://facebook.github.io/react/docs/forms.html">changes the content of the input boxes</a>,
the state is updated on the client side. Then, when a button is clicked,
that state is sent out to the backend server using the API endpoint
and the appropriate action takes places. Then, the state is updated and so is the view.</p>
</div>
<div class="section" id="tutorial-11-organize-my-code">
<h2><a class="toc-backref" href="#id13">Tutorial 11: Organize my code</a><a class="headerlink" href="#tutorial-11-organize-my-code" title="Permalink to this headline">¶</a></h2>
<p>CherryPy comes with a powerful architecture
that helps you organizing your code in a way that should make
it easier to maintain and more flexible.</p>
<p>Several mechanisms are at your disposal, this tutorial will focus
on the three main ones:</p>
<ul class="simple">
<li><a class="reference internal" href="extend.html#dispatchers"><span class="std std-ref">dispatchers</span></a></li>
<li><a class="reference internal" href="extend.html#tools"><span class="std std-ref">tools</span></a></li>
<li><a class="reference internal" href="extend.html#busplugins"><span class="std std-ref">plugins</span></a></li>
</ul>
<p>In order to understand them, let’s imagine you are at a superstore:</p>
<ul class="simple">
<li>You have several tills and people queuing for each of them (those are your requests)</li>
<li>You have various sections with food and other stuff (these are your data)</li>
<li>Finally you have the superstore people and their daily tasks
to make sure sections are always in order (this is your backend)</li>
</ul>
<p>In spite of being really simplistic, this is not far from how your
application behaves. CherryPy helps you structure your application
in a way that mirrors these high-level ideas.</p>
<div class="section" id="dispatchers">
<h3><a class="toc-backref" href="#id14">Dispatchers</a><a class="headerlink" href="#dispatchers" title="Permalink to this headline">¶</a></h3>
<p>Coming back to the superstore example, it is likely that you will
want to perform operations based on the till:</p>
<ul class="simple">
<li>Have a till for baskets with less than ten items</li>
<li>Have a till for disabled people</li>
<li>Have a till for pregnant women</li>
<li>Have a till where you can only using the store card</li>
</ul>
<p>To support these use-cases, CherryPy provides a mechanism called
a <a class="reference internal" href="extend.html#dispatchers"><span class="std std-ref">dispatcher</span></a>. A dispatcher is executed early
during the request processing in order to determine which piece of
code of your application will handle the incoming request. Or, to
continue on the store analogy, a dispatcher will decide which
till to lead a customer to.</p>
</div>
<div class="section" id="tools">
<h3><a class="toc-backref" href="#id15">Tools</a><a class="headerlink" href="#tools" title="Permalink to this headline">¶</a></h3>
<p>Let’s assume your store has decided to operate a discount spree but,
only for a specific category of customers. CherryPy will deal
with such use case via a mechanism called a <a class="reference internal" href="extend.html#tools"><span class="std std-ref">tool</span></a>.</p>
<p>A tool is a piece of code that runs on a per-request
basis in order to perform additional work. Usually a tool is a
simple Python function that is executed at a given point during
the process of the request by CherryPy.</p>
</div>
<div class="section" id="plugins">
<h3><a class="toc-backref" href="#id16">Plugins</a><a class="headerlink" href="#plugins" title="Permalink to this headline">¶</a></h3>
<p>As we have seen, the store has a crew of people dedicated to manage
the stock and deal with any customers’ expectation.</p>
<p>In the CherryPy world, this translates into having functions
that run outside of any request life-cycle. These functions should
take care of background tasks, long lived connections (such as
those to a database for instance), etc.</p>
<p><a class="reference internal" href="extend.html#busplugins"><span class="std std-ref">Plugins</span></a> are called that way because
they work along with the CherryPy <a class="reference internal" href="extend.html#cpengine"><span class="std std-ref">engine</span></a>
and extend it with your operations.</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="#">Tutorials</a><ul>
<li><a class="reference internal" href="#tutorial-1-a-basic-web-application">Tutorial 1: A basic web application</a></li>
<li><a class="reference internal" href="#tutorial-2-different-urls-lead-to-different-functions">Tutorial 2: Different URLs lead to different functions</a></li>
<li><a class="reference internal" href="#tutorial-3-my-urls-have-parameters">Tutorial 3: My URLs have parameters</a></li>
<li><a class="reference internal" href="#tutorial-4-submit-this-form">Tutorial 4: Submit this form</a></li>
<li><a class="reference internal" href="#tutorial-5-track-my-end-user-s-activity">Tutorial 5: Track my end-user’s activity</a></li>
<li><a class="reference internal" href="#tutorial-6-what-about-my-javascripts-css-and-images">Tutorial 6: What about my javascripts, CSS and images?</a></li>
<li><a class="reference internal" href="#tutorial-7-give-us-a-rest">Tutorial 7: Give us a REST</a></li>
<li><a class="reference internal" href="#tutorial-8-make-it-smoother-with-ajax">Tutorial 8: Make it smoother with Ajax</a></li>
<li><a class="reference internal" href="#tutorial-9-data-is-all-my-life">Tutorial 9: Data is all my life</a></li>
<li><a class="reference internal" href="#tutorial-10-make-it-a-modern-single-page-application-with-react-js">Tutorial 10: Make it a modern single-page application with React.js</a></li>
<li><a class="reference internal" href="#tutorial-11-organize-my-code">Tutorial 11: Organize my code</a><ul>
<li><a class="reference internal" href="#dispatchers">Dispatchers</a></li>
<li><a class="reference internal" href="#tools">Tools</a></li>
<li><a class="reference internal" href="#plugins">Plugins</a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="install.html"
title="previous chapter">Installation</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="basics.html"
title="next chapter">Basics</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/tutorials.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="basics.html" title="Basics"
>next</a> |</li>
<li class="right" >
<a href="install.html" title="Installation"
>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>
|