Skip to content
This repository has been archived by the owner on Sep 7, 2018. It is now read-only.

Dive Deeper

Daniel Däschle edited this page Feb 19, 2018 · 11 revisions

Request object

If you need some information from the request you can easly add an attribute to your function.

@on()
def root(req):
    pass

This attribute is a Request object.

Getting json data

@on()
def root(req):
    data = req.json

Getting forms data

@on()
def root(req):
    data = req.form

And other attributes of the request class are:

req.data raw data
req.cookies cookies
req.args URL parameters
req.files From files
req.headers Headers

More at Request and BaseRequest

Shared Directory

If you want to share a directory directly over swapy you can simply use:

...
swapy.shared('shared')
...

In this case the directory shared can be reached over http://yourip/shared. If you use a different directory instead of shared the endpoint remains /shared. For example you can share your css or js files in this directory.

Environment Variables

You need global variables to get access from all modules? Simple use environment variables. It is very simple!

...
swapy.environment({
    'secret_key': 'crypto'
})
...

If you want to access this values you only need to do the follwing.

...
swapy.get_env('secret_key')  # returns 'crypto'
...

If you want to change an environment value during operation you can use swapy.set_env.

...
swapy.set_env('my_key', 'my_value')
...

SSL

This is only for test purposes!

All you need is your IP / Domain and optionally a path to your cert files.

...
swapy.ssl('127.0.0.1')
...

This allows you to use automatically generated SSL certificates for tests. The path parameters have to be defined normally. Otherwise, you have to install the python library OpenSSL using pip or easy_install.

Otherwise, you must add the path to your certificates (without file extensions).

...
swapy.ssl('127.0.0.1', 'path/to/cert')
...

Middlewares

There are actually some built in middlewares available:

  • JsonMiddleware
  • HtmlMiddleware
  • CorsMiddleware
  • ExpectKeysMiddleware (more coming soon)

Using middlewares is easy. First you have to import the desired middleware you want and then use it for all routes.

...
from swapy.middlewares import HtmlMiddleware

swapy.use(HtmlMiddleware)
...

This middleware is only valid for all routes in the module where it is used. If you want to exclude a route from this middleware define it above the use command.

...
# Not affected from JsonMiddleware
@on()
def root():
    return  'Hello swapy!'

use(JsonMiddleware)
...

If you include another module, this is not affected from the middleware. You have to use middlewares in every module seperatly.


You also can add a middleware to a single route. Because middlewares are just only decorators you can decorate the route below the on() decorator.

Example:

...
@on()
@JsonMiddleware
def root():
    return {'message': 'Hello swapy!'}
...

JsonMiddleware

Parses the output from the route to a JSON string.

Possible output types are:

  • str
  • dict
  • list
  • int
  • float
  • None
  • bool

HtmlMiddleware

Appends the Content-Type: application/json header to the response which makes the browser treating the content as HTML.

CorsMiddleware

Appends some CORS headers to the response.

What is CORS? Read this article

ExpectKeysMiddleware

This middleware catches every KeyError and send an error response to the client with status code 400. You can use it when you want to receive a JSON payload which should have some data which you expect.

Warning: It does not serialize the incoming data or return a detailed error to the client.

Exception Handlers

Exception handlers catches errors and return some data to the client.

There are a few built in handlers:

  • DefaultException
  • JsonException

You can use an exception handler by the following code:

from swapy.middlewares import JsonException
import swapy

swapy.error(JsonException)

In this case the exception handler is no decorator. You can only use a handler module specific. This code above catches all error except 404 errors.

For 404 errors you have to use:

...
swapy.not_found(JsonException)
...

This covers 404 errors :)

DefaultException

It simply returns the error as text.

JsonException

It returns the error in a JSON string.

Example:

{
    "message": "TypeError: ..."
}

Config

Using a setting function (like above ssh, include etc.) for everything is maybe not the prettiest solution. In this case you can use the config function.

It is simple like everything else too.

...
config({
    'ssh': '127.0.0.1',
    'use': JsonException,
    'environment': {
        'secret_key': 'i_am_secret'
    }
})
...

You can use everything which is a config function, error and include etc.

You also can use multiple middlewares using a list like:

config({
    'use': [JsonMiddleware, ExpectKeysMiddleware]
})

Cookies

You can get access to cookies on the request object.

@on()
def root(req):
    cookies = req.cookies  # returns a dict
    ...

If you want to set new cookies to the response you have to create the response object manually.

from swapy.wrappers import Response

@on()
def root():
    res = Response('Hello swapy!')
    res.set_cookie('key', 'value')
    return res

Secure Cookie

There are also secure cookies. Gettig secure cookies is like on default cookies.

@on()
def root(req):
    secure_cookies = req.secure_cookie  # returns a dict
    my_value = secure_cookies['key']
    ...

Setting secure cookies is different to default cookies because there is only one cookie which will be set on the clinet. It contains all your data.

@on()
def root(req):
    req.secure_cookie['my_key'] = 'my_value'
    ...

You should never set important data in secure cookies because it isn't save enough. But it is more secure than default cookies :)

Sessions

It is simple like secure cookies. Here a example for setting and for getting values in sessions.

Setting values to a session

@on()
def root(req):
    req.session['my_key'] = 'my_value'
    ...

Getting values from a session

@on()
def root(req):
    my_value = req.session['my_key']
    ...