Examples

We start with a simple example. Before we proceed let setup virtualenv environment:

$ virtualenv env

Since Wheezy Web is template engine agnostic, you need specify extra requirements (per template engine of your choice):

$ env/bin/easy_install wheezy.web[jinja2]
$ env/bin/easy_install wheezy.web[mako]
$ env/bin/easy_install wheezy.web[tenjin]
$ env/bin/easy_install wheezy.web[wheezy.template]

Templates

Template application serves template purpose for you. It includes:

  • Integration with both mako and tenjin template system.
  • User registration and authentication.
  • Form validation.

If you are about to start a new project it is a good starting point.

Hello World

hello.py shows you how to use Wheezy Web in a pretty simple WSGI application. It no way pretend to be shortest possible and absolutely not magical:

""" Minimal helloworld application.
"""

from wheezy.http import HTTPResponse
from wheezy.http import WSGIApplication
from wheezy.routing import url
from wheezy.web.handlers import BaseHandler
from wheezy.web.middleware import bootstrap_defaults
from wheezy.web.middleware import path_routing_middleware_factory


class WelcomeHandler(BaseHandler):

    def get(self):
        response = HTTPResponse()
        response.write('Hello World!')
        return response


def welcome(request):
    response = HTTPResponse()
    response.write('Hello World!')
    return response


all_urls = [
    url('', WelcomeHandler, name='default'),
    url('welcome', welcome, name='welcome')
]


options = {}
main = WSGIApplication(
    middleware=[
        bootstrap_defaults(url_mapping=all_urls),
        path_routing_middleware_factory
    ],
    options=options
)


if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    try:
        print('Visit http://localhost:8080/')
        make_server('', 8080, main).serve_forever()
    except KeyboardInterrupt:
        pass
    print('\nThanks!')

Handler Contract

Let have a look through each line in this application. First of all let take a look what is a handler:

def welcome(request):
    response = HTTPResponse()
    response.write('Hello World!')
    return response

This one is not changed from what you had in wheezy.http so you are good to keep it minimal. However there is added another one (that actually implements the same handler contract internally):

class WelcomeHandler(BaseHandler):

    def get(self):
        response = HTTPResponse()
        response.write('Hello World!')
        return response

What is get method here? It is your response to HTTP GET request. You have post for HTTP POST, etc.

Routing

Routing is inherited from wheezy.routing. Note that both handlers are working well together:

all_urls = [
    url('', WelcomeHandler, name='default'),
    url('welcome', welcome, name='welcome')
]

Application

WSGIApplication is coming from wheezy.http. Integration with wheezy.routing is provided as middleware factory (path_routing_middleware_factory()):

options = {}
main = WSGIApplication(
    middleware=[
        bootstrap_defaults(url_mapping=all_urls),
        path_routing_middleware_factory
    ],
    options=options
)

Functional Tests

You can easily write functional tests for your application using WSGIClient from wheezy.http (file test_hello.py).

import unittest

from wheezy.http.functional import WSGIClient

from hello import main


class HelloTestCase(unittest.TestCase):

    def setUp(self):
        self.client = WSGIClient(main)

    def tearDown(self):
        del self.client
        self.client = None

    def test_home(self):
        """ Ensure welcome page is rendered.
        """
        assert 200 == self.client.get('/')
        assert 'Hello World!' == self.client.content

    def test_welcome(self):
        """ Ensure welcome page is rendered.
        """
        assert 200 == self.client.get('/welcome')
        assert 'Hello World!' == self.client.content

For more advanced use cases refer to wheezy.http documentation, please.

Benchmark

You can add benchmark of your functional tests (file benchmark_hello.py):

from wheezy.core.benchmark import Benchmark

from test_hello import HelloTestCase


class BenchmarkTestCase(HelloTestCase):
    """
        ../../env/bin/nosetests-2.7 -qs -m benchmark benchmark_hello.py
    """

    def runTest(self):
        """ Perform bachmark and print results.
        """
        p = Benchmark((
            self.test_welcome,
            self.test_home
        ), 20000)
        p.report('hello', baselines={
            'test_welcome': 1.0,
            'test_home': 0.9
        })

Let run benchmark tests with nose (to be run from demos/hello directory):

$ ../../env/bin/nosetests-2.7 -qs -m benchmark benchmark_hello.py

Here is output:

hello: 2 x 20000
baseline throughput change target
  100.0%   11518rps  +0.0% test_welcome
   91.0%   10476rps  +1.1% test_home
----------------------------------------------------------------------
Ran 1 test in 3.686s

Table Of Contents

Previous topic

Getting Started

Next topic

Tutorial

This Page