How to Use Python Shutil Make_Archive to Zip Up a Directory Recursively including The Root Folder
The documentation for Python's shutil.make_archive is very confusing. Considering that the arguments to this function only need to be source and destination, makes it even more frustrating to try and reason about. Here are the relevant docs from the p...
Written by Sean Behan on 05/16/2018
How to Just Get SQL Statement Error with SQLAlchemy Python Database Wrapper
If you're working with SQLAlchemy, the best database driver for Python, and want to see only SQL syntax errors, you need to use the StatementError exception class. On it, is an attribute `orig`, that contains just the SQL syntax error... and not any data...
Written by Sean Behan on 05/10/2018
Manual ManyToMany Through with Django's ORM
Here is a code snippet that demonstrates how to set up a __ManyToMany through__ relationship in Django. In Rails, the equivalent would be called a __has_many through__ association. If you set the __through__ argument on the ManyToManyField, Django wil...
Written by Sean Behan on 07/21/2017
How to Fix Raw query must include the primary key with Django ORM
When running raw SQL queries in Django you must include a primary key otherwise an invalid query exception is raised. Normally this is fine but when running more complex queries a primary key may not be available or even make sense. There is a simple ...
Written by Sean Behan on 07/15/2017
How to send email with Python, smtplib and Postmark
Here is a quick code snippet showing how to send email via SMTP with Postmark without any dependencies. It assumes you are using Heroku and have added the addon. But if not just make sure your api keys are set as environment vars. from os import envir...
Written by Sean Behan on 03/12/2017
Using Selenium to Drive Firefox Browser for Web Automation
There are a lot of practical uses for automating user behavior in a browser. Everything from testing your web application to logging into Twitter and auto following people. But first you have to install the tools. Here is everything you need to run yo...
Written by Sean Behan on 03/09/2017
Reshape an Array of Form Inputs for Flask with getlist()
This is how to reshape an array using Python without Numpy. This is a fairly simple task but it can be a little confusing to wrap your head around. I ran into this problem while working with Flask, working with array from form fields. I wanted to us...
Written by Sean Behan on 03/07/2017
Trigrams, Bigrams and Ngrams in Python for Text Analysis
Creating trigrams in Python is very simple trigrams = lambda a: zip(a, a[1:], a[2:]) trigrams(('a', 'b', 'c', 'd', 'e', 'f')) # => [('a', 'b', 'c'), ('b', 'c', 'd'), ('c', 'd', 'e'), ('d', 'e', 'f')] You can generalize this a little bit more ...
Written by Sean Behan on 03/06/2017
How to Decorate Imported Libs in Python for Jinja Template Filters in Flask
To decorate an imported function in Python you would do something like this # in ./lib.py def function_name(): # function body And then in your program you could decorate it like this from lib import function_name function_name = decorat...
Written by Sean Behan on 03/04/2017
Get Method Name as String in Python
Here is how to get the string representation of a method in Python def my_method_name(): print "Hello World" my_method_name.__name__ # => 'my_method_name' Short and sweet!
Written by Sean Behan on 03/04/2017
Destructuring Dictionaries in Python
Here is a quick and dirty way to destructure dictionaries in [Python] d = {'a':'Apple', 'b':'Banana','c':'Carrot'} a,b,c = [d[k] for k in ('a', 'b','c')] a == 'Apple' b == 'Banana' c == 'Carrot'
Written by Sean Behan on 03/04/2017
How to Fix Pypi Upload failed (403): Invalid or non-existent authentication information.
If you run into authentication failure when trying to upload packages Submitting dist/ to https://upload.pypi.org/legacy/ Upload failed (403): Invalid or non-existent authentication information. error: Upload failed (403): Invalid or non-existent...
Written by Sean Behan on 03/02/2017
How to Create a Slug in Python with the Re Module
There are a few 3rd party modules that do this sort of thing. But there is a pretty solution using out of the box Python functionality. You don't have to install any dependencies if you use the `re` module. import re text = ' asdfladf ljklasfj 2324...
Written by Sean Behan on 03/02/2017
My First Python Package on PyPi - Command Line Blog
I wrote my first Python package over the weekend. It is a simple package that adds a basic blog API to an existing Flask application. It's called `command_line_blog` and is available [on Github](https://github.com/seanbehan/command_line_blog) and [on ...
Written by Sean Behan on 03/02/2017
How To Get A Dict from Flask Request Form
The `request.form` object is an immutable dictionary. An `ImmutableMultiDict` object to be exact. Immutable means that you cannot change its values. It's frozen. However, you might want to change the values. Say for instance, creating a slug from a ti...
Written by Sean Behan on 03/02/2017
Python String Format Precision of Float
You can use string interpolation in combination with a dictionary for simple formatting. print "My name is %(name)s and I have $%(change)0.2f in change in my pocket!" % { 'name': 'Sean', 'change': 00.23 } # My name is Sean and I have $0.23 in chang...
Written by Sean Behan on 11/20/2013
How To Install Pyscopg2 Python Postgres Driver on Mac OSX with Homebrew, Postgres.app and VirtualEnv
You might have to append the path of the Postgres.app bin directory to your path in order to install the Python driver for Posgres. export PATH=$PATH:/Applications/Postgres.app/Contents/MacOS/bin To find the location of the application try this ...
Written by Sean Behan on 11/19/2013
How to Create A Unix Timestamp or the Epoch in Python
It's a little convoluted. Seeing as it's a pretty common thing you use when programming computers one might think that there would be a quick and easy method for it. But from what I can tell there isn't. So here is a snippet that will give you a *nix Epoc...
Written by Sean Behan on 11/02/2013
How to Fix Line Wrap Bug in iPython Terminal on OS X Mavericks
There is annoying line wrap issue present after installing iPython on OS X Mavericks for the first time. The issue has to do with readline being missing. To fix the problem uninstall iPython, install readline and then install iPython. pip uninstall ip...
Written by Sean Behan on 10/26/2013
Pretty Formatted JSON from the Command Line
Sometimes you want to see JSON from the command line. I'm sure there are better tools for the job, but here is a little snippet you can throw in your ~/.bash_profile. function json { curl -s "$1" | python -mjson.tool; } Usage json https://g...
Written by Sean Behan on 08/21/2013
Installing MatPlotLib on OS X for Python Version 2.6.1 with PIP and VirtualEnv
If you thought you had installed matplotlib only to find this File "/Library/Python/2.6/site-packages/matplotlib-0.91.1-py2.6-macosx-10.6-universal.egg/matplotlib/numerix/__init__.py", line 166, in __import__('ma', g, l) File "/Library/Python/2.6/...
Written by Sean Behan on 06/17/2012
Mod_Python and Web.py on Ubuntu
Download First install mod_python for Apache and then restart/reload the server. apt-get install libapache2-mod-python /etc/init.d/apache2 force-reload apache2ctl restart Next grab the web.py framework from webpy.org. You can grab the tar or use easy_in...
Written by Sean Behan on 06/17/2012
SHA1 or MD5 Hashing in Python
import hashlib print hashlib.sha1("My wonderful string").hexdigest() print hashlib.md5("My other wonderful string").hexdigest()
Written by Sean Behan on 06/17/2012
Dynamic Attributes in Python Model Class
class Bar(): def __init__(self, **args): for key in args: self.__dict__[key] = args[key] b = Bar(fullname="Monty Python", email="me@monthpython.org") b.fullname #=> Monty Python b.email #=>me@montypython.org
Written by Sean Behan on 06/17/2012
Python Zlib Compress DeCompress
import zlib regular_string = 'this is my string' compressed_string = zlib.compress(regular_string) decompressed_string = zlib.decompress(compressed_string) print compressed_string print decompressed_string
Written by Sean Behan on 06/17/2012
Install MySQLdb for Python on Mac OS X
I don't do much python development. I really like the language and there are a lot of great software projects out there for it. Tornado, for example, is a fast non-blocking web server in python, just open sourced by Facebook that is the engine behind Frie...
Written by Sean Behan on 06/17/2012