File: features.rst

package info (click to toggle)
circuits 3.1.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 9,756 kB
  • sloc: python: 15,945; makefile: 130
file content (576 lines) | stat: -rw-r--r-- 15,977 bytes parent folder | download | duplicates (3)
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
.. _CherryPy: http://www.cherrypy.org/


.. module:: circuits.web


Features
========


circuits.web is not a **Full Stack** or **High Level** web framework, rather
it is more closely aligned with `CherryPy`_ and offers enough functionality
to make quickly developing web applications easy and as flexible as possible.

circuits.web does not provide high level features such as:

- Templating
- Database access
- Form Validation
- Model View Controller
- Object Relational Mapper

The functionality that circutis.web **does** provide ensures that
circuits.web is fully HTTP/1.1 and WSGI/1.0 compliant and offers all the
essential tools you need to build your web application or website.

To demonstrate each feature, we're going to use the classical "Hello World!"
example as demonstrated earlier in :doc:`gettingstarted`.

Here's the code again for easy reference:

.. code-block:: python
    :linenos:
    
    from circuits.web import Server, Controller
    
    
    class Root(Controller):
        
        def index(self):
            return "Hello World!"
    
    
    (Server(8000) + Root()).run()


Logging
-------


circuits.web's :class:`~.Logger` component  allows
you to add logging support compatible with Apache
log file formats to your web application.

To use the :class:`~Logger` simply add it to your application:

.. code-block:: python
    
    (Server(8000) + Logger() + Root()).run()

Example Log Output::
    
    127.0.0.1 - - [05/Apr/2014:10:13:01] "GET / HTTP/1.1" 200 12 "" "curl/7.35.0"
    127.0.0.1 - - [05/Apr/2014:10:13:02] "GET /docs/build/html/index.html HTTP/1.1" 200 22402 "" "curl/7.35.0"


Cookies
-------


Access to cookies are provided through the :class:`~.Request` Object which holds data
about the request. The attribute :attr:`~.Request.cookie` is provided as part of the
:class:`~.Request` Object. It is a dict-like object, an instance of ``Cookie.SimpleCookie``
from the python standard library.

To demonstrate "Using Cookies" we'll write a very simple application that
remembers who we are:

If a cookie **name** is found, display "Hello <name>!".
Otherwise, display "Hello World!"
If an argument is given or a query parameter **name** is given,
store this as the **name** for the cookie.
Here's how we do it:

.. code-block:: python
    :linenos:
    
    from circuits.web import Server, Controller
    
    
    class Root(Controller):
        
        def index(self, name=None):
            if name:
                self.cookie["name"] = name
            else:
                name = self.cookie.get("name", None)
                name = "World!" if name is None else name.value
            
            return "Hello {0:s}!".format(name)
    
    
    (Server(8000) + Root()).run()

.. note:: To access the actual value of a cookie use the ``.value`` attribute.

.. warning:: Cookies can be vulnerable to XSS (*Cross Site Scripting*) attacks
             so use them at your own risk. See: http://en.wikipedia.org/wiki/Cross-site_scripting#Cookie_security


Dispatchers
-----------

circuits.web provides several dispatchers in the :mod:`~.dispatchers` module.
Most of these are available directly from the circuits.web namespace by
simply importing the required "dispatcher" from circuits.web.

Example:

.. code-block:: python
    
    from circuits.web import Static

The most important "dispatcher" is the default :class:`~.Dispatcher` used by the
circuits.web :class:`~.Server` to dispatch incoming requests onto a channel mapping
(*remember that circuits is event-driven and uses channels*), quite similar to that of CherryPy
or any other web framework that supports object traversal.

Normally you don't have to worry about any of the details of the *default*
:class:`~.Dispatcher` nor do you have to import it or use it in any way as it's already
included as part of the circuits.web :class:`~.Server` Component structure.


Static
......


The :class:`~.Static` "dispatcher" is used for serving static resources/files
in your application. To use this, simply add it to your application. It takes
some optional configuration which affects it's behavior.

The simplest example (*as per our Base Example*):

.. code-block:: python
    
    (Server(8000) + Static() + Root()).run()

This will serve up files in the *current directory* as static resources.

.. note::  This may override your **index** request handler of your top-most
           (``Root``) :class:`~.Controller`. As this might be undesirable and
           it's normally  common to serve static resources via a different path
           and even have them stored in a separate physical file path, you can
           configure the Static "dispatcher".

Static files stored in ``/home/joe/www/``:

.. code-block:: python
    
    (Server(8000) + Static(docroot="/home/joe/www/") + Root()).run()

Static files stored in ``/home/joe/www/`` **and** we want them served up as
``/static`` URI(s):

.. code-block:: python
    
    (Server(8000) + Static("/static", docroot="/home/joe/www/") + Root()).run()


Dispatcher
..........


The :class:`~.Dispatcher` (*the default*) is used to dispatch requests
and map them onto channels with a similar URL Mapping as CherryPy's.
A set of "paths" are maintained by the Dispatcher as Controller(s) are
registered to the system or unregistered from it. A channel mapping is
found by traversing the set of known paths (*Controller(s)*) and
successively matching parts of the path (*split by /*) until a suitable
Controller and Request Handler is found. If no Request Handler is found
that matches but there is a "default" Request Handler, it is used.

This Dispatcher also included support for matching against HTTP methods:

- GET
- POST
- PUT
- DELETE.
  
Here are some examples:

.. code-block:: python
    :linenos:
    
    class Root(Controller):
    
        def index(self):
            return "Hello World!"
        
        def foo(self, arg1, arg2, arg3):
            return "Foo: %r, %r, %r" % (arg1, arg2, arg3)
        
        def bar(self, kwarg1="foo", kwarg2="bar"):
            return "Bar: kwarg1=%r, kwarg2=%r" % (kwarg1, kwarg2)
        
        def foobar(self, arg1, kwarg1="foo"):
            return "FooBar: %r, kwarg1=%r" % (arg1, kwarg1)

With the following requests::
    
    http://127.0.0.1:8000/
    http://127.0.0.1:8000/foo/1/2/3
    http://127.0.0.1:8000/bar?kwarg1=1
    http://127.0.0.1:8000/bar?kwarg1=1&kwarg=2
    http://127.0.0.1:8000/foobar/1
    http://127.0.0.1:8000/foobar/1?kwarg1=1

The following output is produced::
    
    Hello World!
    Foo: '1', '2', '3'
    Bar: kwargs1='1', kwargs2='bar'
    Bar: kwargs1='1', kwargs2='bar'
    FooBar: '1', kwargs1='foo'
    FooBar: '1', kwargs1='1'

This demonstrates how the Dispatcher handles basic paths and how it handles
extra parts of a path as well as the query string. These are essentially
translated into arguments and keyword arguments.

To define a Request Handler that is specifically for the HTTP ``POST`` method, simply define a Request Handler like:

.. code-block:: python
    :linenos:
    
    class Root(Controller):
        
        def index(self):
            return "Hello World!"
       
    
    class Test(Controller):
        
        channel = "/test"
        
        def POST(self, *args, **kwargs): #***
            return "%r %r" % (args, kwargs)

This will handles ``POST`` requests to "/test", which brings us to the final
point of creating URL structures in your application. As seen above to create
a sub-structure of Request Handlers (*a tree*) simply create another
:class:`~.Controller` Component giving it a different channel and add it to the system
along with your existing Controller(s).


.. warning:: All public methods defined in your :class:`~.Controller`(s) are exposed
             as valid URI(s) in your web application. If you don't want
             something exposed either subclass from :class:`~BaseController` whereby
             you have to explicitly use :meth:`~.expose` or use ``@expose(False)``
             to decorate a public method as **NOT Exposed** or simply prefix the desired
             method with an underscore (e.g: ``def _foo(...):``).


VirtualHosts
............


The :class:`~.VirtualHosts` "dispatcher" allows you to serves up different parts of
your application for different "virtual" hosts.

Consider for example you have the following hosts defined::
    
    localdomain
    foo.localdomain
    bar.localdomain

You want to display something different on the default domain name
"localdomain" and something different for each of the sub-domains
"foo.localdomain" and "bar.localdomain".

To do this, we use the VirtualHosts "dispatcher":

.. code-block:: python
    :linenos:
    
    from circuits.web import Server, Controller, VirtualHosts
    
    
    class Root(Controller):
        
        def index(self):
            return "I am the main vhost"
    
    
    class Foo(Controller):
        
        channel = "/foo"
        
        def index(self):
            return "I am foo."
    
    
    class Bar(Controller):
        
        channel = "/bar"
        
        def index(self):
            return "I am bar."
    
    
    domains = {
        "foo.localdomain:8000": "foo",
        "bar.localdomain:8000": "bar",
    }
    
    
    (Server(8000) + VirtualHosts(domains) + Root() + Foo() + Bar()).run()

With the following requests::
    
    http://localdomain:8000/
    http://foo.localdomain:8000/
    http://bar.localdomain:8000/

The following output is produced::
    
    I am the main vhost
    I am foo.
    I am bar.

The argument **domains** pasted to VirtualHosts' constructor is a mapping
(*dict*) of: domain -> channel


XMLRPC
......


The :class:`~.XMLRPC` "dispatcher" provides a circuits.web application with the capability of serving up RPC Requests encoded in XML (XML-RPC).

Without going into too much details (*if you're using any kind of RPC "dispatcher" you should know what you're doing...*), here is a simple example:

.. code-block:: python
    :linenos:
    
    from circuits import Component
    from circuits.web import Server, Logger, XMLRPC
    
    
    class Test(Component):
        
        def foo(self, a, b, c):
            return a, b, c
    
    
    (Server(8000) + Logger() + XMLRPC() + Test()).run()

Here is a simple interactive session::
    
    >>> import xmlrpclib
    >>> xmlrpc = xmlrpclib.ServerProxy("http://127.0.0.1:8000/rpc/")
    >>> xmlrpc.foo(1, 2, 3)
    [1, 2, 3]
    >>> 


JSONRPC
.......

The :class:`~.JSONRPC` "dispatcher" is Identical in functionality to the :class:`~.XMLRPC` "dispatcher".

Example:

.. code-block:: python
    :linenos:
    
    from circuits import Component
    from circuits.web import Server, Logger, JSONRPC
    
    
    class Test(Component):
        
        def foo(self, a, b, c):
            return a, b, c
    
    
    (Server(8000) + Logger() + JSONRPC() + Test()).run()

Interactive session (*requires the `jsonrpclib <https://pypi.python.org/pypi/jsonrpc>`_ library*)::
    
    >>> import jsonrpclib
    >>> jsonrpc = jsonrpclib.ServerProxy("http://127.0.0.1:8000/rpc/")
    >>> jsonrpc.foo(1, 2, 3)
    {'result': [1, 2, 3], 'version': '1.1', 'id': 2, 'error': None}
    >>> 


Caching
-------

circuits.web includes all the usual **Cache Control**, **Expires**
and **ETag** caching mechanisms.

For simple expires style caching use the :meth:`~.tools.expires` tool from :mod:`.circuits.web.tools`.

Example:

.. code-block:: python
   :linenos:
    
    from circuits.web import Server, Controller
    
    
    class Root(Controller):
        
        def index(self):
            self.expires(3600)
            return "Hello World!"
    
    
    (Server(8000) + Root()).run()

For other caching mechanisms and validation please
refer to the :mod:`circuits.web.tools` documentation.

See in particular:

- :meth:`~.tools.expires`
- :meth:`~.tools.validate_since`

.. note:: In the example above we used ``self.expires(3600)`` which is
          just a convenience method built into the :class:`~.Controller`.
          The :class:`~.Controller` has other such convenience methods
          such as ``.uri``, ``.forbidden()``, ``.redirect()``, ``.notfound()``,
          ``.serve_file()``, ``.serve_download()`` and ``.expires()``.

          These are just wrappers around :mod:`~.tools` and :mod:`~.events`.


Compression
-----------

circuits.web includes the necessary low-level tools in order to achieve
compression. These tools are provided as a set of functions that can be
applied to the response before it is sent to the client.

Here's how you can create a simple Component that enables compression
in your web application or website.

.. code-block:: python
    :linenos:
    
    from circuits import handler, Component
    
    from circuits.web.tools import gzip
    from circuits.web import Server, Controller, Logger
    
    
    class Gzip(Component):
        
        @handler("response", priority=1.0)
        def compress_response(self, event, response):
            event[0] = gzip(response)
    
    
    class Root(Controller):
        
        def index(self):
            return "Hello World!"
    
    
    (Server(8000) + Gzip() + Root()).run()


Please refer to the documentation for further details:

- :func:`.tools.gzip`
- :func:`.utils.compress`


Authentication
--------------

circuits.web provides both HTTP Plain and Digest Authentication provided by the functions in :mod:`circuits.web.tools`:

- :func:`.tools.basic_auth`
- :func:`.tools.check_auth`
- :func:`.tools.digest_auth`

The first 2 arguments are always (*as with most circuits.web tools*):

- ``(request, response)``

An example demonstrating the use of "Basic Auth":

.. code-block:: python
    :linenos:
    
    from circuits.web import Server, Controller
    from circuits.web.tools import check_auth, basic_auth
    
    
    class Root(Controller):
        
        def index(self):
            realm = "Test"
            users = {"admin": "admin"}
            encrypt = str
            
            if check_auth(self.request, self.response, realm, users, encrypt):
                return "Hello %s" % self.request.login
            
            return basic_auth(self.request, self.response, realm, users, encrypt)
    
    
    (Server(8000) + Root()).run()

For "Digest Auth":

.. code-block:: python
    :linenos:
    
    from circuits.web import Server, Controller
    from circuits.web.tools import check_auth, digest_auth
    
    
    class Root(Controller):
        
        def index(self):
            realm = "Test"
            users = {"admin": "admin"}
            encrypt = str
            
            if check_auth(self.request, self.response, realm, users, encrypt):
                return "Hello %s" % self.request.login
            
            return digest_auth(self.request, self.response, realm, users, encrypt)
    
    
    (Server(8000) + Root()).run()


Session Handling
----------------

Session Handling in circuits.web is very similar to Cookies.
A dict-like object called **.session** is attached to every
Request Object during the life-cycle of that request. Internally
a Cookie named **circuits.session** is set in the response.

Rewriting the Cookie Example to use a session instead:

.. code-block:: python
    :linenos:
    
    from circuits.web import Server, Controller, Sessions
    
    
    class Root(Controller):
        
        def index(self, name=None):
            if name:
                self.session["name"] = name
            else:
                name = self.session.get("name", "World!")
            
            return "Hello %s!" % name
    
    
    (Server(8000) + Sessions() + Root()).run()

.. note:: The only Session Handling provided is a
          temporary in-memory based one and will
          not persist. No future Session Handling
          components are planned. For persistent
          data you should use some kind of Database.