Testing Flask subdomain routing locally

I’m working on a project in which each customer gets a subdomain for his personal area and thanks to Flask it’s just a matter of using “subdomain” params in routing config. The tricky part is how to setup Flask and the /etc/hosts file in order to make it working on a local development machine.
So the first step is to map 127.0.0.1 to a custom domain name, and the same for a custom subdomain name:

127.0.0.1 localwebsite
127.0.0.1 peter.localwebsite

Of course you can choose any name you like, the only important thing is that the main “fake domain” must match in the “fake subdomain” mapping! (in the case above “localwebsite”)

Then in Flask you have to specify the server name and its port (required!):

app.config['SERVER_NAME'] = 'localwebsite:8080'

In the above scenario I’m mapping the previously “fake domain” by specifying the port on which the Flask server is running (which in my development settings is 8080 and should be 5000 if not specifically defined).
Finally we can register the routes:

@app.route('/', subdomain='<customer>')
def customer_subdomain(customer):
    return 'Customer is: {}'.format(customer)

and if we call peter.localwebsite:8080 it will return “Customer is: peter” as a response! (If we point to localwebsite:8080 the default home page view will be used as expected)

Dynamic (and crazy) Python class runtime definition using built-in type() function

I just realized that thanks to the dynamic nature of Python we can create absurd class names at runtime… even a “?” class!
As everybody knows the following code raises a SyntaxError:

class ?What:
    pass

but… what if we create it dynamically using the built-in function type()?
The main use of type() is to get the type of an object like:

class Foo:
    pass

f = Foo()

type(f) # -> <class '__main__.Foo'>

But, the function can be also used to create a class at runtime by passing: a string representing the class name, a tuple containing superclass(es) from which to inherit and a dictionary containing class attributes.
The previously defined class can be dynamically defined in this way:

type('Foo', (object, ), {})

…the crazy thing is that, since we provide the name as a string, we can dynamically create class names which should be otherwise impossible to define in a classic static way. Example:

question_mark_type = type('?', (object, ), {})
question_mark_instance = question_mark_type()
type(question_mark_instance) # -> <class '__main__.?'>

We have defined a “?” class! :D
Of course you should avoid such an abomination, but this is a cool python feature, since it allows magic things happen. In fact I realized this while testing a dynamic database introspection using SQLAlchemy.
I created tables named with invalid chars like “!table”, “$table”, “#table” and so on (which are allowed in some databases) but I was expecting that the ORM automapping would had failed, since that names can’t be valid class names… but clearly SQLAlchemy makes use of type() in order to create dynamic model classes and so is possible to map bad table names as working Python classes… really cool!

Installing and configuring Linux Mint in dual boot on an Apple Macbook Pro with retina display

Preface

I’ve been an happy mac OSX user for almost 10 years, but recently something in my mind has changed… I don’t know… it’s like if… suddenly I’ve started to feel myself like a child which simulates to drive his father’s car (when it comes to the OS) when the reality is that I’m an adult that actually wants to drive his car and has a regular license and the experience to do that :P
So I decided to try the switch from OSX to Linux.
Linux’s world is a mess, there are a bazillion of distros and several “GUI engine” (I don’t know if this is a correct/acceptable term for talking about GNOME, KDE, Cinnamon and so on, but I’m a newbie in the Penguin’s planet :P) so initially my first target has been Ubuntu since it’s the most famous and supported version (and it has for example a dedicated site on my beloved stackoverflow newtork: askubuntu). Unfortunately most famous and adopted doesn’t mean “the best” (can you hear me windows users?!) and in fact after playing with Ubuntu 15 and 14 and by following a suggestion of a friend I tried Linux Mint and as far I tested it’s far better than Ubuntu: it’s more stable, more responsive, it has a better gui free from the several little bugs I found in Ubuntu, and most important currently it has the best support for HiDPI displays thanks to Cinnamon (Ubuntu’s Unity offers a way to scale the interface in order to match the highest pixel density of a retina, but you have to set it manually, Mint instead automatically detect your monitor and apply the right resolution… moreover even by setting the right resolution in Ubuntu, the login screen will always looks bad and several ui components like icons in notification popups will looks blurred… on Mint all the OS elements will automatically looks gorgeous like in OSX!). So I’m currently running Linux Mint Cinnamon 17.1 (code name “Rebecca”) on my macbook pro retina mid 2012.
I opted for a dual boot installation (with Linux starting as the default system) just to be able to use XCode in the future for an eventual iOS app development or something like that requiring OSX.
The installation (even in dual boot) is quite simple and, despite the many tutorial I found on the web, DOES NOT REQUIRE any esoteric third party software like ReFind, LinuxFlashDriveInstaller, BootMyPenguinToApple and so on (actually I invented all these names since I don’t remember the real ones, but you should get it).
So lets see how to install it…

1. Requirements

1. an external hard disk for backup
2. a flashdrive (less than 2gb needed!)
3. an internet connection
4. a cable adapter (you have to connect the macbook to the internet without wifi since you will install the necessary wifi drivers only later)

2. Backup your stuff

This is a very important step in order to avoid the loss of important files and hours/days/weeks or years of work!
If you never used TimeMachine is time to try it out and create a full backup on an external hard disk.
TimeMachine is awesome, you can restore your previous machine state even if you completely erase your primary disk! But if it’s awesome for OSX it’s pretty useless if you want to move your data to a new OS, since it use an incremental backup system that only OSX can properly use. So my suggestion is to have an external HD with 2 partitions: one for the time machine backup and another to manually copy the files you wish to use/conserve for another OS or for the future.

3. Partitioning (preparing the hard disk for running an additional OS)

Open disk utils (it’s an utility app included in OSX to manage disks), select your machine’s disk and add 2 new partitions (using the “+” button at the bottom of the window), one will be used to install Linux Mint, the second one will be used as swap partition. A swap partition is not mandatory but it’s highly recommend, since for example Linux needs it to allow features like hibernation. So the Linux partition should be at least 20gb, the swap partition a few gb, ideally not more than your available ram (in my case 8gb). You can choose any filesystem type for the new partitions, since we will properly format them during Linux installation. Even the partition name doesn’t matter (I choose “LINUX” and “SWAP”). Once you apply the defined partition scheme, your main partition (where OSX is installed) will be shrinked to make room for the new ones by preserving all the current content on the disk (obviously you should have enough free space on it). The partitioning may requires several minutes depending on the size and disk type of your machine.

4. Create a bootable Linux flash drive

Download the iso from Mint’s website (in my case I downloaded the 64bit Cinnamon edition).
Once downloaded you have to convert the iso into an img.
In the terminal app execute the following commands:

sudo hdiutil convert -format UDRW -o /path/to/mint.img /path/to/mint.iso
sudo mv /path/to/mint.img.dmg /path/to/mint.img

Now you have to write the image to the flash drive. Once the flash drive is plugged into the usb port, run the command:

diskutil list

in order to figure to which disk node it has been assigned to (disks “nodes” are in the form /dev/diskN, where N is an incremental number), then run the command:

diskutil unmountDisk /dev/diskN

(where N is the number related to your flash drive).
Now you have to write the image to the flash drive by running the following command:

sudo dd if=/path/to/mint.img of=/dev/rdiskN bs=1m

Note 1: “rdisk” it’s not a typo, but a trick to speed up the write process
Note 2: this command will replace all the data on the flash drive!
Note 3: it may takes some minutes to complete, and no progress input will be displayed, the only visible feedback will be the flashing cursor in the terminal
Note 4: once finished, or during one of the previous step, OSX may show an alert saying something like “disk X is not readable” and offering an option to format it. In this case just press “ignore” (or anyway the button that dismiss the alert without actions)

5. Installation

Once the image has been written to the flash drive (you will see in the terminal the report of written data once the command has completed his job), restart your mac by holding the alt (option) key pressed once you hear the typical booting sound. You will see a screen from which you can select from which disk to boot, choose your flash drive!
Before installing Linux Mint, ensure that: you are connected to the network via network cable and that your machine is connected to the power source.
By booting your mac using the flash drive containing Linux Mint image, you will “land” to the “portable” version of it (that is a working and ready to try Linux Mint OS). On the desktop you’ll see a DVD icon for the actual installation, double click it and proceed to the real installation.
Once you reach the installation screen “Installation type“, be very careful, this is the most important and “dangerous” step. There is a list of several options, but you have to choose the last one: “something else” (since it allows you to specify exactly what to do).
In the next screen you will see a panel with all available disks/partitions and a combo at the bottom “Device for boot loader installation”.
Now you have to find the partition you previously created for Linux (you should figure this out by reading its size and available space and in my case was “/dev/sd4”), then click on “change”, select a file system (the preferred one for Linux is “Ext4 journaling file system“), check “format partition“, set “/” as mount point, press “OK” and confirm your action.
Then you have to find the partition related to the swap, click “change” and select “use as swap area“.
Finally, change the selected option in “Device for boot loader installation” by specifying the proper Linux partition.
Then proceed with the installation by confirming and following the wizard.
At the end of the installation you will be asked to restart your machine, if you get stuck in a black screen and your machine does not restart… just press enter (it’s an embarrassing “little” bug in the GUI that may happen XD).
Your machine should reboot and automatically load Linux Mint OS (you can boot into Mac OSX by holding alt key during the booting).
Now you should have a working mac OSX/Linux Mint dual boot machine… but for Linux, there are a couple of things to do in order to have a fully working OS… for example you can’t currently use the wifi, but we are going to fix this and other issues in the “post installation” section…

6. Post installation

6.1 Installing updates

Once your machine reboots into Linux Mint, the OS should display an icon in the bar displaying available updates, by clicking it the software manager will open up, select all the available updates and install them.

6.2 Installing missing (wifi) drivers

Open the driver manager (just press the command key or “super” as it’s called in Linux and type “driver manager”), it will shows several drivers available for the NVidia (or whatever graphic card your machine has), but DON’T CHANGE THE DEFAULT DRIVER automatically installed by Mint (which should be the only open source one in the list), since as far I saw and even if it sounds odd, the proprietary drivers on Linux won’t work (black screen once installed and rebooted!). The same problem happens with Ubuntu (both 14 than 15).
However the driver for the “airport extreme” (the wifi), can be safely installed (and it’s the only one, available). Once installed you should be able to connect to the internet using the wifi (if not try rebooting your mac).

6.3 Macbook trackpad, external keyboard and mouse setup

There are some configurations to change and some “hacks” to do in order to have a working and conformable input setup. The trackpad works out of the box, but it doesn’t scroll using two fingers as I was used to do nor it has natural scrolling (inverted scrolling -> move up do go down and vice versa like on a mobile device).
So the first thing to do via GUI is to open the “mouse and touchpad” preference and under “Scrolling / Panel layout” choose “two-finger scrolling” and check “enable horizontal scrolling“. As you can see there is a ready-to-click option “enable natural scrolling” which actually does exactly what it says, but leave it unchecked, because it would break natural scrolling on an Apple Magic Mouse! (we will fix things in order to have a natural scrolling on both soon…)

6.3.1 Pairing that F@$%&*’ Magic Mouse!

Blue tooth pairing is automatically handled by Mint and setting up a (Apple) keyboard is dead simple and fast, you just need to turn the keyboard on and the OS will ask you to type a code on the keyboard for the pairing… BUT, setting up a blue tooth mouse is just… IMPOSSIBLE (via GUI), due to a weird bug, for which once the mouse is discovered and the OS opens a popup to insert the pairing code (which is 0000 by default), as soon you click on the input field in order to write the code, that damned popup gets closed, so the result is that you don’t have the opportunity to provide the code… so pairing fails :(
But, fuck off… let’s take the control and manually pairing the mouse using the terminal (fortunately we need to do this only once)!
We need a couple of packages that provides blue-tooth handling functionalities, so let’s get them:

apt-get install -y bluez-tools bluez-hcidump 

then follow the instructions under “solution”: here. I used that post to fix my problems too, but in my case I simply passed the passcode using the retrieved device mac address and I didn’t added it as “trusted device” as described in the tutorial (anyway my magic mouse is properly recognized each times).

6.3.2 Get rid of the “ctrl+v” that Linux OS automatically assigns to the middle mouse button (and that with an Apple Magic Mouse it’s a pain in the ass!!!)

Yep… the third button click on Linux it’s equivalent to a “paste” command, but using a mouse that doesn’t have physical buttons, accidental ctrl+v are very, very easy (I was going crazy by seeing pieces of urls/comments/variables added to my code each time I used the mouse!).
So, the solution is to remove the third button by the used layout, by running:

sudo sh -c "echo 'pointer = 1 0 3 5 4 7 6 8 9 10 11 12' >> ~/.Xmodmap"
sudo xmodmap ~/.Xmodmap

Buttons are numbered incrementally from 1 to 12 and the sequence from left to right means: button one, button two (so middle button), button 3 and so on… By specifying an invalid (missing) button like 0 or 13 we are removing it’s binding. With this command we are also redefining the order of “buttons” 4, 5, 6, 7 that are those related to scrolling gestures in order to have a natural scrolling effect even on the magic mouse… and this settings will also used for the trackpad… so now all should works perfectly!!!

6.3.4 Configuring specific apps in order to properly handle an HiDPI monitor (retina display)

Cinnamon does a great job in order to display the OS gui properly on an HiDPi monitor, but certain applications (mainly Java and QT ones) don’t look very good. Unfortunately these ones can “fixed” only if the vendor has implemented support for the different display (such JetBrains IDEs, chrome, firefox and so on), to find out the required settings in order to display these applications properly read this great resource on Linux Arch wiki.

6.3.5 Configuring the keyboard in order to use European letters like ü, á, ñ…

On Mac OSX even if you use an US keyboard you can hold a key to select one of it’s related “variants” with “special signs” (for example by pressing and holding “i” you can then select an “í” from an inline tooltip that shows up).
On Mint the only way I found in order to use special letters is to switch from “English (US)” keyboard layout to “English (US, International with dead keys)“, this one allows to print special letters by pressing right alt + letter key (so to print “í”, you have to press “i” + the alt key on the right of the keyboard).
Unfortunately the “International with dead keys” as a strange mappings for quotes and brackets, so I can’t set it as the default layout, instead when I need to type those letters I temporally switch from a layout to another using the icon in the system toolbar… it’s a reasonable effort :^)

AngularJS: centralized application loading status handling using http interceptors

It’s a common need in a JavaScript application (especially a single page app) to show a spinner and/or a message while data is getting retrieved from the server (that is while the ajax call is in progress). In fact an ex colleague asked me how I manage this in AngularJS just a couple of weeks ago and I want to share my implementation since I think that’s the cleanest and more effective way to achieve the goal using native framework’s features. Moreover it’s also useful to handle ajax errors in a centralized and generic way and I’m gonna show that too.
AngularJS has a very useful feature: HTTP Interceptors, these ones are services that get automatically called on each ajax request step (before an ajax call, after an ajax call and so on) once they are registered using the $httpProvider.
So they are the perfect place where to write our logic for generic error handling and loading state, in fact the official documentation says:

For purposes of global error handling, authentication, or any kind of synchronous or asynchronous pre-processing of request or postprocessing of responses, it is desirable to be able to intercept requests before they are handed to the server and responses before they are handed over to the application code that initiated these requests. The interceptors leverage the promise APIs to fulfill this need for both synchronous and asynchronous pre-processing.

So what I do in my app is to create the following interceptor:

angular.module('myapp').
    service('LoadingInterceptor', 
    ['$q', '$rootScope', '$log', 
    function($q, $rootScope, $log) {
        'use strict';

        return {
            request: function(config) {
                $rootScope.loading = true;
                return config;
            },
            requestError: function(rejection) {
                $rootScope.loading = false;
                $log.error('Request error:', rejection);
                return $q.reject(rejection);
            },
            response: function(response) {
                $rootScope.loading = false;
                return response;
            },
            responseError: function(rejection) {
                $rootScope.loading = false;
                $log.error('Response error:', rejection);
                return $q.reject(rejection);
            }
        };
    }]);

It makes use of $rootScope to store the loading state “globally”, which is set to true as soon the request is created (request method) and set to false when the request is invalid (requestError) or the call has been completed (response or responseError).
It also logs errors in case of requestError and responseError.

Then I register the interceptor in the module config() block:

.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('LoadingInterceptor');
}]);

As you can see it’s registered as a simple plain string rather than using the usual dependency injection (AngularJS knows how to properly load the service).

Regarding the display of a message/spinner to the user, in my templates all I have to do is something like:

<div data-ng-if="loading">
    Loading...
</div>

That’s really cool! clean! simple! effective! :)

UPDATE:

I realized that my interceptor doesn’t work properly when concurrent xhr requests are involved.
For example, if a request A starts and then a request B starts, if B completes its job before A, the loading status is defined as “false“. To fix this issue I modified it by tracking the count of initialized requests and completed ones, so the final reliable implementation of the interceptor is the following:

angular.module('crs').service('LoadingInterceptor', ['$q', '$rootScope', '$log', 
function ($q, $rootScope, $log) {
    'use strict';

    var xhrCreations = 0;
    var xhrResolutions = 0;

    function isLoading() {
        return xhrResolutions < xhrCreations;
    }

    function updateStatus() {
        $rootScope.loading = isLoading();
    }

    return {
        request: function (config) {
            xhrCreations++;
            updateStatus();
            return config;
        },
        requestError: function (rejection) {
            xhrResolutions++;
            updateStatus();
            $log.error('Request error:', rejection);
            return $q.reject(rejection);
        },
        response: function (response) {
            xhrResolutions++;
            updateStatus();
            return response;
        },
        responseError: function (rejection) {
            xhrResolutions++;
            updateStatus();
            $log.error('Response error:', rejection);
            return $q.reject(rejection);
        }
    };
}]);

Regular Expressions in Python: how to match english and non english letters

Ok, this is a quick (and I hope super-helpful) tip on how to match foreign languages letters like (ö, è…) in a python regex.
As everybody knows, matching letter signs is just a matter of using [a-z] or \w (the latter will also match underscores!) but unfortunately letters with “decorations” are not matched by these selectors. If you want to match them, you have to use unicode selectors (something like [\u00D8-\u00F6]), but python can automatically match all the unicode variants by simply passing the flag re.UNICODE to compile(). So this:

re.compile('[^\W_]', re.IGNORECASE | re.UNICODE)

will match any english and non english letter.
But let me explain… \w matches letters and underscores, \W (note it’s uppercased) as opposite match all but letters and undescores, so [^\W_] will match letters only (thanks to the negation ^).
Bear in mind: the flag re.UNICODE as reported in python docs :

“Makes several escapes like \w, \b, \s and \d dependent on the Unicode character database”

A stupid demonstration:

# -*- coding: utf-8 -*-
import re

ENGLISH_CHARS = re.compile('[^\W_]', re.IGNORECASE)
ALL_CHARS = re.compile('[^\W_]', re.IGNORECASE | re.UNICODE)

assert len(ENGLISH_CHARS.findall('_àÖÎ_')) == 0
assert len(ALL_CHARS.findall('_àÖÎ_')) == 3

ps: not all languages have implemented the unicode flag, for example JavaScript had not …I love Python :)

UPDATE:
Webucator has published a video based on this post, and as explained in the video, this is no longer required in Python 3, since the default encoding is UTF-8 instead of ASCII! Checkout the video