Lior Gradstein’s Blog

Archive for the ‘python’ Category

In a Django project, I have a template that is used by two urls, which is quite common (generic views, using ‘create_object’ and ‘update_object’). The problem is that I had to add a supplementary menu just when the template is loaded from the ‘update’ generic view, and not from the ‘create’ generic view.

Making the difference between the two urls calls at the template level is a problem because it’s managed by generic views, so the same template is used.

Anyways, there are several possibilities:

In urls.py, use the ‘template_name’ variable, where you can speficy a specific template for this url(). That is instead of using the default <model>_form.html.
What I don’t like in this situation, is that I will have two nearly similar templates, just for an added menu. Not cool. Another problem is that I use a loop to create all my urls. So if I add a special template, I’ll add it to ALL my models :-(.

Another solution, is to find a way to use a variable in the template that would be different wether the template has been loaded by update_object or create_object.

In our urlpatterns in urls.py, we can use the ‘extra_context‘ variable (takes a dictionnary as parameter). It is correctly managed, even when using generic views. So, you’ll have :

url(r‘foo/ajouter/$’, ‘django.views.generic.create_update.create_object’,  
                dict(form_class=modelForm,
                extra_context={‘usage’:‘create’},
                name=‘foo_create’,))

url(r‘foo/%s/(?P<object_id>\d+)/modifier/$’,
                ‘django.views.generic.create_update.update_object’,
                dict(form_class=modelForm,
                extra_context={‘usage’:‘modify’},
                name=‘foo_update’))

We can also use, in urls.py, the ‘context_processors’ variable. For more information about the context processors, have a look at this tutorial. The goal is to add ‘django.core.context_processors.request’, like this:

from django.core.context_processors import request

and in the url(), add context_processors:

url(r‘foo/ajouter/$’, ‘django.views.generic.create_update.create_object’,  
                dict(form_class=modelForm,
                context_processors=[request,]),
                name=‘foo_create’,))

The last possiblity is a more global solution. It’s like the context_processors usage above, but added into every templates automatically.
To do this, you’ll have to edit the list of Template Processors in your settings.py file. That list is run each time a template is loaded, and allows one to add any variable to the template automatically. By default (on Django 1.0.x) this list is commented out, so it has by default the list:

("django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media")

You’ll have to uncomment it, and add ‘django.core.context_processors.request’. By doing this, you get the variable ‘request.path’ available in your template.

Finally, you’ll be able to test your variable with {% ifequal %} and display your conditional elements.

  • 0 Comments
  • Filed under: django, python, software
  • Mediawiki allows one to send Recent Changes (RC) to a UDP port.
    The ip address is defined by the variable wgRC2UDPAddress, and the port by the variable wgRC2UDPPort. It’s a really good idea that it’s a UDP transfer, since there is no need for any ACK, so Mediawiki doesn’t block if there is nothing listening on that port.

    These parameters must be set in the LocalSettings.php file, like this, for example.

    $wgRC2UDPAddress = ‘127.0.0.1′;
    $wgRC2UDPPort = 9390;

    I wrote a really simple python program (more a proof of concept) that receives the data, cleans it, and then prints it to stdout :

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    #
    # vim:syntax=python:sw=4:ts=4:expandtab
    import SocketServer
    import re

    HOST,PORT = , 9390

    class MyUDPHandler(SocketServer.BaseRequestHandler):
       def handle(self):
           print re.sub(r\x03\d{0,2}’, , self.request[0])

    if __name__ == ‘__main__’:
       server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
       server.serve_forever()

    I plan to make it into a complete project that will send the data/notifications using Jabber(XMPP).

  • 0 Comments
  • Filed under: mediawiki, python
  • How to dial a number using Asterisk and Python

    I didn’t find any example in Python on how to Dial a number from an Asterisk server and link it to another channel. So here’s a quick code to do it. You just need to have a manager defined in your /etc/asterisk/manager.conf defined.

    import socket

    HOST="192.168.1.116"
    PORT=5038

    p = """Action: login
    Events: off
    Username: %(username)s
    Secret: %(password)s

    Action: originate
    Channel: SIP/%(local_user)s
    WaitTime: 60
    CallerId: 600
    Exten: %(phone_to_dial)s
    Context: default
    Priority: 1

    Action: Logoff
    """
    def click_to_call(phone_to_dial, username, password, local_user):
        pattern = p % {
                ‘phone_to_dial’: phone_to_dial,
                ‘username’: username,
                ‘password’: password,
                ‘local_user’: local_user}

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((HOST, PORT))

        data = s.recv(1024)
        for l in pattern.split(‘n’):
            print "Sending>", l
            s.send(l+‘rn’)
            if l == "":
                data = s.recv(1024)
                print data
        data = s.recv(1024)
        s.close()

    if __name__ == ‘__main__’:
        click_to_call(phone_to_dial=‘123456789′,
                      username=‘manager_login’, password=‘yourpass’,
                      local_user=‘600′)

  • 1 Comment
  • Filed under: asterisk, python, voip
  • Mark Ramm, one of TurboGears’s core developers announced on TurboGears’s mailing list that they will merge with Pylons! To be more precise, the API of TurboGears will be implemented on top of Pylons. It seems they already made some test/proof of concept that are, as they say “a huge success”. That’s really good news for Python web frameworks development, and a good news for me, as I’ll not have to choose between the two :-

    As a sidenote, it seems another framework, CleverHarold has disappeared without anybody noticing. Its domain is parked, and today its Google Group page went off (the last messages were from people asking if the project was still alive).

    Update: Noah Gift wrote a nice article about the merge.

  • 0 Comments
  • Filed under: framework, python, web
  • As the title says it, each presentation was filmed, and has just been uploaded for everyone’s pleasure! Here is the two-part video presentation of Twisted, done by Michael SCHERER.


    Oh, by the way, please take a minute to vote for your favourite Internet Engine!

    Journee Python Conference 2007I went today to the Journée Python 2007 Conference in France. I managed to see half of the Twisted intro, some lightning talks, and most of the afternoon presentations (thanks to Ido’s mid-day nap).

    Most of the talks were introductory type, but they were finely presented (alas most of the audience already knew python). I hope I’ll find the time to prepare some more advanced Twisted presentation for next year’s Conference (there’s one, right?)

  • 0 Comments
  • Filed under: python
  • Nice introduction article on Pylons

    Pylons is a cool web framework (one more, besides TurboGears, Django, Zope, etc.). Someone posted on the mailing list a reference to a nice introduction.

  • 0 Comments
  • Filed under: framework, python, web
  • I found a nicely written article about the problems with Ruby, written by a Ruby user, and why he found Python to be really good. There’s even a quote about Twisted!

    And, there are a bunch of things available to a Python guy that Ruby just can’t compete with that are of particular interest to me. Two that come to mind immediately are Twisted and Stackless Python. The former was used by others at TurnTide for creating a really powerful SMTP testing tool and the latter was used by TurnTide’s competitor IronPort to build one of the industry’s best MTAs.

    I didn’t knew that IronPort was done in Python, even in Stackless Python!

  • 0 Comments
  • Filed under: python, ruby, twisted
  • New Apache module for integrating WSGI apps

    Finally, after such painful setups, I really never could find a really suitable configuration that could satisfy me. Here are the different methods I tried to implement TurboGears/Pylons or similar WSGI/Python projects (MoinMoin for example):

    • FastCGI: So complex to setup, crashes on its own so often, and leaves running processes in memory so have to kill them each time manually to start again with a clean environment. I have to admit it is easier to configure on Lighttpd.
    • SCGI: As complex as FastCGI and not so used in the world, but not bad. Too few options.
    • Proxy: Redirecting on a local different port gives nore work, and as soon as you have several other virtual hosts, you’ll have to keep a registry of all your allocated ports. Painful, but easy to setup. Maybe be hard to configure if you’re using Zope, and if you need some remote information (ip address of the user for example), you’re dead!
    • Direct Access: Configuring you app to run on a local ip alias on your machine and eventually configure your firewall to DNAT on it. Not that complex to setup, but requires access to you OS confiugration and many apps don’t allow you to only listen on a specific interface (MoinMoin allows it, that’s cool)
    • mod_python: Loads Python into memory. Everybody shares the same namespace. Dangerous.

    Now here’s a new contender, mod_wsgi written by Graham Dumpleton. That’s right, it will not work for every app. Zope, not being WSGI aware, is out of the way, except for Zope 3.x. But most of Python apps can be modded to be WSGI aware (MoinMoin is an example).

  • 0 Comments
  • Filed under: python, web
  • PyPy 1.0 has been announced!

    PyPy version 1.0 is now available. That’s really a great news, and a milestone for the Python community (and the rest of the programming world). It’s not yet recommended to use it in production, but we’re not that far from that.

    Please read the announcement and go in the different links referenced there to learn more about PyPy and what it will change in your life.

    Python is so cool.

  • 0 Comments
  • Filed under: language, python
  • Photos of Ido and Oren

    2009-11-22 14.53.56.jpg2009-11-22 14.53.40.jpg2009-11-22 14.33.25.jpg2009-11-22 14.33.14.jpg2009-11-22 14.30.32.jpg2009-11-22 14.28.49.jpg2009-11-22 14.05.22.jpg2009-11-22 14.05.12.jpg2009-11-22 14.05.07.jpg

    Search engine optimization by SEO Design Solutions