Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Sunday, December 6, 2009

Eclipse Pydev for Django with autoreload

In an attempt to use Eclipse for Django, I was looking around to find how I can maximize productivity. IDE provides a few good things like auto completion and debug but if you were to work around it even with an IDE, then its probably not worth it.

Found "How to debug django webapp with autoreload" . That was a smart hack to hook into the autoreload mechanism to set up pydevd.settrace. Its a real pain without that to put in a

    import pydevd
    pydevd.settrace()

in all places that you want to debug. With an IDE, you should be able to setup a breakpoint, hit the code , let it stop where you set the breakpoint and move on.

The post above indicated how things probably worked for Django pre 1.0 and dint work for me with the 1.1 codebase, Here is the modified code for manage.py that worked with Django 1.1

command = None
if len(sys.argv) != 1:
    command = sys.argv[1]
    
if settings.DEBUG and (command == 'runserver' or command == 'testserver'):
    try:
        import pydevd
        inEclipse = True
    except ImportError:
        inEclipse = False

    if inEclipse:
        from django.utils import autoreload
        m = autoreload.main
        def main(main_func):
            import os
            if os.environ.get("RUN_MAIN") == 'true':
                def pydevdDecorator(func):
                    def wrap(*args, **kws):
                        pydevd.settrace(suspend = False)
                        return func()
                    return wrap
                main_func = pydevdDecorator(main_func)
            
            return m(main_func)
    
        autoreload.main = main


Placing the above code in manage.py after importing the "settings" module seems to allow debugging with autoreload option on.

I also added some logic to check if Im running in Eclipse or not. I dont use Eclipse when Im not using my laptop -- vim is my friend. Its not a robust check, but works to check if we are in Eclipse or not. The idea is to not go into the auto-debug block if you are not running in Eclipse (for e.g. when you are running with vim and a command line).

Sunday, November 8, 2009

Using WNCK for capturing Gnome window events

For those new to WNCK (that includes me as well), it stands for Window Navigation Construction Kit and is used for capturing all window based events in GNOME. You could use python's pygtk to do some window management logic. For e.g. Find below some snippets about capturing when a window got switched. The below snippet will print the name of the application whenever any of the GNOME Windows switches (from Alt-Tab or clicking on window on the taskbar)
   import wnck
   import gtk
   scr = wnck.screen_get_default()
   while gtk.events_pending():    # This is required to capture all existing events
       gtk.main_iteration()
   
   def window_switch_handler(screen,window):
      # Get Current window, then the application and the name from it
      cur_win = screen.get_active_window().get_application().get_name()
      print "Currently showing %s" %cur_win

   scr.connect("active-window-changed", window_switch_handler)
   gtk.main()
After the last line "gtk.main()", the python interpreter will hang waiting for events to be serviced. Now if you switch any of the windows, you would see the name of the application displayed on the console. Im working on a similar setup for KDE (using PyQT). I will post a similar setup after I try it at work tomorrow (I dont have a KDE Setup at home). As for Windows, it turns out to be much more difficult. The PyAA seems to have stuff for WM_ACTIVATE and WM_DEACTIVATE but its compiled against Python 2.4 and noone has a later version available (unless its built). Im going to try 2 things. * Compile PyAA with Python 2.5 or Python 2.6 * Use AutoIT for automating windows tasks. Its non-python and could be an issue when I compile all three interfaces together, but atleast it would provide some way to do it. I dont know of any such automation for Mac OSX, but thats partly due to my lack of knowledge on that OS.

Sunday, October 11, 2009

HMAC SHA Signatures using Python for Amazon webservices

Ive recently been working on the Amazon Product Advertising APIs to get some information from Amazon and display it to my users in a different format.

Since Django is such a wonderful framework, I decided to do this using app using Django. The Amazon Product Advertising documentation has examples for Java, C# and PHP, but not much help for Python. There isnt anything unique to Python as the calls are all either REST based or SOAP based, but there was one part that was tricky -- The HMAC SHA Signatures required for REST requests.

For starters, HMAC is abbreviation for keyed-Hash Message Authentication Code. For more information about HMAC, look up the RFC or the wikipedia entry. There is enough information in the documentation about how to make a REST request but none whatsoever about creating the HMAC based signature.

So, after some debugging and browsing through the forums, here is a snippet that will show how to create a HMAC-SHA based signature that you can use with AWS.

In the below code, its assumed that you followed this doc upto Step 7 since there is nothing thats specific to any programming language.

import hmac
import haslib
import base64
import urllib
.....
AWS_SECRET_KEY=
.....
request = """
Build request as shown in the above link till Step 7
"""
h = hmac.new(AWS_SECRET_KEY, request, hashlib.sha256)
signature = base64.b64encode(h.digest())
request = "%s&Signature=%s" %(request,urllib.quote(sig))
...
rest_output = urllib.urlopen('https://ecs.amazonaws.com/onca/xml?%s' %(request)).read()
...



The line for urllib.quote is required because Amazon wants us to quote the output that is gotten from HMAC based signature (Step 9 in the above document).

Hope it helps in doing a Python based HMAC-SHA signature generation for AWS.