Flask Google Maps (plus: how to write a Flask extension)

Last week I was writing a talk to give at Google Developers Bus and I needed to show how to integrate Flask and Google Maps API, as I did not found any extension to Google Maps I decided to create one.

One of the best things in Flask is the way it is extended by Extensions and Blueprints, by the way, Blueprints is one of the best idea I've seem in Python web frameworks, once you start working with Blueprints you want to use it everywhere (but unfortunatelly not every framework has an ellegant way to be extended)

I will start showing how the extension works and then I will explain how to build it from scratch.

Flask Google Maps

Template filter and a template global to create Google Maps from latitude and longitude


pip install flask-googlemaps

Loading in your app

from flask import Flask
from flask.ext.googlemaps import GoogleMaps
app = Flask(__name__)

Using in templates

{{ googlemap('identifier', **params)}}

{{googlemap("map_name", lat=-0.12, lng=-0.45, markers=[(lat, lng), (lat, lng)]}} 


- identifier: The name tat will be used to identify your map (you can have multiple maps in one page)
- lat:  latitude to center the map
- lng: Longitude to center the map
- markers:  a list of tuples, each tuple is a (lat, lng) marker (a pointer in the map)
- zoom: percentage of the zoom
- maptype: Google map type, TERRAIN or ROADMAP. defaults to ROADMAP
- varname: The JS varname to bind the map, defaults to "map"
- style: css style to be appended to the < div >
- cls: css class to the map < div >

TODO: In near future it will be possible to pass an address as argument


The template

<h1>Flask Google Maps Example</h1>

<h2> Google Dev Bus - Rua Quatá, 255 </h2>
{% with %}

    {% set location=(-23.599097,-46.675903) %}
    {% set style="width:500px;height:500px;"%}

        location.0, location.1,

{% endwith %}

The output



Screenshots and docs on Github.


How to create a Flask Extension

Flask is extendable by two patterns Extension and Blueprint

An Extension is something like a complete plugin, a distribution containing models, views, templates, static files, template globals and filters etc and usually an Extension is built of Blueprints, which is an app prototype, it can define the way an app will be when registered, exposing resources, and url rules, also the Blueprint has the capability to access the current running application to contribute with things like config values, template filters, etc.

In the Flask docs there is a great explanation on Extensions and Blueprints

Anathomy of an extension

An extension is just a Python package following the naming convention Flask_anything, with packages naming like that Flask will automatically find them in the Python PATH via the ext proxy. So instead of from flask_anything import something you can do from flask.ext.anything import something in that way the code will be very clear and explicit and you know you are dealing with a Flask extension.


root folder
|__ flask_anything/
    |__ templates/
    |__ static/
    |__ __init__.py
    |__ __some_module.py
    |__ *
|__ setup.py

That is it! you can write really anything you want and it will be available throught from flask.ext.anything.some_module import FooBar

What is inside?

Usually extensions expose a main Class which will be registered in your app, there is no rule, but there is some conventions, an example:

# flask.ext.anything.some_module.py

from flask import Blueprint

class Anything(object):
    def __init__(self, app=None, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

        if app:

    def init_app(self, app):
        # here you get the app object and can do anything you want
        app.add_template_filter("pass a template filter function here")
        app.add_template_global("pass a template global here")

        app.add_url_rule("/anything/<arg>", view_func=self.something)

        #or even better you can register a Blueprint
        module = self.create_blueprint("module")
        another_module = self.create_another_blueprint("another_module")

        # then you can register many blueprints in the app

    def create_blueprint(self, blueprint_name):
        module =  Blueprint(blueprint_name, __name__, template_folder="a_path_to_relative_folder")
        module.add_url_rule("/something/<argument>", view_func=self.some_view)
        return module

    def some_view(self, argument):
        context = {'argument': argument}
        return self.render(self.get_template_name, context)

    def render(self, *args, **kwargs):
        return render_template(*args, **kwargs)


By the community convention your extension main class should receive its configurations in __init__ method and should have a lazy way to init defined as a method called init_app, also is a good practice to create methods for things like create_blueprint, register_blueprint, get_url_rules and also a render_template method inside your Blueprint is usefull. That is because others could extend your class and overwrite them, in example to use Flask-Themes it is usefull to overwrite the render_template method.

Using your extension/Blueprint

# your_app.py

from flask import Flask
from flask.ext.anything.some_module import Anything

app = Flask(__name__)

# option 1

# option 2
anything = Anything()

With the above instantiation/init_app your app will be manipulated by the extension and the views, urls, template filters etc will be available.

There is more conventions to follow as state, namespace, resource access etc, but you can find all the information on Flask docs.

If you have some idea to improve Flask-GoogleMaps, please comment!

Desenvolvendo protótipos para startups com Python e web2py

No dia 18 eu palestrei na semana global do empreendedorismo, la na Plug'n work. A idéia da palestra foi mostrar para os empreendedores que estão começando a desenvolver suas idéias uma maneira de desenvolver seus protótipos (ou até mesmo um MVP) utilizando Python, web2py, bootstrap e o browser.

Além de apresentar Python e ressaltar sua facilidade, assim como todo o poder do web2py para este nicho de público, eu tive a intenção de focar em uma opinião pessoal que é a minha repulsa pelo termo "Sócio técnico" e como isso soa como enganação e é claro mostrar como qualquer empreendedor que saiba usar um computador e pelo menos tenha noção de estrutura de dados (ja tenha usado uma planilha excel) é capaz de desenvolver seu próprio protótipo utilizando o web2py.

Pretendo melhorar este material e quem sabe transformar em um vídeo e tambem estou disponível para dar a mesma palestra em outros eventos, universidades etc..

Seguem os slides.

Este video é parte da aula 4 do cursodepython.com.br

KISS: Use the built in sum() instead of reduce to aggregate over a list comprehension

This post is the beginning of a KISS tag, a place where I will put all the "over complications" I find on codes that I work on, or even to comment on my own mistakes.


Today I was working on a Django reports app and I saw this code:

result = reduce(lambda x, y: x + y, \
        [i.thing.price for i in \

At the first look, specially because of the use of reduce I thought it was a complicated issue to solve.

2 seconds after I realized.

Why using reduce for sum when Python already has the built in sum function?

result = sum([i.thing.price for i in ModelObject.objects.filter(created_at__gte=date)])

Well Python gives us powerful builtins so just use this!

The other problem here is the memory usage of the above solution, it will first get the objects list from filter() and after that it will iterate one by one, doing a field lookup to take the price and return a new list with values to sum.

It can kill your server!

On this case things can be done in a better way! we are talking about Django! and even I am being a Django ORM hater I know that it has some cool things like this one:

Django ORM aggregations

from django.db.models import Count
queryset = ModelObject.objects.filter(created_at__gte=date)
aggregation = queryset.aggregate(price=Sum('thing__price'))
result = aggregation.get('price', 0)

On the above code, the aggregation Sum will translate in to a SQL command and the sum will be performed on the database side! much better

I really do not like the Django ORM syntax, also I hate the way I bind the objects, maybe because I am used to use the wonderful DAL I prefer to refer to data as data, I mean, data as Rows not data as objects. But in cases I am working with Django, I think the best is to use its powerful tools!

Keep It Simple Stupid!