1Another Do-It-Yourself Framework 2================================ 3 4.. contents:: 5 6Introduction and Audience 7------------------------- 8 9It's been over two years since I wrote the `first version of this tutorial <http://pythonpaste.org/do-it-yourself-framework.html>`_. I decided to give it another run with some of the tools that have come about since then (particularly `WebOb <http://webob.org/>`_). 10 11Sometimes Python is accused of having too many web frameworks. And it's true, there are a lot. That said, I think writing a framework is a useful exercise. It doesn't let you skip over too much without understanding it. It removes the magic. So even if you go on to use another existing framework (which I'd probably advise you do), you'll be able to understand it better if you've written something like it on your own. 12 13This tutorial shows you how to create a web framework of your own, using WSGI and WebOb. No other libraries will be used. 14 15For the longer sections I will try to explain any tricky parts on a line-by line basis following the example. 16 17What Is WSGI? 18------------- 19 20At its simplest WSGI is an interface between web servers and web applications. We'll explain the mechanics of WSGI below, but a higher level view is to say that WSGI lets code pass around web requests in a fairly formal way. That's the simplest summary, but there is more -- WSGI lets you add annotation to the request, and adds some more metadata to the request. 21 22WSGI more specifically is made up of an *application* and a *server*. The application is a function that receives the request and produces the response. The server is the thing that calls the application function. 23 24A very simple application looks like this: 25 26.. code-block:: python 27 28 >>> def application(environ, start_response): 29 ... start_response('200 OK', [('Content-Type', 'text/html')]) 30 ... return ['Hello World!'] 31 32The ``environ`` argument is a dictionary with values like the environment in a CGI request. The header ``Host:``, for instance, goes in ``environ['HTTP_HOST']``. The path is in ``environ['SCRIPT_NAME']`` (which is the path leading *up to* the application), and ``environ['PATH_INFO']`` (the remaining path that the application should interpret). 33 34We won't focus much on the server, but we will use WebOb to handle the application. WebOb in a way has a simple server interface. To use it you create a new request with ``req = webob.Request.blank('http://localhost/test')``, and then call the application with ``resp = req.get_response(app)``. For example: 35 36.. code-block:: python 37 38 >>> from webob import Request 39 >>> req = Request.blank('http://localhost/test') 40 >>> resp = req.get_response(application) 41 >>> print resp 42 200 OK 43 Content-Type: text/html 44 <BLANKLINE> 45 Hello World! 46 47This is an easy way to test applications, and we'll use it to test the framework we're creating. 48 49About WebOb 50----------- 51 52WebOb is a library to create a request and response object. It's centered around the WSGI model. Requests are wrappers around the environment. For example: 53 54.. code-block:: python 55 56 >>> req = Request.blank('http://localhost/test') 57 >>> req.environ['HTTP_HOST'] 58 'localhost:80' 59 >>> req.host 60 'localhost:80' 61 >>> req.path_info 62 '/test' 63 64Responses are objects that represent the... well, response. The status, headers, and body: 65 66.. code-block:: python 67 68 >>> from webob import Response 69 >>> resp = Response(body='Hello World!') 70 >>> resp.content_type 71 'text/html' 72 >>> resp.content_type = 'text/plain' 73 >>> print resp 74 200 OK 75 Content-Length: 12 76 Content-Type: text/plain; charset=UTF-8 77 <BLANKLINE> 78 Hello World! 79 80Responses also happen to be WSGI applications. That means you can call ``resp(environ, start_response)``. Of course it's much less *dynamic* than a normal WSGI application. 81 82These two pieces solve a lot of the more tedious parts of making a framework. They deal with parsing most HTTP headers, generating valid responses, and a number of unicode issues. 83 84Serving Your Application 85------------------------ 86 87While we can test the application using WebOb, you might want to serve the application. Here's the basic recipe, using the `Paste <http://pythonpaste.org>`_ HTTP server: 88 89.. code-block:: python 90 91 if __name__ == '__main__': 92 from paste import httpserver 93 httpserver.serve(app, host='127.0.0.1', port=8080) 94 95you could also use `wsgiref <https://docs.python.org/3/library/wsgiref.html#module-wsgiref.simple_server>`_ from the standard library, but this is mostly appropriate for testing as it is single-threaded: 96 97.. code-block:: python 98 99 if __name__ == '__main__': 100 from wsgiref.simple_server import make_server 101 server = make_server('127.0.0.1', 8080, app) 102 server.serve_forever() 103 104Making A Framework 105------------------ 106 107Well, now we need to start work on our framework. 108 109Here's the basic model we'll be creating: 110 111* We'll define routes that point to controllers 112 113* We'll create a simple framework for creating controllers 114 115Routing 116------- 117 118We'll use explicit routes using URI templates (minus the domains) to match paths. We'll add a little extension that you can use ``{name:regular expression}``, where the named segment must then match that regular expression. The matches will include a "controller" variable, which will be a string like "module_name:function_name". For our examples we'll use a simple blog. 119 120So here's what a route would look like: 121 122.. code-block:: python 123 124 app = Router() 125 app.add_route('/', controller='controllers:index') 126 app.add_route('/{year:\d\d\d\d}/', 127 controller='controllers:archive') 128 app.add_route('/{year:\d\d\d\d}/{month:\d\d}/', 129 controller='controllers:archive') 130 app.add_route('/{year:\d\d\d\d}/{month:\d\d}/{slug}', 131 controller='controllers:view') 132 app.add_route('/post', controller='controllers:post') 133 134To do this we'll need a couple pieces: 135 136* Something to match those URI template things. 137* Something to load the controller 138* The object to patch them together (``Router``) 139 140Routing: Templates 141~~~~~~~~~~~~~~~~~~ 142 143To do the matching, we'll compile those templates to regular expressions. 144 145.. code-block:: python 146 :linenos: 147 148 >>> import re 149 >>> var_regex = re.compile(r''' 150 ... \{ # The exact character "{" 151 ... (\w+) # The variable name (restricted to a-z, 0-9, _) 152 ... (?::([^}]+))? # The optional :regex part 153 ... \} # The exact character "}" 154 ... ''', re.VERBOSE) 155 >>> def template_to_regex(template): 156 ... regex = '' 157 ... last_pos = 0 158 ... for match in var_regex.finditer(template): 159 ... regex += re.escape(template[last_pos:match.start()]) 160 ... var_name = match.group(1) 161 ... expr = match.group(2) or '[^/]+' 162 ... expr = '(?P<%s>%s)' % (var_name, expr) 163 ... regex += expr 164 ... last_pos = match.end() 165 ... regex += re.escape(template[last_pos:]) 166 ... regex = '^%s$' % regex 167 ... return regex 168 169**line 2:** Here we create the regular expression. The ``re.VERBOSE`` flag makes the regular expression parser ignore whitespace and allow comments, so we can avoid some of the feel of line-noise. This matches any variables, i.e., ``{var:regex}`` (where ``:regex`` is optional). Note that there are two groups we capture: ``match.group(1)`` will be the variable name, and ``match.group(2)`` will be the regular expression (or None when there is no regular expression). Note that ``(?:...)?`` means that the section is optional. 170 171**line 10**: This variable will hold the regular expression that we are creating. 172 173**line 11**: This contains the position of the end of the last match. 174 175**line 12**: The ``finditer`` method yields all the matches. 176 177**line 13**: We're getting all the non-``{}`` text from after the last match, up to the beginning of this match. We call ``re.escape`` on that text, which escapes any characters that have special meaning. So ``.html`` will be escaped as ``\.html``. 178 179**line 14**: The first match is the variable name. 180 181**line 15**: ``expr`` is the regular expression we'll match against, the optional second match. The default is ``[^/]+``, which matches any non-empty, non-/ string. Which seems like a reasonable default to me. 182 183**line 16**: Here we create the actual regular expression. ``(?P<name>...)`` is a grouped expression that is named. When you get a match, you can look at ``match.groupdict()`` and get the names and values. 184 185**line 17, 18**: We add the expression on to the complete regular expression and save the last position. 186 187**line 19**: We add remaining non-variable text to the regular expression. 188 189**line 20**: And then we make the regular expression match the complete string (``^`` to force it to match from the start, ``$`` to make sure it matches up to the end). 190 191To test it we can try some translations. You could put these directly in the docstring of the ``template_to_regex`` function and use `doctest <http://python.org/doc/current/lib/module-doctest.html>`_ to test that. But I'm using doctest to test *this* document, so I can't put a docstring doctest inside the doctest itself. Anyway, here's what a test looks like: 192 193.. code-block:: python 194 195 >>> print template_to_regex('/a/static/path') 196 ^\/a\/static\/path$ 197 >>> print template_to_regex('/{year:\d\d\d\d}/{month:\d\d}/{slug}') 198 ^\/(?P<year>\d\d\d\d)\/(?P<month>\d\d)\/(?P<slug>[^/]+)$ 199 200Routing: controller loading 201~~~~~~~~~~~~~~~~~~~~~~~~~~~ 202 203To load controllers we have to import the module, then get the function out of it. We'll use the ``__import__`` builtin to import the module. The return value of ``__import__`` isn't very useful, but it puts the module into ``sys.modules``, a dictionary of all the loaded modules. 204 205Also, some people don't know how exactly the string method ``split`` works. It takes two arguments -- the first is the character to split on, and the second is the maximum number of splits to do. We want to split on just the first ``:`` character, so we'll use a maximum number of splits of 1. 206 207.. code-block:: python 208 209 >>> import sys 210 >>> def load_controller(string): 211 ... module_name, func_name = string.split(':', 1) 212 ... __import__(module_name) 213 ... module = sys.modules[module_name] 214 ... func = getattr(module, func_name) 215 ... return func 216 217Routing: putting it together 218~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 219 220Now, the ``Router`` class. The class has the ``add_route`` method, and also a ``__call__`` method. That ``__call__`` method makes the Router object itself a WSGI application. So when a request comes in, it looks at ``PATH_INFO`` (also known as ``req.path_info``) and hands off the request to the controller that matches that path. 221 222.. code-block:: python 223 :linenos: 224 225 >>> from webob import Request 226 >>> from webob import exc 227 >>> class Router(object): 228 ... def __init__(self): 229 ... self.routes = [] 230 ... 231 ... def add_route(self, template, controller, **vars): 232 ... if isinstance(controller, basestring): 233 ... controller = load_controller(controller) 234 ... self.routes.append((re.compile(template_to_regex(template)), 235 ... controller, 236 ... vars)) 237 ... 238 ... def __call__(self, environ, start_response): 239 ... req = Request(environ) 240 ... for regex, controller, vars in self.routes: 241 ... match = regex.match(req.path_info) 242 ... if match: 243 ... req.urlvars = match.groupdict() 244 ... req.urlvars.update(vars) 245 ... return controller(environ, start_response) 246 ... return exc.HTTPNotFound()(environ, start_response) 247 248**line 5**: We are going to keep the route options in an ordered list. Each item will be ``(regex, controller, vars)``: ``regex`` is the regular expression object to match against, ``controller`` is the controller to run, and ``vars`` are any extra (constant) variables. 249 250**line 8, 9**: We will allow you to call ``add_route`` with a string (that will be imported) or a controller object. We test for a string here, and then import it if necessary. 251 252**line 13**: Here we add a ``__call__`` method. This is the method used when you call an object like a function. You should recognize this as the WSGI signature. 253 254**line 14**: We create a request object. Note we'll only use this request object in this function; if the controller wants a request object it'll have to make on of its own. 255 256**line 16**: We test the regular expression against ``req.path_info``. This is the same as ``environ['PATH_INFO']``. That's all the request path left to be processed. 257 258**line 18**: We set ``req.urlvars`` to the dictionary of matches in the regular expression. This variable actually maps to ``environ['wsgiorg.routing_args']``. Any attributes you set on a request will, in one way or another, map to the environment dictionary: the request holds no state of its own. 259 260**line 19**: We also add in any explicit variables passed in through ``add_route()``. 261 262**line 20**: Then we call the controller as a WSGI application itself. Any fancy framework stuff the controller wants to do, it'll have to do itself. 263 264**line 21**: If nothing matches, we return a 404 Not Found response. ``webob.exc.HTTPNotFound()`` is a WSGI application that returns 404 responses. You could add a message too, like ``webob.exc.HTTPNotFound('No route matched')``. Then, of course, we call the application. 265 266Controllers 267----------- 268 269The router just passes the request on to the controller, so the controllers are themselves just WSGI applications. But we'll want to set up something to make those applications friendlier to write. 270 271To do that we'll write a `decorator <http://www.ddj.com/web-development/184406073>`_. A decorator is a function that wraps another function. After decoration the function will be a WSGI application, but it will be decorating a function with a signature like ``controller_func(req, **urlvars)``. The controller function will return a response object (which, remember, is a WSGI application on its own). 272 273.. code-block:: python 274 :linenos: 275 276 >>> from webob import Request, Response 277 >>> from webob import exc 278 >>> def controller(func): 279 ... def replacement(environ, start_response): 280 ... req = Request(environ) 281 ... try: 282 ... resp = func(req, **req.urlvars) 283 ... except exc.HTTPException, e: 284 ... resp = e 285 ... if isinstance(resp, basestring): 286 ... resp = Response(body=resp) 287 ... return resp(environ, start_response) 288 ... return replacement 289 290**line 3**: This is the typical signature for a decorator -- it takes one function as an argument, and returns a wrapped function. 291 292**line 4**: This is the replacement function we'll return. This is called a `closure <http://en.wikipedia.org/wiki/Closure_(computer_science)>`_ -- this function will have access to ``func``, and everytime you decorate a new function there will be a new ``replacement`` function with its own value of ``func``. As you can see, this is a WSGI application. 293 294**line 5**: We create a request. 295 296**line 6**: Here we catch any ``webob.exc.HTTPException`` exceptions. This is so you can do ``raise webob.exc.HTTPNotFound()`` in your function. These exceptions are themselves WSGI applications. 297 298**line 7**: We call the function with the request object, any any variables in ``req.urlvars``. And we get back a response. 299 300**line 10**: We'll allow the function to return a full response object, or just a string. If they return a string, we'll create a ``Response`` object with that (and with the standard ``200 OK`` status, ``text/html`` content type, and ``utf8`` charset/encoding). 301 302**line 12**: We pass the request on to the response. Which *also* happens to be a WSGI application. WSGI applications are falling from the sky! 303 304**line 13**: We return the function object itself, which will take the place of the function. 305 306You use this controller like: 307 308.. code-block:: python 309 310 >>> @controller 311 ... def index(req): 312 ... return 'This is the index' 313 314Putting It Together 315------------------- 316 317Now we'll show a basic application. Just a hello world application for now. Note that this document is the module ``__main__``. 318 319.. code-block:: python 320 321 >>> @controller 322 ... def hello(req): 323 ... if req.method == 'POST': 324 ... return 'Hello %s!' % req.params['name'] 325 ... elif req.method == 'GET': 326 ... return '''<form method="POST"> 327 ... You're name: <input type="text" name="name"> 328 ... <input type="submit"> 329 ... </form>''' 330 >>> hello_world = Router() 331 >>> hello_world.add_route('/', controller=hello) 332 333Now let's test that application: 334 335.. code-block:: python 336 337 >>> req = Request.blank('/') 338 >>> resp = req.get_response(hello_world) 339 >>> print resp 340 200 OK 341 Content-Type: text/html; charset=UTF-8 342 Content-Length: 131 343 <BLANKLINE> 344 <form method="POST"> 345 You're name: <input type="text" name="name"> 346 <input type="submit"> 347 </form> 348 >>> req.method = 'POST' 349 >>> req.body = 'name=Ian' 350 >>> resp = req.get_response(hello_world) 351 >>> print resp 352 200 OK 353 Content-Type: text/html; charset=UTF-8 354 Content-Length: 10 355 <BLANKLINE> 356 Hello Ian! 357 358 359Another Controller 360------------------ 361 362There's another pattern that might be interesting to try for a controller. Instead of a function, we can make a class with methods like ``get``, ``post``, etc. The ``urlvars`` will be used to instantiate the class. 363 364We could do this as a superclass, but the implementation will be more elegant as a wrapper, like the decorator is a wrapper. Python 3.0 will add `class decorators <http://www.python.org/dev/peps/pep-3129/>`_ which will work like this. 365 366We'll allow an extra ``action`` variable, which will define the method (actually ``action_method``, where ``_method`` is the request method). If no action is given, we'll use just the method (i.e., ``get``, ``post``, etc). 367 368.. code-block:: python 369 :linenos: 370 371 >>> def rest_controller(cls): 372 ... def replacement(environ, start_response): 373 ... req = Request(environ) 374 ... try: 375 ... instance = cls(req, **req.urlvars) 376 ... action = req.urlvars.get('action') 377 ... if action: 378 ... action += '_' + req.method.lower() 379 ... else: 380 ... action = req.method.lower() 381 ... try: 382 ... method = getattr(instance, action) 383 ... except AttributeError: 384 ... raise exc.HTTPNotFound("No action %s" % action) 385 ... resp = method() 386 ... if isinstance(resp, basestring): 387 ... resp = Response(body=resp) 388 ... except exc.HTTPException, e: 389 ... resp = e 390 ... return resp(environ, start_response) 391 ... return replacement 392 393**line 1**: Here we're kind of decorating a class. But really we'll just create a WSGI application wrapper. 394 395**line 2-4**: The replacement WSGI application, also a closure. And we create a request and catch exceptions, just like in the decorator. 396 397**line 5**: We instantiate the class with both the request and ``req.urlvars`` to initialize it. The instance will only be used for one request. (Note that the *instance* then doesn't have to be thread safe.) 398 399**line 6**: We get the action variable out, if there is one. 400 401**line 7, 8**: If there was one, we'll use the method name ``{action}_{method}``... 402 403**line 8, 9**: ... otherwise we'll use just the method for the method name. 404 405**line 10-13**: We'll get the method from the instance, or respond with a 404 error if there is not such method. 406 407**line 14**: Call the method, get the response 408 409**line 15, 16**: If the response is just a string, create a full response object from it. 410 411**line 19**: and then we forward the request... 412 413**line 20**: ... and return the wrapper object we've created. 414 415Here's the hello world: 416 417.. code-block:: python 418 419 >>> class Hello(object): 420 ... def __init__(self, req): 421 ... self.request = req 422 ... def get(self): 423 ... return '''<form method="POST"> 424 ... You're name: <input type="text" name="name"> 425 ... <input type="submit"> 426 ... </form>''' 427 ... def post(self): 428 ... return 'Hello %s!' % self.request.params['name'] 429 >>> hello = rest_controller(Hello) 430 431We'll run the same test as before: 432 433.. code-block:: python 434 435 >>> hello_world = Router() 436 >>> hello_world.add_route('/', controller=hello) 437 >>> req = Request.blank('/') 438 >>> resp = req.get_response(hello_world) 439 >>> print resp 440 200 OK 441 Content-Type: text/html; charset=UTF-8 442 Content-Length: 131 443 <BLANKLINE> 444 <form method="POST"> 445 You're name: <input type="text" name="name"> 446 <input type="submit"> 447 </form> 448 >>> req.method = 'POST' 449 >>> req.body = 'name=Ian' 450 >>> resp = req.get_response(hello_world) 451 >>> print resp 452 200 OK 453 Content-Type: text/html; charset=UTF-8 454 Content-Length: 10 455 <BLANKLINE> 456 Hello Ian! 457 458URL Generation and Request Access 459--------------------------------- 460 461You can use hard-coded links in your HTML, but this can have problems. Relative links are hard to manage, and absolute links presume that your application lives at a particular location. WSGI gives a variable ``SCRIPT_NAME``, which is the portion of the path that led up to this application. If you are writing a blog application, for instance, someone might want to install it at ``/blog/``, and then SCRIPT_NAME would be ``"/blog"``. We should generate links with that in mind. 462 463The base URL using SCRIPT_NAME is ``req.application_url``. So, if we have access to the request we can make a URL. But what if we don't have access? 464 465We can use thread-local variables to make it easy for any function to get access to the currect request. A "thread-local" variable is a variable whose value is tracked separately for each thread, so if there are multiple requests in different threads, their requests won't clobber each other. 466 467The basic means of using a thread-local variable is ``threading.local()``. This creates a blank object that can have thread-local attributes assigned to it. I find the best way to get *at* a thread-local value is with a function, as this makes it clear that you are fetching the object, as opposed to getting at some global object. 468 469Here's the basic structure for the local: 470 471.. code-block:: python 472 473 >>> import threading 474 >>> class Localized(object): 475 ... def __init__(self): 476 ... self.local = threading.local() 477 ... def register(self, object): 478 ... self.local.object = object 479 ... def unregister(self): 480 ... del self.local.object 481 ... def __call__(self): 482 ... try: 483 ... return self.local.object 484 ... except AttributeError: 485 ... raise TypeError("No object has been registered for this thread") 486 >>> get_request = Localized() 487 488Now we need some *middleware* to register the request object. Middleware is something that wraps an application, possibly modifying the request on the way in or the way out. In a sense the ``Router`` object was middleware, though not exactly because it didn't wrap a single application. 489 490This registration middleware looks like: 491 492.. code-block:: python 493 494 >>> class RegisterRequest(object): 495 ... def __init__(self, app): 496 ... self.app = app 497 ... def __call__(self, environ, start_response): 498 ... req = Request(environ) 499 ... get_request.register(req) 500 ... try: 501 ... return self.app(environ, start_response) 502 ... finally: 503 ... get_request.unregister() 504 505Now if we do: 506 507 >>> hello_world = RegisterRequest(hello_world) 508 509then the request will be registered each time. Now, lets create a URL generation function: 510 511.. code-block:: python 512 513 >>> import urllib 514 >>> def url(*segments, **vars): 515 ... base_url = get_request().application_url 516 ... path = '/'.join(str(s) for s in segments) 517 ... if not path.startswith('/'): 518 ... path = '/' + path 519 ... if vars: 520 ... path += '?' + urllib.urlencode(vars) 521 ... return base_url + path 522 523Now, to test: 524 525.. code-block:: python 526 527 >>> get_request.register(Request.blank('http://localhost/')) 528 >>> url('article', 1) 529 'http://localhost/article/1' 530 >>> url('search', q='some query') 531 'http://localhost/search?q=some+query' 532 533Templating 534---------- 535 536Well, we don't *really* need to factor templating into our framework. After all, you return a string from your controller, and you can figure out on your own how to get a rendered string from a template. 537 538But we'll add a little helper, because I think it shows a clever trick. 539 540We'll use `Tempita <http://pythonpaste.org/tempita/>`_ for templating, mostly because it's very simplistic about how it does loading. The basic form is: 541 542.. code-block:: python 543 544 import tempita 545 template = tempita.HTMLTemplate.from_filename('some-file.html') 546 547But we'll be implementing a function ``render(template_name, **vars)`` that will render the named template, treating it as a path *relative to the location of the render() call*. That's the trick. 548 549To do that we use ``sys._getframe``, which is a way to look at information in the calling scope. Generally this is frowned upon, but I think this case is justifiable. 550 551We'll also let you pass an instantiated template in instead of a template name, which will be useful in places like a doctest where there aren't other files easily accessible. 552 553.. code-block:: python 554 555 >>> import os 556 >>> import tempita #doctest: +SKIP 557 >>> def render(template, **vars): 558 ... if isinstance(template, basestring): 559 ... caller_location = sys._getframe(1).f_globals['__file__'] 560 ... filename = os.path.join(os.path.dirname(caller_location), template) 561 ... template = tempita.HTMLTemplate.from_filename(filename) 562 ... vars.setdefault('request', get_request()) 563 ... return template.substitute(vars) 564 565Conclusion 566---------- 567 568Well, that's a framework. Ta-da! 569 570Of course, this doesn't deal with some other stuff. In particular: 571 572* Configuration 573* Making your routes debuggable 574* Exception catching and other basic infrastructure 575* Database connections 576* Form handling 577* Authentication 578 579But, for now, that's outside the scope of this document. 580 581