snippets with tag 'python'

Python : cross platform library loader helperdrax's answer for loading a named or absolute library on any platform :)
import os, sys, ctypes

# Types reminder:
#!/usr/bin/python
# String  : ctypes.c_char_p
# Integer : ctypes.c_int
# Long    : c_ulonglong

def loadbinlib(libname="", libpath=""):
   if not libpath:
       if sys.platform in ['win32','win64']:
          libpath = '%s.dll' % libname
       elif sys.platform in ['mac']:
          libpath = '%s.dylib' % libname
       elif sys.platform in ['linux', 'linux2']:
          libpath = '%s.so' % libname
   return ctypes.CDLL(libpath)
tags : python, system, linux, windows

Python : dynamic user profile accesUseful to filter profiles dynamically and in a generic way. thanx to mattcc@#django for ideas
from django.db.models import get_model
profile_class = get_model(*settings.AUTH_PROFILE_MODULE.split('.'))
jabber_user = profile_class.objects.filter(jabber !='')
tags : python, django

Django : automatic and unique slug fieldOverride your model save method to auto create an unique slug id. Useful for SEO. This method ensure the slug is unique using a regexp.
#!/usr/bin/python
 
from django.db import models, IntegrityError
import re
from django.template.defaultfilters import slugify
   
class MyModel(models.Model):

    title= models.CharField(max_length=50)
    slug = models.SlugField(blank = True, unique=True)

    def save(self):
        # auto fill the slug field
        if not self.slug:
            self.slug = slugify(self.title) 
        while True:
            try:
                super(MyModel, self).save()
            except IntegrityError:
                matches = re.match(r'^(.*)-(\d+)$', self.slug)
                if match_obj:
                    current = int(matches .group(2)) + 1
                    self.slug = matches .group(1) + '-' + str(current)
                else:
                    self.slug += '-2'
            else:
                break
tags : python, django, regexp

Django : DictCursor for raw sql using djangothis has been removed from django trunk because of unused, but maybe useful.
# inspired from old django code
# mimics MySQLdb.cursors.DictCursor behaviour

def dictfetchall(cursor): 
    "Returns all rows from a cursor as a dict" 
    desc = cursor.description 
    return [dict(zip([col[0] for col in desc], row))   for row in cursor.fetchall()]
tags : python, django, MySQL

Django : cookieless Django authentificationThis allows you to auth an user without any cookie, using a single POST parameter. this is especially useful for using with swfupload that cannot send cookies. Ideally, use this inside a decorator.
#!/usr/bin/python

def authFromSessionid(request):
    from django.shortcuts import get_object_or_404
    from django.contrib.sessions.models import Session
    session = get_object_or_404(Session, session_key=request.POST.get('sessionid'))
    session_data = session.get_decoded()
    user = get_object_or_404(User, pk = session_data['_auth_user_id'])
    request.user = user
tags : python, django

Django : Use your django project outside djangoThis is how to use your django models and data outside your web project. For example this can be used to create some cron jobs.
#!/usr/bin/python

from django.core.management import setup_environ
import settings
setup_environ(settings)

# do your stuff
tags : python, system, django

Python : Email regexp validatorRegexp basique pour la validation d'adresses email simples
#!/usr/bin/python

def valid_email(email):
    import re
    reg = re.compile('([\w\.\-]+@[\w\.\-]+)')
    return reg.match(email)
tags : python, regexp

Python : simple XML/XSL transformationEasyly convert any XML file or string to text, html or anything using an XSLT stylesheet. You can pass a parameters dictionnary to the stylesheet if needed :)
#!/usr/bin/python

def xsl_transormation(xslfile, xmlfile = None, xmlstring = None, params={}):
    from lxml import etree
    import StringIO
    xslt_tree = etree.XML(utils.readfile(xslfile))
    transform = etree.XSLT(xslt_tree)
    xml_contents = xmlstring
    if not xml_contents:
        if xmlfile:
            xml_contents = utils.readfile(xmlfile)
        else:
            xml_contents = '<?xml version="1.0"?>\n<foo>A</foo>\n'
    f = StringIO.StringIO(xml_contents)
 
    doc = etree.parse(f)

    f.close()
    transform = etree.XSLT(xslt_tree)
    result = transform(doc, **params)
   
    return result
tags : python, XML, XSL

Python : Valider un RIB
def validRIB(banque, guichet, compte, cle):
    # http://fr.wikipedia.org/wiki/Clé_RIB#V.C3.A9rifier_un_RIB_avec_une_formule_Excel
    import string
    lettres = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    chiffres = "12345678912345678923456789"
    # subst letters if needed
    for char in compte:
        if char in string.letters:
            achar = char.upper()
            achiffre = chiffres[lettres.find(achar)]
            compte = compte.replace(char, achiffre)
    reste = ( 89*int(banque) + 15*int(guichet) + 3*int(compte) ) % 97
    ccle = 97 - reste
    return (ccle == int(cle))
tags : python

Python : Valider un numéro de sécurité sociale
def validInsee(insee, cle):
    # http://fr.wikipedia.org/wiki/Numero_de_Securite_sociale#Unicit.C3.A9
    # gestion numeros corses
    insee = insee.replace('A', 0)
    insee = insee.replace('B', 0)
    reste = int(insee) % 97
    return ((97 - reste) == int(cle))
 
tags : python

Django : Iterations sur un dictionnaire dans un template djangoSimple mais utile :)
{% for key,value in settings.items %}
        var SESSION_{{ key }} = "{{ value }}";
{% endfor %}
tags : python, django

Python : Détecter la version de l'OS
import sys
print sys.platform
tags : python, system

Django : Autodetect project pathdont hardcode your paths !
# add this to your settings.py 
# BASE_DIR is your main project path

BASE_DIR = os.path.abspath(os.path.split(__file__)[0])
tags : python, django

all tags : python, system, vlc, video, apache, proxy, linux, django, MySQL, .NET, XML, XSL, regexp, bat, windows, bash, git

back to snippets home
site réalisé et hébergé par revolunet © 2009 - informations légales