Requests - renzon/zenwarch GitHub Wiki

Once router.py solves the Routing issue, the next step is write a bridge between http requests and Python code.

The next examples will be writen for a Google App Engine Application. Besides that, the process can be adapted for another contexts

Building one RequestHandler for all Requests

The main idea is that just one RequestHandler to handle all requests, searching for Python scripts based on convention:

In this file, we are delegating almost all request to convention.py. This file is located on project_template folder:

import sys
import os

#Put lib on path, once Google App Engine does not allow doing it directly
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))

import settings
from zen.gae import middleware
import webapp2


class BaseHandler(webapp2.RequestHandler):
    def get(self):
        self.make_convention()

    def post(self):
        self.make_convention()

    def make_convention(self):
        middleware.execute(settings.MIDDLEWARES, self)


app = webapp2.WSGIApplication([("/.*", BaseHandler)], debug=False)

After write the script to handle all request, let´s configure it on app.yaml:

application: zenwarchi
version: 1
runtime: python27
api_version: 1
threadsafe: yes

inbound_services:
- warmup

libraries:
- name: jinja2
  version: "2.6"

- name: webapp2
  version: "2.5.2"

- name: webob
  version: "1.2.3"

- name: markupsafe
  version: "0.15"

- name: setuptools
  version: "0.6c11"

handlers:
- url: /
  script: convention.app

- url: /(.*)static(.*)
  static_files: web/\1static\2
  upload: web/.*static.*

- url: /_ah/warmup
  script: warmup.app

- url: /.*
  script: convention.app

The important concept here is that there will be no need to configure handlers anymore. To add a handler, just create the script files using the framework's convention. Let´s do it writing a Hello World example

Hello World

To make Hello World example, we have to create a home module inside web package. The structure of the project looks like this:

project_template
  web
    home
      index

Now let´s edit home.py:

# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
def index(_resp):
    _resp.write('Hello World')

Run this app and acces it through browser and you must see "Hello Word" message. So the iteration step to add handlers is creating functions without worrying about configuration anymore :D

Let's see next section: Dependency Injection

⚠️ **GitHub.com Fallback** ⚠️