Why I do love python so much: How it all started

This is something I always wanted to write about. It is on why I picked python as my programming language and why I felt in love with it instantaneously. I’ll break down the post in some parts to avoid making a very extensive one. This first part is on how I began with python.

It all started six years ago at the university, on a subject called syntax and semantics of the programming languages. During one of the classes the professor just made a vague mention about a language that uses indentation to delimit blocks of code. It was called python he said. That was all I needed to start my research and the most amazing journey of my life.

Several days later I started reading tutorials and watching youtube videos about the basics of python. It took me a while to get all the concepts of the language. At that time I didn’t really know much about functional and object oriented programming, I was just starting at the university with procedural programming in languages like Pascal and C.

Once I finally understood the basic data types and the main features of the language they simply blew my mind. They were semantically amazing and the syntax was so clear. Maybe the professor at the university mentioned this language for a reason, I wish he would have gone more deeply in order to enlighten more students. But for me that was just enough.

The years passed and I gained a lot more experience in python and, of course, in coding techniques, paradigms, methodologies, patterns, etc. Nothing drifted me away from my initial path so much to make me change my programming language, on contrary, the more I learn about programming, the more I get attached to python. And I do it in a way that makes me feel I will be using it until I reach the end of my days. I’m truly in love.

In the next post I’ll get more in deep on the technical aspects that I like the most about python. So keep reading 🙂

Filenergy – A simple file sharing tool written in python using flask

Recently I started looking at Flask as a fully-featured framework ready to compete with Django. And I don’t mean it just for simple application that don’t need to access a database. With the amazing Flask-migrate package and thanks to SqlAlchemy and Alembic we are now able to apply migrations on production databases just like we used to do with Django’s South.

The results of my first complete app using Flask and the stack I mentioned above: A simple file sharing tool.

I’ll attach some screenshots here but I think the app just talks for itself. It’s really simple to use it and It can be very useful to share files with other people or just with yourself, as storage service.

You can find a live demo at http://filenergy.crawley-cloud.com/ (In case you want some customization I’d love to work for you making the product suitable to your needs!)

Of course it’s open source and the code is available at https://github.com/jmg/filenergy.

Image

ImageImageImage

Hope you enjoy it!

Django Deployment

I was working on a tool to make django apps really easy to deploy. Just write a config file and run a command specifying the directory of the app. I think it will deserve another post when it’s finished. In the meantime you can take a look at the code on https://github.com/jmg/django_deployment. It’s based on the amazing ssh tool for python, fabric.

Any feedback or contribution would be appreciated!

My last one weekend project of 2012

In the last weekend of 2012 I wanted to build a project before the year ends. So last Friday 28/12 I started coding this new idea, a github repos aggregator for open source projects. Think in it as a hackernews-like site but for projects hosted on github.

It was challenging to build an application in so short time, but recently I’ve participated on many hackathons where the development sprint is about 10/48 hs of non-stop coding. So I’m kind of used to do this stuff now, and I like it!

The good thing about one weekend projects is that you can keep the focus on one thing. Just one thing. As Unix philosophy says, do just one thing but do it really well, I think hackathon’s projects follow the same pattern. In a very short time you have to focus on solving one problem, but in a pretty new and amazing way.

My new idea, hackersprojects aims to solve the fragmentation in the open source community by providing developers a way to share, discover, vote, comment and contribute open source projects. The site is pretty similar to hackers news and the algorithm used to rank trending projects was taken from this analysis on the hacker news ranking algorithm.

The project is completely open source so you can take a look at the repo on https://github.com/jmg/hackersprojects and, why not, send a pull request to contribute with something you may find useful. It will be appreciated. The idea is to make this project grow with the community.

Nothing less to say, just enjoy it! Right now it’s up and running since 9PM 31/12 UTC time. So I guess I accomplished my goal, which was to have a first working implementation before the year ends.

Here is the link: http://www.hackersprojects.com/

Regards and happy new year of coding!

Embedded Chat

Hey guys,

I want to announce the release of a new social embedded chat service. I was working with my colleague on this over the last few months and now we are very happy to make it public as a closed beta service.

You can check it out on our the live site at http://www.embedded-chat.com and give us a try ;-). As we are in private beta this is totally for FREE and you’ll get much benefits when we release the final version if you sign up now.

For the tech people that read this I’ll make another post going deeply on the technologies we are using on this new service. One hint: Python and Node.js can make it really well together ;-). Also you can write all your code in a “pythonic” way if you use coffescript instead of javascript on the node server side. Don’t miss my next post about the geeky side of this project.

Facebook JS SDK for login and python backend api calls with Pyfb.

Sometimes you don’t want to have a redirect from your site to facebook to just perform the login. The solution to this problem is simple. Fortunately facebook provides a login via a popup through the js sdk. The only big problem with this is that you must do api call with javascript right on the client side. This is not the best choice at all. If you don’t take care your application might become very vulnerable.

That’s the reason I’ll you you how to use the js sdk just for login and api calls through python backend code using the library I wrote, Pyfb.

First at all you need to write the index.html where the code to achive the login will be located. It would look like this:

<html>
    <head><title>Facebook Login with JS SDK</title>
    </head>
    <body>
    <div id="fb-root"></div>
    <script>

        function isConnected(response) {
            return response.status == 'connected';
        }

        function getLoginStatus(FB) {

            FB.getLoginStatus(function(response) {

                if (isConnected(response)) {
                    onLogin(response);
                }
                else {
                    FB.login(onLogin);
                }
            });
        }

        function onLogin(response) {

            if (isConnected(response)) {
                location.href = '/facebook_javascript_login_sucess?access_token=' + response.authResponse.accessToken;
            }
        }

        window.fbAsyncInit = function() {

            FB.init({
                appId      : '{{FACEBOOK_APP_ID}}',
                channelUrl : 'http://localhost:8000/media/channel.html',
                status     : true,
                cookie     : true,
                xfbml      : true,
                oauth      : true,
            });

        };

        (function(d){
             var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
             js = d.createElement('script'); js.id = id; js.async = true;
             js.src = "http://connect.facebook.net/en_US/all.js";
             d.getElementsByTagName('head')[0].appendChild(js);
        }(document));

    </script>

        <button onclick="getLoginStatus(FB)">Facebook Javascript Login</button>
    </body>
</html>

As you can see, in the login callback function (onLogin) you are receiving the access token. This token will allow you to make backend calls, so don’t lose it! I’d recommend to save it in session or store it on the database every time a user do the login.

I will be using django for this example but you could use whatever you want for backend. The views.py django file would looks like this:

from pyfb import Pyfb
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response

from settings import FACEBOOK_APP_ID, FACEBOOK_SECRET_KEY

def index(request):
    return render_to_response("index.html", {"FACEBOOK_APP_ID": FACEBOOK_APP_ID})

#Login with the js sdk and backend queries with pyfb
def facebook_javascript_login_sucess(request):

    access_token = request.GET.get("access_token")

    facebook = Pyfb(FACEBOOK_APP_ID)
    facebook.set_access_token(access_token)

    return _render_user(facebook)

def _render_user(facebook):

    me = facebook.get_myself()

    welcome = "Welcome <b>%s</b>. Your Facebook login has been completed successfully!"
    return HttpResponse(welcome % me.name)

Finally just configure the urls.py:

urlpatterns = patterns('',
    (r'^$', 'djangoapp.django_pyfb.views.index'),
    (r'^facebook_javascript_login_sucess/$', 'djangoapp.django_pyfb.views.facebook_javascript_login_sucess'),
)

And don’t forget to have the properly configuration constants on your settings.py:

# Facebook related Settings
FACEBOOK_APP_ID = 'YOUR_APP_ID'
FACEBOOK_SECRET_KEY = 'YOUR_APP_SECRET_CODE'

That’s it! enjoy the facebook graph API!

Proxy Dispatcher implemented in PHP

I want to share a piece of code which might be very usefull when you have to deal with objects introspection in PHP. I played for years with the python’s introspection system and I loved it.

But now I’m back on PHP. A language that have very good metaprogramming tools but which is less pragmatic than python or ruby in this aspects (and maybe in almost all aspects) under my point of view.

In this piece of code I’m trying to replace the *args of python with the php function call_user_func_array. The functionally behind this differents implementations is very similar in the end. But I ever think python’s approach is far better =).

Let the code talk:

/**
* Proxy Dispatcher using php call_user_func_array (http://us2.php.net/manual/en/function.call-user-func-array.php)
* */

class Foo {

    function bar1($arg, $arg2, $arg3, $arg4) {
         return "arg: $arg, arg2: $arg2, arg3: $arg3, arg4: $arg4\n";
    }
    function bar2($arg, $arg2) {
        return "arg: $arg, arg2: $arg2\n";
    }
    function bar3($arg) {
        return "arg: $arg\n";
    }
}

class FooWrapper {

    public function __construct() {
        $this->_foo = new Foo();
    }

    public function __call($method, $arguments) {
        return call_user_func_array(array($this->_foo, $method), $arguments);
    }
}

$fooWrapper = new FooWrapper();
echo $fooWrapper->bar1(1,2,3,4);
echo $fooWrapper->bar2(1,2);
echo $fooWrapper->bar3(1);

And here is the python’s code for the same:

class Foo(object):

    def bar1(self, arg, arg2, arg3, arg4):
        print "arg: %s, arg2: %s, arg3: %s, arg4: %s" % (arg, arg2, arg3, arg4)

    def bar2(self, arg, arg2):
        print "arg: %s, arg2: %s" % (arg, arg2)

    def bar3(self, arg):
        print "arg: %s" % arg


class FooWrapper(object):

    foo = Foo()

    def __getattr__(self, name):
        return lambda *args, **kwargs: getattr(self.foo, name)(*args, **kwargs)


fooWrapper = FooWrapper()
fooWrapper.bar1(1,2,3,4)
fooWrapper.bar2(1,2)
fooWrapper.bar3(1)