Using Github’s page creation tool, Stumpy now has a new front-end for downloading the latest packages and all the information you need to get things running.
You can check it out here: http://mutaku.github.com/Stumpy/
Using Github’s page creation tool, Stumpy now has a new front-end for downloading the latest packages and all the information you need to get things running.
You can check it out here: http://mutaku.github.com/Stumpy/
Started work on a wrapper for the Google Geocoding API, called pygeocoding. Check out the Github page for the code and usage.
The intent is to provide a Pythonistic interface in building your Google Maps such as building a Google Map in Django with locations stored in your models. As noted on the API page:
Note: the Geocoding API may only be used in conjunction with a Google map; geocoding results without displaying them on a map is prohibited. For complete details on allowed usage, consult the Maps API Terms of Service License Restrictions.
Some example usage:
import pygeocoding
# Let's find CERN
pygeocoding.LookUp(address="CERN CH-1211 Genève 23 Switzerland")
{u'status': u'OK', u'results': [{u'geometry': {u'location_type': u'APPROXIMATE', # ... truncated output
# We can also search backwards - let's pipe in the lat/long of the liberty bell (approximately)
# - we'll just see what the first result is
r = pygeocoding.LookUp(latlng="39.9518819802915,-75.1476150197085")
# now we can pipe these results to our mapping functions
Let’s take a quick look at a great tool to post to Facebook from Python called fbconsole. It’s fairly self explanatory, so I won’t bother going into much textual detail here. I’ll take you through some of the basic features and highlight as we go. In the following code snippet, we will post some data to our personal status feed, similar to how we push from KindleQuotes to Facebook when a user would like to share an item.
import fbconsole as F
# If you have an APP ID from Facebook, you can add that here.
# Otherwise, you will be posting as fbconsole.
F.APP_ID = '<YOURID>'
# Set some authentication parameters
# Here we will set the ability to publish to a stream
F.AUTH_SCOPE = ['publish_stream']
# Now we will login and get our OAuth token.
F.authenticate()
# After successful login, we can add our status update.
# Let's assume we have some neat data we want to push to the stream.
# We'll post our world_changing_data to our personal feed
F.post('/me/feed', {'message': world_changing_data})
# Want to logout and wipe your OAuth token?
F.logout()
We just completed a very simple data push to our Facebook status feed from within our python program. There is a lot more functionality to check out once you have the basic setup working in your program.
I’ve written before about how you can use Python to upload images to Imgur. I wanted to write a quick update to inform anyone interested that there is a github repository I have created to house PyImgur.
You can find the most current code here.
As assembled on github …
Stumpy Commit Activity
Stumpy Version 1.5 is now out and ready for testing.
Should be functional, but please submit any issues you might find to the issues page.
Changes include (from commits):
How do we follow the Django DRY principle and avoid as many hard coded elements as possible in our project when we need to include Javascript? A good example of this is if we are pulling in a bookmarklet that will be offered on the site. We need to reference the domain of our project in the bookmarklet, but this then yields code buried in our project’s static files that needs to be altered by anyone that might be utilizing your open sourced code.
This example presents a little bit of a challenge. If this were HTML in our template we could simply reference a DOMAIN variable that we would feed in through a view. However, this is a static Javascript file, so how do we go about utilizing Django template variables in supposedly static Javascript?
Here is a simple method. In our HTML template, we will setup a Javascript global variable that is created to reference a template variable that we feed in from our view, here a domain, and this variable is then referenced in our static Javascript files.
<!-- Our HTML Template (templates/index.html) that is fed data from views.py -->
{% extends "base.html" %}
{% block content %}
<script type="text/javascript" src="/static/somejs.js"></script>
<script>
var DOMAIN = "{{ site_domain }}";
</script>
<!-- rest of our template, business as usual. -->
{% endblock %}
As you can see, we would feed in a site_domain variable from views.py that might be created something like this.
from django.contrib.sites.models import Site
from django.shortcuts import render_to_response
def index(request):
'''Our main index view.'''
site_domain = smart_str(Site.objects.get_current().domain)
# more of our view code...
return render_to_response('templates/index.html', {
'site_domain': site_domain,
#...rest of our template vars
})
Now, how do we use this in our static Javascript? We reference that global Javascript variable we declared in our template using our Django template variable site_domain.
// Our Javascript file ... /static/somejs.js
alert("Your current domain is: "+DOMAIN);
Now our code is much more portable, even in places where things should essentially be static.
We want to accept some HTML, while stripping out the rest, in our Django form. Let’s take a quick look at how we can introduce some basic HTML cleaning functionality to our Django ModelForm. We will be using Bleach to do all the dirty work.
from yourapp.models import YourModel
from django import forms
import bleach
class YourForm(ModelForm):
class Meta:
model = YourModel
def bleachData(self, data, whitelist=[]):
allowed = whitelist
clean_data = bleach.clean(data, allowed)
return clean_data
def clean_somefield(self):
somefield = self.cleaned_data['somefield']
whitelist = ['b', 'i']
somefield = self.beachData(somefield, whitelist)
return somefield
def clean(self):
cleaned_data = super(YourForm, self).clean()
self.cleaned_data['somefield'] = self.clean_somefield()
return self.cleaned_data
As you can see, we run our normal form validation methods and then initiate a post-cleanse cleanse by bleaching ‘somefield’ and allowing a whitelist of tags, bold and italics.
Want to grab some basic audio file information in your Python program?
Let’s use Mutagen to look at the type, length, and size of an audio element.
import mutagen
class Audio:
pass
f = "some_audio.m4a"
element = mutagen.File(f)
if element:
Audio.format_list = element._mimes
Audio.size = element.size
Audio.length = element.length
else:
Audio.error = "Invalid audio file."
Here, we could have imported the M4A handler, but using the File class we don’t have to make audio type assumptions a priori. If the audio format cannot be handled or is invalid, we will simply get a None Type return when sending our file to the File class.
Running XFCE4 and setting the preferred applications generally works. However, I noticed that some applications still would not listen to my demands of using a specific browser when launching links. For example, using python’s webbrowser module, and therefore almost any other module opening external links, would use Firefox or Opera (depending on which was available).
# Checking python invocation of a browser
import webbrowser as w
w.get().open('http://mutaku.com')
Here’s the culprit, check in your /etc/alternatives/ directory and you’ll see what I mean.
ls -l /etc/alternatives/
Notice the entry x-www-browser. This will be a symlink to a browser and this value was different than what I was attempting to set through the XFCE4 GUI configuration. This problem seems somewhat common as I’ve seen it occur in KDE and GNOME as well.
To fix this issue, simply run the following command and you should be presented with a list of browsers from which you can set.
# Update your browser choice and choose from the presented text menu sudo update-alternatives --verbose --config x-www-browser # Now make sure teh proper symlink is setup ls -l /etc/alternatives/x-www-browser
Now you should have a functional default choice. Those GUIs can suck it!