<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Boschmans Account &#187; cherrypy</title>
	<atom:link href="http://www.boschmans.net/tag/cherrypy/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.boschmans.net</link>
	<description>A collection of interests and happenings...</description>
	<lastBuildDate>Wed, 01 Feb 2012 22:21:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Proof of concept for a simple webserver running python code</title>
		<link>http://www.boschmans.net/2012/01/31/proof-of-concept-for-a-simple-webserver-running-python-code/</link>
		<comments>http://www.boschmans.net/2012/01/31/proof-of-concept-for-a-simple-webserver-running-python-code/#comments</comments>
		<pubDate>Tue, 31 Jan 2012 21:31:27 +0000</pubDate>
		<dc:creator>alex</dc:creator>
				<category><![CDATA[Blog News]]></category>
		<category><![CDATA[cherrypy]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[website]]></category>

		<guid isPermaLink="false">http://www.boschmans.net/?p=1113</guid>
		<description><![CDATA[Here is a small code example using CherryPy to run a very simple webserver that generates a simple math question compares the answer to the solution. It&#8217;s meant as a proof of concept, so there is no security built in. &#8230; <a href="http://www.boschmans.net/2012/01/31/proof-of-concept-for-a-simple-webserver-running-python-code/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Here is a small code example using <a title="CherryPy" href="http://cherrypy.org/">CherryPy</a> to run a very simple webserver that</p>
<ul>
<li>generates a simple math question</li>
<li>compares the answer to the solution.</li>
</ul>
<p>It&#8217;s meant as a <em>proof of concept</em>, so there is no security built in. It&#8217;s running on localhost on port 8888 (modifiable in the main part of the code).<br />
It allows you to play around and test out your ideas.</p>
<p><span style="color: #ff0000;">Do not use this code on an outside network !</span></p>
<p>It&#8217;s simply an example showing how easy it is to set up a web server and how you can create pages for it using python and CherryPy. It&#8217;s been cobbled together in an evening from previous programming so there&#8217;s some cruft left in. I&#8217;ve also extensively commented the code.</p>
<p>Requirements:</p>
<ul>
<li>python 2.7 ( 2.5 will work as well is my guess )</li>
<li><a title="CherryPy" href="http://cherrypy.org/">cherrypy</a> 3.2.2 ( use easy_install or pip to download and install the latest version)</li>
<li><a href='http://www.boschmans.net/wp-content/uploads/2012/01/site.py_1.txt'>site.py</a> ( the file containing the python code )</li>
</ul>
<p>You start the server in a command prompt using : <em>python site.py</em> which will start the server. Leave the command prompt open.</p>
<p>You can then visit the webserver by opening a browser and going to <a href="http://localhost:8888">http://localhost:8888</a> to see the index page and play around with it.</p>
<pre class="brush: python; title: ; notranslate">
#
# MathPoc : Proof of concept of a simple math problem, bringing it to the browser
#
# Alex Boschmans
#
# Version 0.2, February 2011
#
# 0.2 Added some error checks and expanded math to not just adding but also
# subtraction and multiplication and divisions. Extensively commented code.

header = &quot;&quot;&quot;&lt;HTML&gt;
            &lt;HEAD&gt;
                &lt;title&gt;MATH Proof of Concept&lt;/title&gt;
            &lt;/HEAD&gt;
            &lt;BODY&gt;
        &quot;&quot;&quot;
footer = &quot;&lt;/BODY&gt;&lt;/HTML&gt;&quot;

indexhtml = &quot;&quot;&quot;
        &lt;H1&gt;Math Proof of Concept&lt;/H1&gt;
        &lt;p&gt;Please answer the following question&lt;/p&gt;
                &lt;p&gt;How much is %d %s %d ? &lt;/p&gt;

                &lt;form action=&quot;/response&quot; method=&quot;post&quot;&gt;
                Answer: &lt;input type=&quot;text&quot; name=&quot;answer&quot; /&gt;
                &lt;input type=&quot;hidden&quot; name=&quot;number1&quot; value=&quot;%d&quot;&gt;
                &lt;input type=&quot;hidden&quot; name=&quot;number2&quot; value=&quot;%d&quot;&gt;
                &lt;input type=&quot;hidden&quot; name=&quot;operation&quot; value=&quot;%s&quot;&gt;
                &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;
                &lt;/form&gt;

        &quot;&quot;&quot;

def generatequestion():
    # This generates the question that we will pose using the random function
    # Generate a random question using 2 random numbers between 1 and 10
    number1 = random.randint(1,10)
    number2 = random.randint(1,10)
    # Now we choose an operatioin
    ops = [&quot;+&quot;, &quot;-&quot;, &quot;x&quot;, &quot;/&quot;]
    operation = random.choice(ops)
    # Let's check the division
    if operation == &quot;/&quot;:
        # Prevent divisions with remainders using the modulo operator
        # Using module on the two numbers evaluates to 0 when no remainder is present
        # While the modulo remainder is not equal to 0, generate two new numbers
        while number1 % number2 &lt;&gt; 0:
                number1 = random.randint(1,10)
                number2 = random.randint(1,10)
    # Assemble the html, inputting the numbers in the foreseen places in the html
    # In a more extensive project, you would keep this html in a template file and
    # call it with a dictionary of items that need to be filled in the template
    question = indexhtml % (number1, operation, number2, number1, number2, operation)
    # Add common html like header and footer - these are defined just once and reused
    # for each page
    html = header + question + footer
    # Return the completed html to the calling function (in this case index)
    return html

# This is the class that the cherrypy server uses and where you create the views that the
# webuser sees. After each definition there is a &lt;function&gt;.exposed=True that indicates if the
# webuser can see this page or not.
class MathPoc:
    def index(self):
        # This is the main index page that is shown to the user when he first visits the site.
        # We create the page by calling the function generatequestion (which is outside the class
        # MathPoc but accessible and we show it to the user by 'return'ing the page
        page = generatequestion()
        return page
        # The webuser will now see the page and will have a chance to enter an answer.
        # In the html form I've specified that the submitted result will go to the url &quot;response&quot;
        # I've added all the values I want to receive either as hidden values (eg the
        # original numbers, the operation) or as part of the form (eg the answer)
    index.exposed = True

    def response(self, answer, number1, number2, operation):
        # First check if we received an answer or if the user submitted without an answer
        if answer:
            # Calculate our own answer ourselves and generate a response to the user
            # We receive strings, so convert them to integers using int()
            number1 = int(number1)
            number2 = int(number2)
            answer = int(answer)
            # Answer is dependent on operation
            if operation == &quot;+&quot;:
                solution = number1 + number2
            elif operation == &quot;-&quot;:
                solution = number1 - number2
            elif operation == &quot;x&quot;:
                solution = number1 * number2
            else:
                solution = number1 / number2
            # See if the answer is correct and display according the result
            # Using templates, you could put all this in one template and
            # call the template with options so it knows what to show
            if solution &lt;&gt; answer:
                html = &quot;&quot;&quot;
                &lt;H1&gt;Sorry.&lt;/H1&gt;
                &lt;p&gt;The question was : %s %s %s = ?&lt;/p&gt;
                &lt;p&gt;Your answer %s is wrong. The correct answer is %d.&lt;/p&gt;
                &lt;p&gt;&lt;a href = &quot;/&quot;&gt;Try Again.&lt;/a&gt;&lt;/p&gt;
                &quot;&quot;&quot; % (number1, operation, number2, answer, solution)
            else:
                html = &quot;&quot;&quot;
                &lt;H1&gt;Correct !&lt;/H1&gt;
                &lt;p&gt;The question was : %s %s %s = %s&lt;/p&gt;
                &lt;p&gt;Your answer is correct !&lt;/p&gt;
                &lt;p&gt;&lt;a href = &quot;/&quot;&gt;Try Again.&lt;/a&gt;&lt;/p&gt;
                &quot;&quot;&quot; % (number1, operation, number2, answer)
        else:
            # We did not receive an answer
            html = &quot;&quot;&quot;
            &lt;h1&gt;Sorry ?&lt;/h1&gt;
            &lt;p&gt;You need to fill in an answer !&lt;/p&gt;
            &lt;p&gt;&lt;a href = &quot;/&quot;&gt;Try Again.&lt;/a&gt;&lt;/p&gt;
            &quot;&quot;&quot;
        # Return the page to the user, adding the common html
        return header + html + footer
    response.exposed = True

if __name__ == '__main__':
    import random
    import cherrypy
    import os, sys
    # Set the current directory - this is probably not needed for this example, cruft.
    try:
        current_dir = os.path.dirname(os.path.abspath(__file__))
    except:
        # probably running inside py2exe which doesn't set __file__
        current_dir = os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( )))

    # Set up site-wide config first so we get a log if errors occur.
    # Adding the setting 'environment': 'production' to the below turns off auto-reload.
    # Otherwise CherryPy monitors the code and any change to code reloads the server - handy for development !
    cherrypy.config.update({'server.socket_port':8888,
                            'server.socket_host':'127.0.0.1',
                            'log.error_file': 'site.log',
                            'log.screen': True})
    # CherryPy will complain of an empty config but will continue
    conf = {}
    cherrypy.tree.mount(MathPoc())
    #cherrypy.config.update({'server.socket_port':8888})
    cherrypy.quickstart(MathPoc(),'/', config=conf)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.boschmans.net/2012/01/31/proof-of-concept-for-a-simple-webserver-running-python-code/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using CherryPy for webform authentication</title>
		<link>http://www.boschmans.net/2010/03/07/using-cherrypy-for-webform-authentication/</link>
		<comments>http://www.boschmans.net/2010/03/07/using-cherrypy-for-webform-authentication/#comments</comments>
		<pubDate>Sun, 07 Mar 2010 21:48:57 +0000</pubDate>
		<dc:creator>alex</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[cherrypy]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[website]]></category>

		<guid isPermaLink="false">http://www.boschmans.net/?p=965</guid>
		<description><![CDATA[If you are using CherryPy, I can recommend the webform-based authentication that Arnar Birgisson wrote for ease of use and extensability. After trying out the included authentication models with CherryPy (I&#8217;m using 3.1.2, the last stable version at the moment &#8230; <a href="http://www.boschmans.net/2010/03/07/using-cherrypy-for-webform-authentication/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If you are using CherryPy, I can recommend the webform-based authentication that <a title="Arnar Birgisson" href="http://www.hvergi.net/arnar/" target="_blank">Arnar Birgisson</a> wrote for ease of use and extensability.</p>
<p>After trying out the included authentication models with CherryPy (I&#8217;m using 3.1.2, the last stable version at the moment of writing), I was disappointed in the results. Then I stumbled over a recommandation from someone on <a title="Nabble Forum System" href="http://old.nabble.com/" target="_blank">Nabble</a>, a web-based programmar&#8217;s discussion forum, which pointed to the following wiki page on the CherryPy site:</p>
<p><a title="CherryPy Authentication and Access restrictions" href="http://tools.cherrypy.org/wiki/AuthenticationAndAccessRestrictions" target="_blank">http://tools.cherrypy.org/wiki/AuthenticationAndAccessRestrictions</a></p>
<p>The complete program code plus examples are on the page and are well explained.</p>
<p>You can have a skeleton login system (using a hardcoded dictionary) up and running in literally half an hour !</p>
<ul>
<li> Just copy/paste the code on the page and save it as auth.py in your cherrypy script dir.</li>
<li>Add the hardcoded dictionary containing username and passwords to it (or script the db access, see the example included)</li>
<li>Put &#8216;require()&#8217; everywhere on your cherrypy pages that need to have login protection &#8211; additionally, you can also have roles so that only admins can access certain pages.</li>
</ul>
<p>Early last week I replaced that hardcoded dictionary and built the db lookup query for the login. Once that was working, I added a &#8216;my profile&#8217; page to the application I&#8217;m working on.  Then I thought it would be nice for the admin to have a &#8216;create user&#8217; form in the admin section to add users. Done that as well, using the jquery-ui to create tabs and seperate content in the admin section.</p>
<p>All in all, a nice week of nice work.</p>
<p>I&#8217;m starting to think this might make it&#8217;s way to my hosting server one of the coming weeks&#8230;  although I need to do some more work on showing the user only his keywords and not all the keywords, as well as doing something with the keywords to use them better.</p>
<p>Oh and one more thing: this works better under SSL than in the clear http: sky !</p>
]]></content:encoded>
			<wfw:commentRss>http://www.boschmans.net/2010/03/07/using-cherrypy-for-webform-authentication/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

