| 41 | == Filtering == |
| 42 | |
| 43 | One important feature of markup streams is that you can apply ''filters'' to the stream, either filters that come with Markup, or your own custom filters. |
| 44 | |
| 45 | A filter is simply a callable that accepts the stream as parameter, and returns the filtered stream: |
| 46 | |
| 47 | {{{ |
| 48 | #!python |
| 49 | def noop(stream): |
| 50 | """A filter that doesn't actually do anything with the stream.""" |
| 51 | for kind, data, pos in stream: |
| 52 | yield kind, data, pos |
| 53 | }}} |
| 54 | |
| 55 | Filters can be applied in a number of ways. The simplest is to just call the filter directly: |
| 56 | |
| 57 | {{{ |
| 58 | #!python |
| 59 | stream = noop(stream) |
| 60 | }}} |
| 61 | |
| 62 | The `Stream` class also provides a `filter()` method, which takes an arbitrary number of filter callables and applies them all: |
| 63 | |
| 64 | {{{ |
| 65 | #!python |
| 66 | stream = stream.filter(noop) |
| 67 | }}} |
| 68 | |
| 69 | Finally, filters can also be applied using the ''right shift'' operator (`>>`): |
| 70 | |
| 71 | {{{ |
| 72 | #!python |
| 73 | stream = stream >> noop |
| 74 | }}} |
| 75 | |
| 76 | ''Note: this is only available in the current development version (0.3)'' |
| 77 | |
| 78 | One example of a filter included with Markup is the `HTMLSanitizer` in `markup.filters`. It processes a stream of HTML markup, and strips out any potentially dangerous constructs, such as Javascript event handlers. `HTMLSanitizer` is not a function, but rather a class that implements `__call__`, which means instances of the class are callable. |
| 79 | |
| 80 | Both the `filter()` method and the right-shift operator allow easy chaining of filters: |
| 81 | |
| 82 | {{{ |
| 83 | #!python |
| 84 | from markup.filters import HTMLSanitizer |
| 85 | stream = stream.filter(noop, HTMLSanitizer()) |
| 86 | }}} |
| 87 | |
| 88 | That is equivalent to: |
| 89 | |
| 90 | {{{ |
| 91 | #!python |
| 92 | stream = stream >> noop >> HTMLSanitizer() |
| 93 | }}} |
| 94 | |