Evolution of calling Python from Node

A bit of disclaimer here: I just started learning Node.js from this project so still consider myself a very bad Node.js developer. There might be errors or things I’m not aware of.

A bit of background

At Geoblink, we have 3 different tech teams:

  • Infra, which I won’t talk about here
  • Core, the web team working on the front-end and back-end of the app. They control every of the app itself, the looks, the interactions, the business logic, etc… They use Node.js everywhere and master it completely.
  • Data, doing data things like data-science, data-engineering, data-mining or data-cleaning… This is the team I’m in. A majority of us primarily use Python, even if some prefer Scala or R or Java…

How does the data go from the inside of the brain of a data scientist to the screen of a Geoblink user? Well usually, the data scientist thinks of a solution, write some Python code to do it, this Python code will modify a database, a database that the Core team will make use of to beautifully rendered data. So, the usual flow is data scientist -> Python -> Postgres Database -> Node.js -> end user.

But when I joined, we started to need to make a Node.js service and a Python process talk to each other directly. The database in-between would be really superfluous, add a lot complexity, and plumb the whole service speed. That is because we needed some tools written by a Python guy to be called within a service written by a JS guy.

In this post I will cover how the communication between Python and Node.js evolved over time, as we had to implement this communication in different projects.

The ‘brute’ solution: bash script

The first Python tool we connected to Node was a heavy statistical model. It applies a lot of pre-processing and data-cleaning before giving the actual output and rewriting it into Node.js would have cost a lot of time and efforts.

The solution we came up with was to run it via the `spawn` function of `child_process` of Node.js.

We rewrote the input/output of the Python tool so that it would consume JSON from `stdin` and produce a JSON in `stdout`. Capture `stdout` from Node.js and you got a working tool! But if you do that, you might have problems with `PYTHON_PATH` or with encoding (working with Spanish and French addresses implies caring about accented letters. Enforcing UTF-8 encoding can help here). So we changed how we made the call from a Python file to a Bash file where we would export a valid `PYTHON_PATH` and do other operations.

Good thing:
* You control everything

Bad thing:
* You have to control everything

From the Node side:

const spawn = require('child_process').spawn
const toolParams = JSON.stringify(params)
const pythonProcess = spawn('bash', [config.tool.path, toolParams], {})
const stdout = []
const stderr = []

pythonProcess.stdout.on('data', data => stdout.push(data.toString()))
pythonProcess.stderr.on('data', data => stderr.push(data.toString()))

pythonProcess.on('close', (code) => {
if (code !== 0) {
const errorMessage = stderr.join('')
return reject(errorMessage)
const pythonResult = JSON.parse(stdout.join(''))
// Exploit pythonResult

Intermediate Bash script:

#!/usr/bin/env bash
export PYTHON_PATH=/some/location/:$PYTHONPATH

python3 run_tool.py $@ || exit 1

From the Python side:

import sys
import json

tool_params = json.loads(sys.argv[1])
result = do_something(tool_params)
json_output = json.dumps(result)

The ‘let-the-experts-do’ solution: python-shell

Some time later, another challenge arrived: Our service had to execute a lot of small Python scripts, each one very different from the others, each with their dependencies, some of them at the same time, but all returning the same type of data.

This time, I remember deciding to fetch a package to do the job for us. In the Python universe, most of your problems can be solved by a `import antigravity`. So I went to `npm` and found `python-shell` (https://github.com/extrabacon/python-shell) that seemed to do the job.

It works a bit like our previous solution: it sends the parameters to the Python script via `stdin` and gets the output via `stdout`. But, it can also support binary files, show tracebacks or execute the Python process in a child process. Most importantly, it is well tested and proven to work. With that part taken care of, the only thing left was to agree with the Python developers on a common way of writing the input/output of their scripts.

Good thing:
* Your job is reduced to understanding and using a library
* The library is done by people who probably spent more time
than you thinking about the problem

Bad thing:
* You are dependent on a library, its bugs and security failures included
* You are limited by the possibilities of the library (unless you expand it)

From the Node.js side:

const PythonShell = require('python-shell')

const pythonOptions = {
mode: 'json',
scriptPath: '/some/location/small_script.py',
pythonPath: '/usr/bin/python3'
const pyshell = new PythonShell(pythonParams.filepath, pythonOptions)
const pythonData = []

pyshell.on('message', function (message) {
pythonData = message

pyshell.end(function (err) {
if (err) {
throw err
// Exploit pythonData

From the Python side:

import sys
import json

data = do_something()

print(json.dumps(data, ensure_ascii=False))


Our most recent solution: micro-services

Fast-forward a few months and a new project now required us to connect another tool to a Node.js service. This time, the Python tool we had to connect was a heavy application, another statistical model.
It has these characteristics:

  • When launched, it occupies a lot of memory
  • The launching is not instantaneous
  • It is (kind of) slow (takes seconds to produce a result)
  • It requires a lot of dependencies

It seemed like a dreamed opportunity to build a Python service!

To avoid complexity, we decided to run the service in our local network. We separated the Python code into the loading of resources and the actual use of the tool. Then we prepared it so it would consume and produce a JSON, before agreeing on an endpoint and a JSON format.

There are ton of resources to explain how to deploy a statistical model in a service. Most of them will explain very well how to do it with Flask (http://flask.pocoo.org/). But oftentimes, they will miss one important point about Flask:

Flask’s built-in server is not suitable for production (from Flask documentation)

You need to connect your Flask service to a WSGI HTTP server to scale correctly. If you choose a standalone solution, you can choose between Gunicorn (the one we choose), uWSGI, Twisted, etc…

Good thing:
* Scalable, fully reusable component
* Separated concerns

Bad thing:
* Writing a fully functional service can take some time
(don’t skip security, logging or deploying steps)
* Demands DevOps work
* HTTP request can be slow

From the Node.js side (classic HTTP request):

const request = require('request')

const options = {
json: true,
body: {variable: value}
const pythonResult = request.post(options, function (err, response, body) {
if (err) {
throw err
if (response.statusCode === 200) {
// Exploit body

From the Python side (no WSGI setup shown):

from flask import Flask, request
from myproject.models import my_model
app = Flask(__name__)

@app.route(rule='/predict', methods=['POST'])
def do_prediction():
input_sent = request.json
result = my_model.predict(input_sent)
return result, 200

if __name__ == '__main__':

Key takeaways

Do you want to control exactly the context in which Python is called?
Write a Bash script.

Do you want an out-of-the-box solution?
Search for an already implemented library or package.

Do you want a scalable solution, something you can easily reuse in you app?
Take the time to create a micro-service.

I like the similarities between biological evolution and choosing a solution in software engineering. There is not really a solution better than the other, but rather the best solution is the one that best fits your needs.
Building a micro-service is cool, but it may not be adapted to the problem you want to solve (and will be more complex and take longer to build).

Thanks for reading.


Denis Vivies – Data Science

How to scrape a website

If you came to this page and you feel like extracting content from a webpage for any good (and legal, be very careful with this as there are several lawsuits currently in courts) reason, you have landed to the right place: here is our Web Scraper tutorial! At Geoblink, culture is one of our key values…Victor Hugo, Pedro Almodovar, Marco Asensio… Our Geoblinkers like to scrape the list of the upcoming cultural events so we don’t miss any of them even during the World Cup. Here, we offer you the opportunity to be a Geoblink monkey and scrape some cultural data

Ok, imagine that you want to know which cultural events are going to happen in Madrid during the next month. You can find every culture and entertainment events sorted by district on the webpage https://www.madridcultura.es/. At Geoblink, we like to use the incredible WebScraper to make our lists of cultural events.

Basically, WebScraper is a Google Chrome Extension. You can install it here: https://chrome.google.com/webstore/detail/web-scraper

Ok, let’s dive deep into the Madrid cultural experience:

1) Open WebScraping

Open the Developer tools of Google Chrome Browser in the customize panel or just type Ctrl+Shift+i. Then click on the Web Scraper Headless on the top of the banner.


2) Create a Sitemap

Click on the option Create new sitemap, fill a Sitemap name and then select a Start Url…. And let’s scrape

3) Add new selector

Webscraper works as a tree graph, where you have to create nodes that contain more nodes with information. There are different types of selectors, each one works with various characteristics and, depending on the object that you want to choose, you are to select a specific type….which may be a bit tricky at times. The most common types of selectors are Text, Links, and Element (that’s what we are gonna use for this tutorial) but, sometimes it’s necessary to use Element Click or Element Attribute.

We’re going to create this selector graph by choosing a Selector Link that matches each district of Madrid. Click on the button ‘Add new selector’ and complete the following options:

  • Id: Name of the node ( for this example ‘district_links’)
  • Type: Select the kind of node ( chose ‘Link’)
  • Selector : click on the button Select and choose the link that you want to go. If there are more than one you can select all the links by selecting various links. Awhen you are done selecting, click on…
  •  Done selecting! 🙂
  • In order to save the selection. If there is more than one link, you have to match the Multiple option.

To make sure you’re on track, glance at the Data preview and the Element preview. If you can’t see what you expect, well first, it sucks, and then you should scroll up to improve things 🙂

To save all click on the Save selector button.

4) Create a selector element

Click on the saved selector. It appears that you can create more nodes inside. If you go inside one district link you can see that there is more than one activity on the main page. For this example it’s necessary to have an element selector that compiles all the information of the different events.

To create that, it’s the same as the previous example, but now you have to choose Element in the type option. To select all the elements of the page, you have to click on the Select button, mark all the boxes and then choose the Multiple option.

5) Define the information of the event

Again, if you click inside the previous selector, you can create more. At this point, you want to define the different information of the event, like name, date, place. To do that, create one selector for each data choosing Text on the selector type. You can also create a Link selector to obtain more information regarding the event (as the address and the event web page).

6) Pagination

If you have followed the previous steps, you have built a tree graph for the main page of every district. But, if you look at the top of the page, you can see that there are more than one page per district. That’s the reason why pagination is needed.

To create accurate pagination, you have to go to the beginning of the tree, to the same step, then choose Element Selector, then create a Link Selector and pick on the different pages.

After that you need to edit the Event Element and modify its Parents Selector by selecting the previous node and the pagination selector that you have just created.

7) Let’s Scrape

You have finished building the Sitemap, so let’s scrape and see what happens. Click on the button Scrape and choose a Request Interval and Page load delay. The default values work, but sometimes it’s necessary to modify those. So, click on Start Scraping and a pop up should appear.

It’s recommended to click on the Browser button to see how it works and to check everything pans out well.

8) Export the results

The pop up window will close at the end of the scrape. So when it happens, you can download the data. Go to Export data as CSV, and click on Download now! A CSV will be downloaded with all the data of the cultural events in Madrid. After that, it’s recommended that you clean the data a little bit because some columns with links are added in the process. Also, you can download the Sitemap that you have just created.

Eventually you’ll get a nice CSV with almost 600 differents events for the next month in Madrid !

Alejandro Cantera – Data Acquisition

Nicolas Planchon – Data Acquisition

Encrypting a directory in Linux

Safety is something we developers care about. In this modern life our most valuable information is in our electronic devices, and if you are reading this you probably use Linux. Then yes, you found the proper post to keep your secrets safe from the bad guys.

Supposing you use Ubuntu I’ll explain how to encrypt the folder where you keep stuff you don’t want anyone to have access to – for example if someone steals your laptop.

For this task we’ll use eCrypfs. It’s a stacked filesystem for Linux. It can be mounted in a single directory and it does not not require a separate partition.

The mechanism of encryption will be based in mounting the folder using eCryptfs. Once the directory has been mounted with the tool you can manage it as if it was an standard folder. When you finish your work and you want to keep the files inaccessible you need to unmount the directory. If you want to keep using the files you need to mount the folder again.

Preparation steps:

Install eCryptfs

sudo apt-get install ecryptfs-utils

Create the required folders and change their permissions

mkdir ~/.private ~/private
chmod 0700 ~/.private ~/private

Initialize the folder mounting

Initialize eCryptfs (1 1 n n yes yes) (Grab ecryptfs_sig and remember your passphrase)

mount -t ecryptfs ~/.private ~/private
WARNING: Based on the contents of [/root/.ecryptfs/sig-cache.txt],
it looks like you have never mounted with this key 
before. This could mean that you have typed your 
passphrase wrong.

Would you like to proceed with the mount (yes/no)? : yes

Would you like to append sig [2f5efa91218fe4d3] to
in order to avoid this warning in the future (yes/no)? : yes
Successfully appended new sig to user sig cache file
Mounted eCryptfs

Once the folder has been mounted you can add your files.

The file /root/.ecryptfsrc that saves your preferences will be automatically created. It should look like the image shown below. Check that no passphrase location is in the file, if you see it delete the line:

If you need the ecryptfs_sig it is located in: 



Now when you want to unmount your folder, so that nobody can access it:

sudo umount ~/private

Get your UID

id -u

Append one entry to /etc/fstab (use your UID and SIG obtained in previous steps)

# eCryptfs $HOME/.private mounted to $HOME/private
 /home/foo/.private /home/foo/private ecryptfs rw,noauto,nofail,uid=1000,umask=0077,relatime,ecryptfs_sig=2f5efa91218fe4d3,ecryptfs_cipher=aes,ecryptfs_key_bytes=16,ecryptfs_unlink_sigs,ecryptfs_passthrough=no,ecryptfs_enable_filename_crypto=no 0 0

Ready to use


And to remount, so that you can read the data again:

sudo mount -t ecryptfs ~/private

You’ll be asked to insert your passphrase every time you want to mount your folder. I hope you chose a safe one.

If you type wrong the mount passphrase then you need to unmount the folder in order to be able to mount it correctly again.

sudo mount -t ecryptfs ~/private/ (wrong passphrase)
sudo umount ~/private/
sudo mount -t ecryptfs ~/private/ (right passphrase)

And this is it.

In conclusion, if you are like me and has villain enemies all around the globe it’s worth the 10 minute setup. Your data will be in a safer place and you’ll have a better sleep.

You’re welcome.

Useful links:



By Diego Borchers – DevOps Engineer

From AngularJS to Vue without dying in the attempt

You should know by now that here at Geoblink we work with a humongous amount of data, most of which has to be beautifully displayed across the whole app. That means that, besides needing a good performance on our backend to serve that data, we need a good performance on the browser side to process it and render it to our users in the fastest way possible.

Until now, and still for months to come, we’ve been relying on AngularJS as our frontend framework of choice. Needless to say, it’s been a 3 years relationship and generally speaking, we’re really happy with it. It’s a robust system, incredibly well supported even though there are 3 new versions ahead of it and easy to work with.

However, with apps growing bigger and becoming each time more and more common to do most of the calculations on the browser, we started to worry about the app performance had we decided to continue with AngularJS forever. Taking that into account, we started looking for other possibilities. Considering the size of our application, we didn’t even consider migrating to the newest versions of Angular, since the breaking changes were so big (completely different framework really) that we would’ve needed months to make the change. Of course we considered React, having that huge ecosystem and with great state management tools like redux, it was something to bear in mind. Yet we were reluctant, since we didn’t think combining both technologies would really be successful. We needed something that we could start working with progressively, instead of building a new application from the ground up. And then we ‘viewed’ VueJS (pun intended).

We had the chance of working with Vue in one of our so called Geothons, and we fell in love IMMEDIATELY. The performance improvements were astonishing, and the development speed increased incredibly fast, even though none us had previously worked with it. Plus, the progressive part of the framework was just what we needed. Start developing with this framework while we kept maintaining the main parts of our app with AngularJS. It was a no brainer.

Download Angular video

Download Vue video

The first test came quick. We had to completely redo a whole section of the app and we decided to start implementing Vue within Geoblink. But stop with the mumbo jumbo you’d say. How do you use two frameworks at the same time without interfering with one another? Really, it couldn’t be more simple, and it’s all thanks to an already included Angular directive.

<div id=”main-vue-app” ng-non-bindable>
<first-vue-component />
<some-other-vue-component />

That’s it? I told you it was simple. When attaching this directive to any HTML element, AngularJS stops watching whatever may be inside it. Basically it tells the framework to not consider anything inside as angular code. What happens inside a non-bindable element, stays within it.

Having this, you can start developing your new VueJS app as you’d normally do. Declare your main app, attach your components, your stores if you’re using Vuex (and you certainly should do it) and that’s it, you have a full working VueJS app within an AngularJS application.

// Require vue components files
import  firstVueComponent from ‘path-to-component’
import someOtherComponent from ‘path-to-other-component’

new Vue({ 
    el: '#main-vue-app',
    store: mainStore,
    components: {

As simple as it may seem, this is really all you need. Of course, this can become way more complicated, but if you are, as we were, thinking of doing a migration for your own app, I can’t recommend enough to consider this framework. So far it’s been great, and we’ve just started! We can’t wait to keep implementing new functionalities with this amazing framework.

Happy coding!

What came and what’s to come at Geoblink Tech

Happy new year! In these first days of 2018 here at Geoblink we have done a quick look back on what were the technologies that got us more excited during 2017. This includes technologies that some of us had to learn to work with our existing systems, the ones that we played around with just for fun and others that were new to us and were cool enough to end up in our production systems.

Not only that but we also compared that list against the technologies that each of us is looking forward to learn or work with in 2018. We hope you find the list interesting, and if you want to comment on it let us know in Twitter (@geoblinkTech).

Read more

2 days of fun and data BigDataSpain 2017

On Thursday and Friday last week a few geoblinkers from the Tech team were fortunate enough to attend Big Data Spain in Madrid, “one of the three largest conferences in Europe about Big Data”.

The line-up of speakers this year was amazing and they certainly didn’t disappoint. Moreover, our VP of Technology Miguel Ángel Fajardo and our Lead Data Scientist Daniel Domínguez had the chance to actively participate as speakers with a thought-provoking talk titled “Relational is the new Big Data”, where we tried to remark how relational databases can today solve many use cases regardless of the size of your dataset, adding lots of benefits with respect to other No-SQL options.

Relational is the new Big Data

Read more

Happy GIS Day!

From Geoblink we want to celebrate the GIS Day by sharing with you our last improvement in the catchment areas computation.

As Carlos explained in this previous post, at Geoblink we take advantage of the benefits of the graph theory for computing the catchment area of a location. Thus, we define our graph as a set of intersections (nodes) connected by street/road segments (links), and we add to both, nodes and links, some properties that define them.

The new property added to our links is the traffic peak, which allows us to compute catchment areas considering rush hours. Therefore, we first define a location of interest. Secondly, we apply our set of algorithms to our graph for computing the catchment area of the location of interest, specifying if the rush hours must be considered or not. As a result, we obtain a set of intersections and streets/roads segments that make up the catchment area of the location of interest with or without considering traffic peaks.

But, how does it work? Let’s compute the Geoblink’s catchment area traveling 5 minutes by car, not considering the rush hours and considering them.



As you can see, the resulting catchment area taking in consideration peak traffic is smaller than the other one. The addition of the traffic peak property to our street/road segments allows us to provide to our clients a more accurate catchment area when rush hours must be considered.

Learning from nothing or almost

Last article

In my first article for this blog,  I talked about how my teachers and a team of students I joined used the latest Deep Learning (DL) technologies to help fight cancer.
The goal was to segment and colorize areas in a scanner image corresponding to biological tissues, which could be used to estimate the health of the patient and, in turn, to a better formulation of his treatment.


Not colored scan

Colorization of a scanner image

Colorization of a scanner image

Colorization of a scanner image










At that time, in order to focus on how technology can improve medicine,
I had to skip a crucial component of this IODA project, namely pre-training of the auto-encoders. By presenting it here, I’ll try to illustrate a bit some problematics of deep learning.

So, first, let’s do a quick reminder on deep learning.

Read more

LATERAL, a hidden gem in PostgreSQL

LATERAL is a very useful tool that every SQL user should have in his toolbelt. However, it is normally not explained in introductory courses and many get to miss it.

Suppose that we want to find the perfect match between two tables. For example, we could have a table with all students, a table with all schools, and we would like to find the school that is closest to each student. Another example, we have a table of users with some preferences and another table with products, and we want to find the product that is most similar to what they want. Then LATERAL is a lot of times the right tool for you.

Let’s try out to solve the problem with mock data.

Read more

JS meets SQL. Say hi to AlaSQL!

At Geoblink, we often find ourselves moving a lot of data from our database to the frontend, to display in useful charts and graphs for our users. Although restructuring data from the backend is usually necessary, it is not especially challenging, as the queries to the database are crafted to return the data how we need it for each purpose. For these cases, Lodash is more than enough to filter and fit the data to needs of the front-end.  But, what happens when we do not query the data ourselves? Sometimes, when using third-party APIs, the data may not be structured how we want it. We need a way to organize this data quickly and easily.

Cue in AlaSQL. AlaSQL gives us the power of SQL queries in Javascript, in a fast, in-memory SQL database. With this library, we can store records in a relational table format, and query the data using SQL syntax. This is extremely useful for counting or grouping a large amount of records in a flash, without having to overthink how to manipulate the JSONs to achieve the required structure.

Read more