domingo, 15 de enero de 2012

Confusing python path2

Lets clear things up:

I want to add a path to PYTHONPATH so Python doesn't complain about not finding a module(a library)/cannot import a module. 
From my terminal emulator(console, terminal)
$user: export PYTHONPATH=$PYTHONPATH:/path/to/my/module
From inside a python module
import sys
sys.path.append('path/to/my/module')

I want python to always find this or that module
$user: gedit ~/.bashrc
export PYTHONPATH=$PYTHONPATH:/path/to/my/module
Or
From the first file.py you run
import sys
sys.path.append('path/to/my/module')

This is different that then system PATH
This other path is used to find binaries/executables in your console/terminal emulator. You modify this other path using:
export PATH=$PATH:/path/to/a/binary
So you can run your shiny new binary/executable like this
$user: binary


And if you want to modify this path from inside python you do:
import os.environ['PATH'] += ':/new/path'
This only affects the current session and its practically useless unless you are doing some weird bash inside python stuff. Remember that you use : to separate paths.

jueves, 12 de enero de 2012

Automatically modifing data from models in django

If you want Django to automatically  add new data, update existing data or delete from a model you got various choices with various pros and cons.
This post will attempt to give you the necesary information to decide whats the best strategy, you can see how they are implemented in each of the provided links.
You basically have 3 options:



Signals 
The good
Signals is the most flexible way to work with your models, you can do pretty much anything at anytime with signals.
The bad
Because they get sent all the time and with many arguments, you might have to do many checks to know if you need them in that particular time and that migh easily lead to unnecessary code, and if you forget some check, your database will suffer.
Conclusion
Use them as your last resort,when the other options do not cut it, go for signals.

Overriding the save and/or the delete method in model classes
The good
This will run EVERY time a model is deleted or saved, you will never miss a chance to change your model data.
The bad
It can lead to hard to track bugs, if the operations you are doing inside the method assume too many things. This can be dangerous, and you might not now the time you are writing them how are you going to use your models.
Conclusion
Go safe with this one, only use things you are sure will always be available at the point of the save method. And try not to change other models data.

Overriding the save_model/delete_model/save_formset methods inside your model_admin class
The good
These methods are only called when you do things in your admin, so this are pretty safe to use, and allow you provide additional features and automation to your admin interface.
The bad
Limited use, won't do anything outside the admin.

martes, 10 de enero de 2012

Pushing to a working webfaction repo from your dev machine

I was able to succesfully push to a git repository in webfaction using this general strategy. Save your self(and my future self) some googling and follow this links.
Set up the ssh connection
Follow the webfaction guide to set up a git repo
Follow Abhijit Menon-Sen guide to setup the push

lunes, 9 de enero de 2012

On yakuake in gnome

Note: I know this blog is called Notes on Using Python, but i'll also do random posts on using linux.

Yakuake its hands down the best drop down terminal emulator on Linux, but it can be tricky to get it to play nice with gnome.

THE PROBLEM
The behavior should be this:
  1. I hit my yakuake hotkeys(defined in the yakuake shortcut settings) and yakuake toggles between hidden or shown.
  2. I hit my show desktop hotkey and it toggles all the windows off and on.
Right now this happens
  1. I hit my yakuake hotkeys(defined in the yakuake shortcut settings) and yakuake does nothing.
  2. If yakuake is being show if i hit my showdesktop hotkey, yakuake ignores it and remains.
THE SOLUTION
My solution involves
Dont set a hotkey in the yakuake shortcut settings(delete any shortcuts)
Set a hotkey using the keyboard shortcuts gnome system application: adding a new shortcut that runs the command yakuake, to my desired hotkey.
To fix the show desktop im using wmctrl, which you can get using a simple:
sudo apt-get install wmctrl
Then create the file showdesktop
sudo gedit /usr/local/bin/showdesktop
Paste this content into the file and save it
#!/bin/sh
if wmctrl -m | grep "mode: ON"; then
    wmctrl -k off
    if ! wmctrl -l | grep Yakuake; then
        yakuake
    fi
else
    wmctrl -k on
    if wmctrl -l | grep Yakuake; then
        yakuake
    fi
fi
Give it permission to run
sudo chmod +x /usr/local/bin/showdesktop
And then go again to the keyboard shortcuts gnome system application and add a new shortcut that simply runs showdesktop.
Boom, now all works as expected.

domingo, 8 de enero de 2012

Different ways to get urls in a django view

During production i've had the need to various urls, and i've found a few ways to do this, i leave this here so hopefully somebody can use it, and as a self reminder.
1. Using the Sites app to get the current domain url
def current_domain_url():
    """Returns fully qualified URL (no trailing slash) for the
    current site."""
    from django.contrib.sites.models import Site
    current_site = Site.objects.get_current()
    protocol = getattr(settings, 'MY_SITE_PROTOCOL', 'http')
    port     = getattr(settings, 'MY_SITE_PORT', '')
    url = '%s://%s' % (protocol, current_site.domain)
    if port:
        url += ':%s' % port
    return url

Good side:
It does'nt need the request to work, only the Sites app with your list of sites.
Bad side:
The problem with this approach is that if it depends on the sites app, this is good enough if you are diciplined enough to keep that app updated with your development enviroment, your stating server and your production server, it can be annoying.
Via Fragments of code 
2. Using the HTTP_REFERER to get the current url

def current_site_url(request):
    """Returns fully qualified URL (no trailing slash) for the 
    current site."""
    return '/'.join(request.meta['HTTP_REFERER'].split('/')[:3])

Good side:
I'm not sure where this function could be used, maybe as a helper to prevent sites from outside yours to load some urls. Because of the:
Bad side:

It only works if the current view was called from another url. If the user types directly the url of the current view, it won't work because there is not http referer. Use it only if you are sure your view will always be called from a hyperlink.
Plus the client can modify the http header to send a different referer so it cannot be relied.


3. Using the request HTTP_HOST get the current url

def current_site_url(request):
    full_path = ('http', ('', 's')[request.is_secure()],
                       '://', request.META['HTTP_HOST'], request.path)
    return ''.join(full_path)

Good side:
It's the simplest form to get your current url. All it takes is a request.
Bad side:

Same problem as the HTTP_REFERER the client can modify the http header so it can't be relied upon.
Credit goes to limodou, the author of this django snippet


4. Using the built in build_absolute_uri to get the current url

from django.core.urlresolvers import reverse
def current_site_url(request,*args,**kwargs):
    """Returns fully qualified URL (no trailing slash) for the
    current site."""
    relative_url = reverse(*args,**kwargs)
    return request.build_absolute_uri(relative_url) 

Good side:
It's pretty solid, it only takes the current view, or an url name, basically everything reverse() accepts this functions does.

Bad side:
This function needs a relative url you want to get the full url, so its uses is limited. Also, the build_absolute_uri was introduce in Django 1.2+ so that could be a problem for older apps. And i'm not really sure about its short comings i haven't .