Tag Archives: Python

Use Vagrant to Manage an OEL6 Virtual Machine

Vagrant is a tool that you can use to set up, configure, and access a VM through the command line. This is a life changer. I love it. In this post I’ll walk through setting up an OEL6 virtual machine, installing a non-ancient version of Python, and configuring the port forwarding so that you can use it for backend web development. (The port forwarding is not obvious on RHEL/OEL.)

Continue reading

Using Sessions in Flask

In this post I’ll provide an example of using session management in Flask. This is useful when you need to recover persistent data across different endpoints in your application. In this example, we set the permanent attribute of the session object to True in order to ensure that the session data lasts indefinitely until it is cleared when the user accesses the root endpoint again. The best practice is to have a timeout on the session data.

Continue reading

Using app2py for OS X Distribution

I thought that .pex files were the way to go for distributing Python applications to OS X users, but it was only partially successful. For one, users needed to reinstall Python with Homebrew, which isn’t difficult, it’s just awkward explaining to people that the Python distribution that ships with Mac isn’t the same Python distribution that exists in the wild. Their next question is invariably, “how will this affect the rest of my system?” I can’t answer that. I can’t guarantee that things will be future-proof.

And then I found app2py (or five dollars) which creates a Mac application bundle out of a Python script. It worked like a charm. The best thing is that you don’t have to write a stupid setup.py file, it writes one for you. That’s five minutes of your precious time you can look at cat videos with, or whatever.

You can install this using pip, so that’s cool. Next, you do as the tutorial explains,

py2applet --make-setup MyApplication.py

This will create a setup.py file. Finally, for deployment, you build the distribution with a non-Mac Python installation. (If you haven’t already run brew install python you’ll want to run that.) My brew installation of the Python landed somewhere in /usr/local/Cellar/....

/usr/local/Cellar/python/2.7.8_2/bin/python setup.py py2app

This will create a standalone Python application that you can distribute painlessly to your Mac colleagues.

Simple Reservoir Algorithm in Python

I needed to sample lines from a file, and I found this SO post on on the Reservoir Algorithm. The code below lets you sample a single line from a file in O(n) time. What makes this code special, besides it’s linear time, simplicity and elegance, is the fact that the file you’re sampling from doesn’t need to fit in memory.

import random

def random_line( filename ):
    hdl = open( filename, "r" )
    line = next( hdl )
    for num, aline in enumerate( hdl ):
        if random.randrange(num + 2):
        line = aline
    return line