Use CherryPy add a web interface to a Python script


jQuery is a library that adds all sorts of functionality to web pages – ranging from changing text color to animation and interaction. I'm using it to perform Ajax calls and to change the content of divs once data arrives.

Next, getParameterByName will parse the URL parameters for the name I ask for and return it. I use it on line 14 to get the player hash. Because playerHash is defined outside of any function, it will be available to all JavaScript functions on the same page.

The getHTML function (line 15) fetches HTML from CherryPy via Ajax. Each Ajax function starts by defining an object obj (line 17). Then variables are added as needed (line 18). Line 20 is the jQuery Ajax function. The dollar sign in $.post is the shortcut to jQuery included on line 3, and post is the command name. The first argument, "../play" in this case, is the address to send the command to. It starts with ../ because CherryPy is looking for commands one level up from the web folder where index.html lives.

The next argument is data to send to the specified address. Here, I pass the object obj that I created on line 17. The third argument is what to do when the Ajax call returns data. The syntax is somewhat strange with an inline function definition, but you get used to it. Inside the inline function, the program checks to see whether the data received is different from what it already has (line 22). If so, jQuery is used to update the div called "cards." The jQuery line

$ ( "#cards" ).html ( data );

tells jQuery (the dollar sign) to find a div named cards (# means div) and change its HTML (.html) to the data provided (data).

The deal and bet functions work the same way. setInterval calls a function continuously (here, getHTML()), so the player's screen polls for new information. On the web server side, Python evaluates the state of the poker game at any given time and returns the appropriate cards, betting form, or dealer button.


On line 55, the body style makes the background green. Then, the div on line 56 takes up the entire screen and is assigned the ID cards. The jQuery Ajax functions search for this ID when they have content to replace.

Buy this article as PDF

Express-Checkout as PDF

Pages: 8

Price $2.95
(incl. VAT)

Buy Raspberry Pi Geek

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content