Controller

You know Controller in before sections, now let access request data and modify response. Get back to app_creation, remove BookCtl and add RootCtl, we have example below explains how to do it:

Built-in controllers in clink.ctl

Example

controller.py
# STEP 1: get clink library
from clink import stamp, mapper, App, AppConf, Controller
from clink.error.http import Http401Error, Http404Error


# STEP 2: get an WSGI server
from wsgiref.simple_server import make_server


# STEP 3: create application configuration and application
conf = AppConf('book-api', 'Hell Corporation', '1st, Hell street')
app = App(conf)


# STEP 4: define component - controllers
# ===[BEGIN] REMOVE BOOKCTL AND ADD ROOTCTL ==================================
@stamp()
@mapper.path('/req')
class RootCtl(Controller):
    @mapper.get('/info')
    def get_info(self, req, res):
        res.body = {
            'path': req.path,
            'query_str': req.query_str,
            'content_type': req.content_type,
            'content_length': req.content_length,
            'server_name': req.server_name,
            'server_port': req.server_port,
            'server_protocol': req.server_protocol,
            'remote_addr': req.remote_addr,
            'header': req.header,
            'body': req.body,
        }

    @mapper.get('/no-content')
    def no_content(self, req, res):
        res.status = 204

    @mapper.get('/not-found')
    def not_found(self, req, res):
        raise Http404Error(req, 'Nothing here')

    @mapper.get('/no-auth')
    def no_auth(self, req, res):
        raise Http401Error(req, 'Go back. You are alien')
# ===[END] REMOVE BOOKCTL AND ADD ROOTCTL ====================================


# STEP 5: add components to application
app.add_ctl(RootCtl)


# STEP 6: load components
app.load()


# STEP 7: serve application on WSGI server
address = 'localhost'
port = 8080
print('Prepare API on http://%s:%i/req/info' % (address, port))
httpd = make_server(address, port, app)
httpd.serve_forever()

Testing

$ python controller.py &> /dev/null &
[1] 6556

$ curl -X GET localhost:8080/req/info; echo
{"query_str": null, "body": null, "header": {"HOST": "localhost:8080",
"ACCEPT": "*/*", "USER_AGENT": "curl/7.38.0"}, "content_type": null,
"remote_addr": "127.0.0.1", "server_name": "localhost",
"server_protocol": "HTTP/1.1", "server_port": 8080, "path": "/req/info",
"content_length": 0}

$ curl -X GET -D - localhost:8080/req/no-content; echo
HTTP/1.0 204 No Content
Date: Sat, 20 May 2017 14:56:20 GMT
Server: WSGIServer/0.2 CPython/3.4.2
Content-Type: application/json
Content-Length: 0

$ curl -X GET localhost:8080/req/not-found; echo
{"status_name": "404 Not Found", "message": "Nothing here", "status": 404}

$ curl -X GET localhost:8080/req/no-auth; echo
{"status_name": "401 Unauthorized", "message": "Go back. You are alien",
"status": 401}

$ kill %1