Last PPP Ip .

#!/usr/bin/python
"""
A really simple piece of code that i use to track down my
dynamics IP (assigned by my isp while using ppp).

"""
filename = '/home/soif/Perso/Data/lastIp.sqlite'

import sys,os,time
try:
    import sqlite
except ImportError:
    print "Please install python sqlite binding first"
    sys.exit(0)

def createTables(cursor):
    schema = "CREATE TABLE connect ( 
             id INTEGER PRIMARY KEY, 
             ip VARCHAR(27), 
             date VARCHAR 
             );"
    cursor.execute(schema)
    print "Database creation: Done"

def printLastIps(cursor):
    cursor.execute('SELECT * FROM connect ORDER BY id DESC LIMIT 15')
    results = cursor.fetchall()
    print "=" * 78
    print " Last Ips "
    print "=" * 78
    for r in results:
        print '- %-15s  %s' % ( r[1],r[2] )

def getLastIp(cursor):
    cursor.execute('SELECT * FROM connect ORDER BY id DESC LIMIT 1')
    r = cursor.fetchall()
    if len(r) > 0:
        return r[0][1]
    return

def insertCurrentIp(cursor,ip):
    sql = 'INSERT INTO connect values(NULL,"%s","%s") ' %  (ip,time.ctime())
    cursor.execute(sql)
    print "Inserting of %s: Done" % ip

def usage():
    print sys.argv[0]
    print " Arguments:"
    print "    -c    : create the database"
    print "    -a ip : add the ip to the db"
    print "    -l    : list the last ips"

#import pdb;pdb.set_trace()

db = sqlite.connect(filename)
cursor = db.cursor()

if len(sys.argv) == 2  and sys.argv[1] == '-c':
    createTables(cursor)

elif len(sys.argv) == 2  and sys.argv[1] == '-l':
    printLastIps(cursor)

elif len(sys.argv) == 3 and sys.argv[1] == '-a':
    newIp = sys.argv[2]
    lastIp = getLastIp(cursor)
    insertCurrentIp(cursor,newIp)
    if lastIp != newIp:
        print "Sending Email"
        os.system('echo Changing Ip of gateway from %s to: %s | mail -s 'New Ip %s ' -a 'From: jkx@club-internet.fr' jkx@wanadoo.fr' %  (lastIp,newIp,newIp))

else:
    usage()
db.commit()

Sample output

==============================================================================
 Last Ips
==============================================================================
- 217.128.96.43    Thu Aug 28 21:33:40 2003
- 193.252.3.209    Wed Aug 27 21:33:43 2003
- 217.128.96.95    Tue Aug 26 21:33:47 2003
- 80.15.151.254    Tue Aug 26 18:53:18 2003
- 80.15.151.107    Tue Aug 26 07:34:39 2003
- 81.48.168.91     Mon Aug 25 07:34:36 2003
- 80.15.151.40     Sun Aug 24 07:34:38 2003
- 81.48.168.41     Sat Aug 23 07:54:41 2003
- 80.15.151.125    Fri Aug 22 07:34:44 2003
- 80.15.151.169    Thu Aug 21 07:34:46 2003
- 193.251.14.187   Wed Aug 20 07:34:49 2003
- 193.251.14.36    Tue Aug 19 07:35:07 2003
- 81.48.168.47     Mon Aug 18 07:35:01 2003
- 80.15.151.187    Sun Aug 17 07:34:58 2003
- 81.48.168.75     Sat Aug 16 07:35:01 2003

AutoMatic cache for Modeling FrameWork in WebWare

This is my first hack over ZPTPage and Modeling to enable regerating of ZPTPage only when Modeling objects changed .. check out class A: (which is a sample fake Modeling Object)

import os,time

from ZPTPage import ZPTPage

class A:
    def __init__(self):
        self.a = 'B' * 50
        self.willChange()

    def getA(self):
        self.willRead()
        return self.a

    def setA(self,value):
        self.a=value
        self.willChange()

    def willRead(self):
        #print "Read %s" % self
        pass

    def willChange(self):
        self.lastChange = time.time()

class HereProxy(dict):
     def __init__(self,orig):
        print "New Here"
        self.orig = orig

     def __getitem__(self,key):
         result=getattr(self.orig,key)
         print "*** %-10s : %s " % ( key,result)
         cache = self.orig.application().cache[self.orig.hashCache()]

         if result not in cache:
             cache.update( {result:result.lastChange })
         return result

class Main(ZPTPage):
    def __init__(self):
        self.a = A()
        ZPTPage.__init__(self)
        self.here = HereProxy(self)
        self.validCache = False

    def writeHTML(self):
        if self.request().hasField('A'):
            self.a.setA(self.request().value('A') )

        cachedFileName=os.path.join('/tmp/w/',self.hashCache() +'.html')
        try:
            cache = self.application().cache[self.hashCache()]
        except KeyError:
            self.application().cache[self.hashCache()] = {}
            cache = self.application().cache[self.hashCache()]

        needUpdate = 0

        #import pdb;pdb.set_trace()
        for obj in cache.keys():
            try:
                print obj.lastChange
                if obj.lastChange !=  cache[obj]:
                    needUpdate = 1
                    break
            except AttributeError:
                needUpdate = 1
                break

        if needUpdate == 0:
            print "*** Serving cache %s ***"  % self.hashCache()
            try:
                data = open(cachedFileName,'r').read()
            except IOError:
                needUpdate = 1

        if needUpdate:
            print "*** Regerating %s ***"  % self.hashCache()
            self.buildContext()
            data = self.template.render()
            open(cachedFileName,'w').write(data)
        self.response().setHeader('Content-type', 'text/html; charset=UTF-8')
        self.writeln(data)

    def buildContext(self):
        self.updateContext('text','Toto')

    def getTime(self):
        import time
        return time.time()

    def getHere(self):
        #return {'a':A()}
        return self.here

    def sleep(self,context):
        print self.application().cache
        ZPTPage.sleep(self,context)

    ### cache ###
    def hashCache(self):
        return "MainTemplate"

Garbage Collector statistics

Have you ever wondering what is in the gabarge collector ? This little piece
of code may help :)

import string,gc

def debugGC(threshold=10):
    d = {}
    print "*" * 80
    for o in gc.get_objects():
        try:
            s = str(o.__class__)
            try:
                d[s] = d[s] + 1
            except  KeyError:
                d[s] = 1
        except AttributeError:
            pass # this is not a str_able object
    l = d.keys()
    l.sort()
    for key in l:
        if d[key] > threshold:
            print "%70s -> %d " % (key,d[key])
    print "*" * 80

Python sous l’eclipse

Différentes initiatives commencent à naitre sur les IDE python. Un relativement récente consiste à utiliser eclipse, l’IDE java.

http://www.xored.com/products.php

L’installation du plugin se fait directement via eclipse via Window -> Open Perspective -> Other resource -> Install or Update. Puis ajout de http://www.trustudio.org la fenètre en bas à gauche et c fini :)

Screenshot :