Other articles

  1. Using BBC MicroBit accelerometer with Python

    In these days I'm having a bit of fun with BBC MicroBit board and I'm learning how to use the different sensors available. The latest one I wanted to try was the accelerometer. The board can "sense" if you are moving it in any of the 3 dimensional axes: X, Y, Z. According to the documentation there are four methods available that can be used to get these values: microbit.accelerometer.get_values() will return you a tuple with all the 3 values, while  microbit.accelerometer.get_x()microbit.accelerometer.get_y()microbit.accelerometer.get_z() will give you the single values.

    The documentation on the official website doesn't explain much and for example I didn't even know what was the range of the values I can get back from these methods (by the way it's between -1024 and 1024), so I decided to play with the code directly and write a very simple example. The small example I wrote, shows a smile on the board display if you keep it straight and shows a sad face if you bend it.

    This is the result:

    and this is all the needed code of the application:

    In the next days I will try to play with more sensors and to publish other examples.

    read more

    comments

  2. How to write a custom Django Middleware

    To understand how a Django Middleware works we need to remember that the basic architecture of Django is composed by a request and a response. A middleware is something that stays in the middle. Let's give a look to the next diagram, taken from official Django documentation:

    middleware

    Important things to know

    There are four important things to know about middlewares:

    • You need to write a class that just inherit from object
    • The order where you place your middleware in settings.py is important: middlewares are processed from top to bottom during a request and from bottom to top during a response.
    • You don't need to implement all the available methods of a middleware. For example you can just implement process_request and process_template_response
    • If you implement process_request and you decide to return an HttpResponse, all the other middlewares, views etc... will be ignored and only your response will be returned

    Writing a middleware

    In my example I wanted to implement a feature that saves the time when a request is made and the time when a request has been processed, then calculates the time delta and exposes this value in the context so that is accessible from our templates. How to implement a similar feature using a middleware? Here is my example:

    from datetime import datetime
    
    
    class BenchmarkMiddleware(object):
        def process_request(self, request):
            request._request_time = datetime.now()
    
        def process_template_response(self, request, response):
            response_time = request._request_time - datetime.now()
            response.context_data['response_time'] = abs(response_time)
            return response
    

    Please don't care about how I calculated the time. I'm aware that there are better ways to do it, but I just wanted to keep it simple and show how to implement a simple middleware.

    If you want to see a complete example of a project that includes and uses this middleware, here you can find the complete source code: https://github.com/andreagrandi/benchmark-middleware-example

    References

    read more

    comments

  3. Automatically pull updated Docker images and restart containers with docker-puller

    If you use docker.io (or any similar service) to build your Docker containers, it may be possible that, once the new image is generated, you want your Docker host to automatically pull it and restart the container.

    Docker.io gives you the possibility to set a web hook after a successful build. Basically it does a POST on a defined URL and send some informations in JSON format.

    docker-puller listens to these web hooks and can be configured to run a particular script, given a specific hook. It's a very simple service I wrote using Python/Flask. It's also my first Flask application, so if you want to improve it, feel free to send me a pull request on GitHub.

    Note: this is not the only existing service that is able to do this task. I took inspiration from this article http://nathanleclaire.com/blog/2014/08/17/automagical-deploys-from-docker-hub/ and I really tried to customize https://github.com/cpuguy83/dockerhub-webhook-listener for my own needs, but the problem is that dockerhub-webhook-listener is not ready to be used as is (you have to customize it) and I'm not very good with Golang (yet) to be able to do it in little time. This is why I rewrote the service in Python (that is my daily language). I want to thank Brian Goff for the idea and all the people in #docker @ FreeNode for the support.

    How to use docker-puller

    Setting up the service should be quite easy. After you clone the repository from https://github.com/glowdigitalmedia/docker-puller there is a config.json file where you define the host, port, a token and a list of hooks you want to react to. For example:

    {
        "host": "localhost",
        "port": 8000,
        "token": "abc123",
        "hooks": {
            "hello": "scripts/hello.sh"
        }
    }
    

    Create a bash script (in this case it was called hello.sh) and put it under script folder and write the instructions to be executed to pull the new image and restart the container (example):

    docker pull andreagrandi/test:latest
    docker stop test
    docker rm test
    docker run --name test -d -p 8000:80 andreagrandi/test:latest
    

    Once configured, I suggest you to setup a Nginx entry (instructions not covered here) that for example redirect yourhost.com/dockerpuller to localhost:8000 (I would advise to enable SSL too, or people could be able to sniff your token). The service can be started with: "python app.py" (or you can setup a Supervisor script).

    At this point docker-puller is up and running. Go to docker.io automatic build settings and setup a webhook like this: http://yourhost.com/dockerpuller?token=abc123&hook=hello

    Every time docker.io finishes building and pushing your image to the docker registry, it will POST on that URL. docker-puller will catch the POST, check for a valid token, get the hook name and will execute the relative script.

    That's all! I hope this very simple service can be useful to other people and once again, if you want to improve it, I will be glad to accept your pull requests on GitHub.

    read more

    comments

Page 1 / 3 »

social