diff options
Diffstat (limited to 'pypers/bolzano')
85 files changed, 4942 insertions, 0 deletions
diff --git a/pypers/bolzano/add_to.py b/pypers/bolzano/add_to.py new file mode 100755 index 0000000..b612eb8 --- /dev/null +++ b/pypers/bolzano/add_to.py @@ -0,0 +1,17 @@ +import sys +def add_to(obj): + def wrapper(f): + setattr(obj, f.__name__, f) + return f + return wrapper + +################################### + +def obj(): pass + +@add_to(obj) +def identity(x): + return x + +print identity +print obj.identity diff --git a/pypers/bolzano/biblioteca.py b/pypers/bolzano/biblioteca.py new file mode 100755 index 0000000..6ac3882 --- /dev/null +++ b/pypers/bolzano/biblioteca.py @@ -0,0 +1,27 @@ +class Libro(object): + def __init__(self, titolo, autore): + self.titolo = titolo + self.autore = autore + def __str__(self): + return "%s | %s" % (self. titolo, self.autore) + +class Biblioteca(object): + def __init__(self, libri): + self.libri = libri + def ordina_per(self, campo): + def compara(l1, l2): + return cmp(getattr(l1, campo), getattr(l2, campo)) + lista = self.libri[:] + lista.sort(compara) + return lista + +l1 = Libro("Il Signore degli Anelli", "Tolkien") +l2 = Libro("La Luna e' una severa maestra", "Heinlein") + +archivio = Biblioteca([l1, l2]) + +for libro in archivio.ordina_per("titolo"): + print libro + +for libro in archivio.ordina_per("autore"): + print libro diff --git a/pypers/bolzano/cgi-bin/box_radio.py b/pypers/bolzano/cgi-bin/box_radio.py new file mode 100755 index 0000000..9cff61a --- /dev/null +++ b/pypers/bolzano/cgi-bin/box_radio.py @@ -0,0 +1,30 @@ +#!/usr/bin/python2.4 +import os, sys, cgi +from ms.html_utils import cgipage, cgiform, getscriptname, interp, html_form + +def entry(form): + checkbox=""" + C1<input type=checkbox name=check1><br/> + C2<input type=checkbox name=check2><br/> + C3<input type=checkbox name=check3><br/> + """ + radiobuttons=""" + R1<input type=radio name=choice value=1><br/> + R2<input type=radio name=choice value=2><br/> + R3<input type=radio name=choice value=3><br/> + """ + submit=""" + <input type='submit' name='submit' value='confirm'> + """ + return cgipage(html_form(checkbox + radiobuttons + submit)) + +def exit(form): + return cgipage(interp("""Thank you. You submitted:<br/> + check1 $check1<br/> + check2 $check2<br/> + check3 $check3<br/> + choice $choice<br/> + """, form)) + +if __name__ == "__main__": + print cgiform(entry, exit) diff --git a/pypers/bolzano/cgi-bin/example1.py b/pypers/bolzano/cgi-bin/example1.py new file mode 100755 index 0000000..0447ed4 --- /dev/null +++ b/pypers/bolzano/cgi-bin/example1.py @@ -0,0 +1,60 @@ +#!/usr/bin/python2.4 +""" +usage: %prog [options] +-i, --input=/tmp: search directory +-o, --output=.: output directory +-s, --size: order by size +""" + +import os, sys, cgi +from ms.optionparse import OptionParser, option_parser_from +from ms.html_utils import template, simplepage, printpage, cgiform, \ + getscriptname + +@template() +def checkbox(option, flags): + for flag in flags: + name = flag.dest + if not name or name == "submit": continue + checked = ["", "checked"][getattr(option, name) or 0] + yield "<tr>\n" + yield "<td>%s</td>" % flag.help + yield "<td><input type='checkbox' name=%r %s></td>" % (name, checked) + yield "</tr>\n" + +@template() +def entrybox(option, option_args): + for o_arg in option_args: + name = o_arg.dest + if not name: continue + val = getattr(option, name) or "" + yield "<tr>" + yield "<td>%s</td>" % o_arg.help + yield "<td><input type='text' name=%r value=%r></td>" % (name, val) + yield "</tr>" + +@template() +def inputform(option, op): + yield "<form action=%r>" % getscriptname() + yield "<table summary='Input form'>" + yield entrybox(option, op.get_option_args()) + yield checkbox(option, op.get_flags()) + yield "</table>" + yield "<input type='submit' name='submit' value='confirm'>" + yield "</form>" + +def entryform(form): + printpage(inputform(option, op), title="Example 1") + +def exitform(form): + printpage("Thank you for filling this form.") + +if __name__ == "__main__": + op = option_parser_from(__doc__) + op.add_option("-S", "--submit", action="store_true", default=False, + help="Submit the form") + option, args = op.parse_args() + if option.submit: # script called from the command line + os.environ["QUERY_STRING"] = "&submit=confirm" + cgiform(entryform, exitform) + diff --git a/pypers/bolzano/cgi-bin/textarea.py b/pypers/bolzano/cgi-bin/textarea.py new file mode 100755 index 0000000..a4dd9b6 --- /dev/null +++ b/pypers/bolzano/cgi-bin/textarea.py @@ -0,0 +1,22 @@ +#!/usr/bin/python2.4 +import os, sys, cgi +from ms.html_utils import cgipage, cgiform, getscriptname, interp, html_form + +def entry(form): + textarea=""" + <textarea name='text'> + Write something here + </textarea> + """ + submit=""" + <input type='submit' name='submit' value='confirm'> + """ + return cgipage(html_form(textarea + submit)) + +def exit(form): + return cgipage(interp("""Thank you. You submitted:<br/> + $text + """, dict((k, form.getfirst(k)) for k in form))) + +if __name__ == "__main__": + print cgiform(entry, exit) diff --git a/pypers/bolzano/db/BooksOnline.py b/pypers/bolzano/db/BooksOnline.py new file mode 100755 index 0000000..836c744 --- /dev/null +++ b/pypers/bolzano/db/BooksOnline.py @@ -0,0 +1,49 @@ +from quixote_utils import RootDirectory +from quixote.form.form import Form +from quixote.form.widget import * +from bookdb import Book, BookDatabase + +class DBInterface(RootDirectory): + _q_exports = ["", "show", "add_book", "edit_book"] + def __init__(self, db): + super(DBInterface, self).__init__() + self.db = db + self.currentbook = self.db.get_book("000000") + def _q_index(self): + return """Welcome to our online library! <br/><br/> + Please go to our <a href="show">show</a> page.""" + def show(self): + return "list of books" + def edit_book(self): + "" + form = Form() + for field in Book.FIELDS: + form.add(StringWidget, field, title=field, + value=getattr(self.currentbook, field)) + form.add(SubmitWidget, "submit") + if not form.is_submitted(): + return form.render() + else: + self.db.edit_book(self.currentbook.dbkey, + *[form[field] for field in Book.FIELDS]) + self.db.commit() + return "The book has been edited!" + + def add_book(self): + form = Form() + for field in Book.FIELDS: + form.add(StringWidget, field, title=field) + form.add(SubmitWidget, "submit") + if not form.is_submitted(): + return form.render() + else: + self.db.add_book(*[form[field] for field in Book.FIELDS]) + self.db.commit() + return "A new book has been added!" + + def add_from_text_file(self): + return "Please choose the book file." + + +root = DBInterface(BookDatabase("books")) +root.publish_show("edit_book", browser="mozilla") diff --git a/pypers/bolzano/db/bookdb.py b/pypers/bolzano/db/bookdb.py new file mode 100755 index 0000000..8b8c744 --- /dev/null +++ b/pypers/bolzano/db/bookdb.py @@ -0,0 +1,63 @@ +import shelve + +class Book(object): + FIELDS = ["title", "score", "author", "date", "genre", "nation"] + def __init__(self, title, score, author, date, genre, nation, dbkey): + self.title = title + self.score = score + self.author = author + self.date = date + self.genre = genre + self.nation = nation + self.dbkey = dbkey + def __str__(self): + return """<%(dbkey)s %(title)s %(score)s %(author)s %(date)s +%(genre)s %(nation)s>""" % vars(self) + +class BookDatabase(object): + def __init__(self, datafile): + self.db = shelve.open(datafile) + self.recno = len(self.dbkeys()) + self.print_all() + def commit(self): + self.db.sync() + def close(self): + self.db.close() + def getkey(self): + return "%06d" % self.recno + def dbkeys(self): + dbkeys = self.db.keys() + dbkeys.sort() + return dbkeys + def add_book(self, title, score, author, date, genre, nation): + self.db[self.getkey()] = Book( + title, score, author, date, genre, nation, self.getkey()) + self.recno += 1 + def edit_book(self, dbkey, title, score, author, date, genre, nation): + self.db[dbkey] = Book( + title, score, author, date, genre, nation, dbkey) + def add_from_file(self, filename): + for line in file(filename): + title = line[0:33].strip() + score = line[33:38].strip() + author = line[38:51].strip() + dd, mm, aa = line[51:61].strip().split("-") + genre = line[61:65].strip() + nation = line[65:67] + if "87" <= aa <= "99": + aaaa = "19" + aa + else: + aaaa = "20" + aa + date = "-".join([aaaa, mm, dd]) + self.add_book(title, score, author, date, genre, nation) + def del_book(self, book): + del self.db[book.dbkey] + def get_book(self, dbkey): + return self.db[dbkey] + def print_all(self): + for key in self.dbkeys(): + print self.db[key] + +if __name__ == "__main__": + bd = BookDatabase("books") + diff --git a/pypers/bolzano/db/books87.txt b/pypers/bolzano/db/books87.txt new file mode 100755 index 0000000..1490f5b --- /dev/null +++ b/pypers/bolzano/db/books87.txt @@ -0,0 +1,109 @@ +La sintesi Einsteiniana OOO Born 03-01-87 SF SU +I robots dell'alba OOO+ Asimov 08-01-87 FS SU +Elementi di Astrofisica OO+ Santi 14-01-87 AS IT +Il mago di Oz OOO Baum 25-01-87 FA SU +Il nome della rosa OOO Eco 06-02-87 RS IT +Figli di domani OO Van Vogt 07-02-87 FS SU +Il mondo nuovo OO+ Huxley 14-02-87 FS GB +Cosmo profondo OO+ Tubb 18-02-87 FS SU +Ars amatoria OOO Ovidio 26-02-87 LL IT +Heroides OO Ovidio 27-02-87 LL IT +Orlando Furioso OOO Bignami 27-02-87 FA IT +Unico indizio: la Luna piena OOO King 27-02-87 TR SU +Contact OO Sagan 04-03-87 FS SU +Asterix e Cleopatra OOO Uderzo 05-03-87 CO FR +Il pianeta degli schiavi OO Jenifer 05-03-87 FS SU +La Regina delle Nevi OOO Vinge 08-03-87 FS SU +Il cielo OOO Cecchini 18-03-87 AS IT +Yargo + Susann 24-03-87 FS SU +La civilta' dei Solari OO Spinrad 25-03-87 FS SU +Logo: ali per la mente OOO Reggini 30-03-87 IN IT +Fisica Statistica OO+ U. Berkeley 03-04-87 SF SU +Partiranno OO+ D'Eramo 16-04-87 FS SU +Il popolo dell'Autunno OOO+ Bradbury 17-04-87 TR SU +Racconti incompiuti OOO Tolkien 20-04-87 FA GB +Meccanica OOO U. Berkeley 02-05-87 SF SU +Il vagabondo delle scienze OOO Asimov 05-05-87 SG SU +Il Rosso e il Nero OO Stendhal 05-05-87 LF FR +L'assalto al treno OO Arpino 20-05-87 FA IT +Racconti filosofici OOO Voltaire 24-05-87 LF FR +La mano sinistra delle tenebre OOO Le Guin 25-05-87 FS SU +Introduzione alla programmazione OO Ralston 26-05-87 IN SU +Pascal OO+ Watt 08-06-87 IN SU +Il problema marziano OO Vari 09-06-87 FS SU +Teoria dei giochi OO Morgenstein 16-06-87 SM SU +Le avventure di Alice OOO Carroll 16-06-87 FA SU +Antiche sere OO+ Mailer 19-06-87 RS SU +Le avventure di Sherlock Holmes OOO+ Doyle 04-07-87 GI GB +Guerra eterna OOO Haldeman 07-07-87 FS SU +Noi marziani OOO Dick 08-07-87 FS SU +Le vie della Frontiera OO+ Chandler 09-07-87 FS SU +Shock 1 OOO Matheson 10-07-87 TR SU +Shock 2 OO+ Matheson 11-07-87 TR SU +Fuochi OO Yourcennar 13-07-87 LF FR +Il gioco dei pianeti O+ Bradbury 13-07-87 FS SU +Le quattro ore di Satana OO Hubbard 14-07-87 TR SU +E. T. il libro del Pianeta Verde OOO Kotzwinkle 15-07-87 FS SU +Le armi di Isher OOO Van Vogt 16-07-87 FS SU +Le grandi storie della FS 2 OOO+ Vari 19-07-87 FS SU +La Fantascienza OO+ Montanari 20-07-87 SG IT +Shock 3 OO Matheson 21-07-87 TR SU +Universo a sette incognite OOO Vari 21-07-87 FS SU +Shock 4 OO+ Matheson 22-07-87 TR SU +La svastica sul sole OO+ Dick 23-07-87 FS SU +I Principi Demoni OOO Vance 24-07-87 FS SU +Forth OO Vickers 25-07-87 IN SU +C OO Wagner 25-07-87 IN SU +Robot speciale OO+ Vari 26-07-87 FS SU +Stella doppia OO+ Heinlein 26-07-87 FS SU +All'ombra degli dei OO+ Vari 28-07-87 FS SU +Ponte di cenere OO+ Zelazny 30-07-87 FS SU +Dizionario del Basic OO+ Lien 30-07-87 IN SU +La danzatrice di Atlantide OO+ Anderson 02-08-87 FS SU +Il morbo di San Francesco OO+ Hughes 03-08-87 FS SU +Intervista sul PC OO+ Didday 03-08-87 IN SU +Come si programma in Pascal OO Margaroli 04-08-87 IN IT +Il giorno del cosmo + Malzberg 04-08-87 FS SU +Programmare in Assembler OO Pinaut 06-08-87 IN FR +C'era una volta un pianeta OO Iohannis 07-08-87 FS SU +La ruota a tre punte OO+ Anderson 08-08-87 FS SU +Il mercante delle stelle OO+ Anderson 08-08-87 FS SU +Pascal OO+ Le Beaux 09-08-87 IN FR +Guerra al Grande Nulla OO+ Blish 10-08-87 FS SU +Il guerriero del tramonto OO+ Lusthaden 10-08-87 FS SU +Il pianeta dei venti OOO Martin 12-08-87 FS SU +Le nebbie di Avalon OOO+ Bradley 14-08-87 FA SU +Guerra fredda OO Pohl 16-08-87 FS SU +Il mondo di Theodore Sturgeon OO Sturgeon 19-08-87 FS SU +Robot speciale: antologia OOO Van Vogt 22-08-87 FS SU +Di terrore si muore OO+ Lee 24-08-87 TR SU +Parapsicosi O+ Bunker 24-08-87 TR SU +Gummer Street OO+ Krohn 24-08-87 CO SU +Arturo e Zoe OO Bushmiller 24-08-87 CO SU +Avvertite il mondo OO+ Brunner 25-08-87 FS SU +Le tre stimmate di Palmer Dietr. OO Dick 25-08-87 FS SU +Leggende alla fine del tempo OO Moorcock 27-08-87 FS SU +La legge dei Soal OO+ Kilworth 30-08-87 FS SU +John Carter di Marte OOO Burroghs 10-09-87 FS SU +La mente di Marte OOO Burroghs 12-09-87 FS SU +Il dottor Oss OO+ Verne 12-09-87 FS SU +Il medico delle isole OO+ Magri 15-09-87 RS IT +Comunicare con il computer OO+ Mauri 16-09-87 IN IT +Il computer da scrivere OOO Eco 17-09-87 IN IT +Il mondo dei quanti OO Polkinghorne 17-09-87 SF IT +Incontri programmati OOO Enstrom 18-09-87 FS SU +I Promessi Sposi: sunti e note OO Stirati 24-09-87 LI IT +Guida ai fantasmi inglesi OO Halifax 04-10-87 TR GB +Bollettino Universitario OO+ U. Padova 09-10-87 SF IT +I Robot e l'Impero OOO Asimov 01-11-87 FS SU +Lucrezia Borgia OO Bellonci 01-11-87 ST SU +Teorie cosmologiche rivali OOO Vari 16-11-87 AS SU +Gravitazione OO+ Vari 18-11-87 AS SU +Frankenstein OOO+ Shelley 04-12-87 TR GB +Cosmolinea B-1 OOO Brown 12-12-87 FS SU +Nova SF: l'ultima stella OO+ Vari 15-12-87 FS SU +Fortran 77 OO+ Page 17-12-87 IN SU +Assembler 68000 OO Erskine 17-12-87 IN SU +Mastro Don Gesualdo OOO Verga 23-12-87 LI IT +Storia della Fantascienza I OOO Vari 28-12-87 FS SU +Disputationum Tusculanarum I OO+ Cicerone 31-12-87 LL IT diff --git a/pypers/bolzano/db/design.txt b/pypers/bolzano/db/design.txt new file mode 100755 index 0000000..d80312f --- /dev/null +++ b/pypers/bolzano/db/design.txt @@ -0,0 +1,13 @@ +FIELDS + titolo + giudizio + autore + data + genere + nazionalita + +FEATURES + add_book + add_from_text_file + edit_book + delete_book diff --git a/pypers/bolzano/db/esempio.txt b/pypers/bolzano/db/esempio.txt new file mode 100755 index 0000000..662a0de --- /dev/null +++ b/pypers/bolzano/db/esempio.txt @@ -0,0 +1,3 @@ +Magliette 10 +Pantaloni 20 +Berretti 5 diff --git a/pypers/bolzano/db/esempio2.txt b/pypers/bolzano/db/esempio2.txt new file mode 100755 index 0000000..4b306fa --- /dev/null +++ b/pypers/bolzano/db/esempio2.txt @@ -0,0 +1,2 @@ +ciao Michele +ciao Marco diff --git a/pypers/bolzano/db/iter_utils.py b/pypers/bolzano/db/iter_utils.py new file mode 100755 index 0000000..78ce0ec --- /dev/null +++ b/pypers/bolzano/db/iter_utils.py @@ -0,0 +1,151 @@ +"""General utilities involving iterables.""" + +import sets, itertools, os +try: # Python 2.4 vs. Python 2.3 + set +except NameError: + from sets import Set as set + +def check(it): + """ + Checks if an iterator is empty. Returns a copy of the original iterator. + + >>> it = check(iter([1])) + >>> if it: it.next() + 1 + """ + try: + first = it.next() + except StopIteration: + return False + else: + return itertools.chain([first], it) + +def skip_redundant(iterable, skipset=None): + "Redundant items are repeated items or items in the original skipset." + if skipset is None: skipset = set() + for item in iterable: + if item not in skipset: + skipset.add(item) + yield item + +def chop(iterable, batchsize): + """Chop an iterable. For instance + + >>> list(chop([1,2,3,4], 2)) + [[1, 2], [3, 4]] + >>> list(chop([1,2,3,4,5,6,7],3)) + [[1, 2, 3], [4, 5, 6], [7]] + + It trunks the remainder elements, if the + iterable is not divisible by batchsize. + """ + it = iter(iterable) + while True: + batch = list(itertools.islice(it, batchsize)) + if batch: yield batch + else: break + +# used in the voting package +def first_duplicate_ls(it): + """Returns None or a list with the duplicated element.""" + dupl = sets.Set() + for el in it: + if el in dupl: + return [el] + else: + dupl.add(el) + +# useful to display the list of votes in a short form +class PackedList(list): + """Take a list with repetitions and pack it in the form + + PackedList([elements ..]) --> [(number_of_repetitions, element) ...] + + Gives a nice printing representation. Usage: + PackedList(<list>, <string-repr-method> = str) + It is possible to specify a custom string representation for + the list elements.""" + + def __init__(self, ls, to_str = str): + self.to_str = to_str + self.packedls = [] + self.pack(list(ls)) + self.extend(self.packedls) + + def pack(self, lst): + """Recursive packer. At each call removes an element from ls and + adds it to self.packedls. Returns when ls is fully depleted. + """ + if not lst: return + el, ls= lst[0], lst[1:] + count = 1 # number of repetitions + for i, elem in enumerate(ls[:]): + if elem == el: # remove the duplicated element + del ls[i+1-count] # in the right position + count += 1 + self.packedls.append((count, el)) + self.pack(ls) # recurse until ls is empty + + def __str__(self): + """Returns a table <number of repetions>: <element>""" + return "\n".join(["%s: %s" % (t[0], self.to_str(t[1])) for t in self]) + +# a reiterable cycle going in both directions +class Cycle(object): + def __init__(self, seq): + self._list = list(seq) + self._len = len(self._list) + self.index = 0 + def __iter__(self): + return itertools.cycle(self._list) + def next(self): + self.index += 1 + return self() + def prev(self): + self.index -= 1 + return self() + def __len__(self): + return self._len + def __call__(self): + return self._list[self.index % self._len] + def __getitem__(self, i): + return self._list[i % self._len] + def __setitem__(self, i, v): + self._list[i % self._len] = v + +############ OLD VERSIONS ############### + +## def chop_trunk(it, n = 2): +## tup = (iter(it), ) * n +## return itertools.izip(*tup) + +## def chop_notrunk(iterable, binsize): +## bin = [] +## for i, el in enumerate(iterable): +## bin.append(el) +## if i % binsize == binsize-1: +## yield bin; bin = [] +## if bin: +## yield bin + +## def chop(iterable, binsize, trunk=False): +## if trunk: +## return chop_trunk(iterable, binsize) +## else: +## return chop_notrunk(iterable, binsize) + +if __name__ == "__main__": # test Cycle + c = Cycle([1,2,3]) + print c() + print c.next() + print c.next() + print c.next() + print c.next() + print c.next() + print c.prev() + print c.prev() + print c.prev() + print c.prev() + print c.prev() + print c.prev() diff --git a/pypers/bolzano/db/mysql/cycle.py b/pypers/bolzano/db/mysql/cycle.py new file mode 100755 index 0000000..d3d8c80 --- /dev/null +++ b/pypers/bolzano/db/mysql/cycle.py @@ -0,0 +1,66 @@ +#from itertools import cycle + +class CycleOld(object): + def __init__(self, seq): + self.seq = list(seq) + self.index = 0 + self.min_index = 0 + self.max_index = len(self.seq) - 1 + def __call__(self): + return self.seq[self.index] + def prev(self): + if self.index == self.min_index: + self.index = self.max_index + else: + self.index -= 1 + return self() + def next(self): + if self.index == self.max_index: + self.index = self.min_index + else: + self.index += 1 + return self() + +class Cycle(object): + def __init__(self, seq): + self.seq = list(seq) + self.len = len(self.seq) + self.index = 0 + def __call__(self): + return self.seq[self.index % self.len] + def prev(self): + self.index -= 1 + return self() + def next(self): + self.index += 1 + return self() + +def chop(seq, binsize): + bin = [] + for i, el in enumerate(seq): + bin.append(el) + if i % binsize == binsize - 1: + yield bin; bin = [] + if bin: + yield bin + +if __name__ == "__main__": + print list(chop("precipitevolissimevolmente", 3)) + +# chop([1,2,3,4,5,6], 2) +# [[1,2], [3,4], [4.6]] + + +## cycle = Cycle2([1,2,3]) +## print cycle() +## print cycle.prev() +## print cycle.prev() +## print cycle.prev() +## print cycle.prev() +## print "-"*10 +## print cycle.next() +## print cycle.next() +## print cycle.next() +## print cycle.next() + + diff --git a/pypers/bolzano/db/mysql/ex_dec.py b/pypers/bolzano/db/mysql/ex_dec.py new file mode 100755 index 0000000..532decd --- /dev/null +++ b/pypers/bolzano/db/mysql/ex_dec.py @@ -0,0 +1,11 @@ +def double(func): + def wrapped_func(i): + return 2*i + return wrapped_func + +def f(i): + return i + +f = double(f) + +print f(5) diff --git a/pypers/bolzano/db/mysql/ex_gen.py b/pypers/bolzano/db/mysql/ex_gen.py new file mode 100755 index 0000000..82e1f84 --- /dev/null +++ b/pypers/bolzano/db/mysql/ex_gen.py @@ -0,0 +1,19 @@ +def prova(): + yield "ciao" + yield "marco" + +for line in prova(): + print line + +error = False +it = prova() +while not error: + try: + print it.next() + except StopIteration: + error = True + +print repr("\n".join(prova())) + +print str.join("\n", prova()) +["A", 2].join("\n") diff --git a/pypers/bolzano/db/mysql/insert_books.py b/pypers/bolzano/db/mysql/insert_books.py new file mode 100755 index 0000000..8fc5aec --- /dev/null +++ b/pypers/bolzano/db/mysql/insert_books.py @@ -0,0 +1,38 @@ +import MySQLdb + +DATAFILE = "/home/micheles/md/varie/libri/libri.txt" + +def make_record(line): + title = line[0:33].strip() + score = line[33:38].strip() + author = line[38:51].strip() + dd, mm, aa = line[51:61].strip().split("-") + genre = line[61:65].strip() + nation = line[65:67] + if "87" <= aa <= "99": + aaaa = "19" + aa + else: + aaaa = "20" + aa + date = "-".join([aaaa, mm, dd]) + return title, score, author, date, genre, nation + +def escape(s): + s = s.replace("'", "\\'") + s = s.replace('"', '\\"') + return s + +def tup2str(tup): + return "(%s)" % ", ".join(['"%s"' % escape(s) for s in tup]) + +if __name__ == "__main__": + # populate the books table of the books database + cx = MySQLdb.connect() + cu = cx.cursor() + cu.execute("create database if not exists books;") + cu.execute("use books;") + cu.execute("drop table if exists books;") + cu.execute("""create table books + (title varchar(30), score char(4), author varchar(20), read_date date, + genre char(2), nation char(2));""") + for line in file(DATAFILE): + cu.execute("insert into books values %s;" % tup2str(make_record(line))) diff --git a/pypers/bolzano/db/mysql/iter_utils.py b/pypers/bolzano/db/mysql/iter_utils.py new file mode 100755 index 0000000..78ce0ec --- /dev/null +++ b/pypers/bolzano/db/mysql/iter_utils.py @@ -0,0 +1,151 @@ +"""General utilities involving iterables.""" + +import sets, itertools, os +try: # Python 2.4 vs. Python 2.3 + set +except NameError: + from sets import Set as set + +def check(it): + """ + Checks if an iterator is empty. Returns a copy of the original iterator. + + >>> it = check(iter([1])) + >>> if it: it.next() + 1 + """ + try: + first = it.next() + except StopIteration: + return False + else: + return itertools.chain([first], it) + +def skip_redundant(iterable, skipset=None): + "Redundant items are repeated items or items in the original skipset." + if skipset is None: skipset = set() + for item in iterable: + if item not in skipset: + skipset.add(item) + yield item + +def chop(iterable, batchsize): + """Chop an iterable. For instance + + >>> list(chop([1,2,3,4], 2)) + [[1, 2], [3, 4]] + >>> list(chop([1,2,3,4,5,6,7],3)) + [[1, 2, 3], [4, 5, 6], [7]] + + It trunks the remainder elements, if the + iterable is not divisible by batchsize. + """ + it = iter(iterable) + while True: + batch = list(itertools.islice(it, batchsize)) + if batch: yield batch + else: break + +# used in the voting package +def first_duplicate_ls(it): + """Returns None or a list with the duplicated element.""" + dupl = sets.Set() + for el in it: + if el in dupl: + return [el] + else: + dupl.add(el) + +# useful to display the list of votes in a short form +class PackedList(list): + """Take a list with repetitions and pack it in the form + + PackedList([elements ..]) --> [(number_of_repetitions, element) ...] + + Gives a nice printing representation. Usage: + PackedList(<list>, <string-repr-method> = str) + It is possible to specify a custom string representation for + the list elements.""" + + def __init__(self, ls, to_str = str): + self.to_str = to_str + self.packedls = [] + self.pack(list(ls)) + self.extend(self.packedls) + + def pack(self, lst): + """Recursive packer. At each call removes an element from ls and + adds it to self.packedls. Returns when ls is fully depleted. + """ + if not lst: return + el, ls= lst[0], lst[1:] + count = 1 # number of repetitions + for i, elem in enumerate(ls[:]): + if elem == el: # remove the duplicated element + del ls[i+1-count] # in the right position + count += 1 + self.packedls.append((count, el)) + self.pack(ls) # recurse until ls is empty + + def __str__(self): + """Returns a table <number of repetions>: <element>""" + return "\n".join(["%s: %s" % (t[0], self.to_str(t[1])) for t in self]) + +# a reiterable cycle going in both directions +class Cycle(object): + def __init__(self, seq): + self._list = list(seq) + self._len = len(self._list) + self.index = 0 + def __iter__(self): + return itertools.cycle(self._list) + def next(self): + self.index += 1 + return self() + def prev(self): + self.index -= 1 + return self() + def __len__(self): + return self._len + def __call__(self): + return self._list[self.index % self._len] + def __getitem__(self, i): + return self._list[i % self._len] + def __setitem__(self, i, v): + self._list[i % self._len] = v + +############ OLD VERSIONS ############### + +## def chop_trunk(it, n = 2): +## tup = (iter(it), ) * n +## return itertools.izip(*tup) + +## def chop_notrunk(iterable, binsize): +## bin = [] +## for i, el in enumerate(iterable): +## bin.append(el) +## if i % binsize == binsize-1: +## yield bin; bin = [] +## if bin: +## yield bin + +## def chop(iterable, binsize, trunk=False): +## if trunk: +## return chop_trunk(iterable, binsize) +## else: +## return chop_notrunk(iterable, binsize) + +if __name__ == "__main__": # test Cycle + c = Cycle([1,2,3]) + print c() + print c.next() + print c.next() + print c.next() + print c.next() + print c.next() + print c.prev() + print c.prev() + print c.prev() + print c.prev() + print c.prev() + print c.prev() diff --git a/pypers/bolzano/db/mysql/memoize.py b/pypers/bolzano/db/mysql/memoize.py new file mode 100755 index 0000000..58374f0 --- /dev/null +++ b/pypers/bolzano/db/mysql/memoize.py @@ -0,0 +1,21 @@ +import time + +memoize_dic = {} + +# memoize decorator +def memoize(func): + def wrapped_func(*args): + if args in memoize_dic: + return memoize_dic[args] + else: + result = func(*args) + memoize_dic[args] = result + return result + wrapped_func.__name__ = func.__name__ + return wrapped_func + +@memoize +def create_graph(n): + time.sleep(3) + return "graph%s" % n + diff --git a/pypers/bolzano/db/mysql/memoize_simple.py b/pypers/bolzano/db/mysql/memoize_simple.py new file mode 100755 index 0000000..2439157 --- /dev/null +++ b/pypers/bolzano/db/mysql/memoize_simple.py @@ -0,0 +1,18 @@ +import time + +## def memoize(func): +## return func + +memoize_dic = {} + +def create_graph(n): + if n in memoize_dic: + return memoize_dic[n] + time.sleep(3) + result = "graph%s" % n + memoize_dic[n] = result + return result + +print "created ", create_graph(1) +print "created ", create_graph(1) + diff --git a/pypers/bolzano/db/mysql/mysite.py b/pypers/bolzano/db/mysql/mysite.py new file mode 100755 index 0000000..068ea2a --- /dev/null +++ b/pypers/bolzano/db/mysql/mysite.py @@ -0,0 +1,21 @@ +from quixote_utils import RootDirectory, get_user +from quixote.publish import SessionPublisher +from registration import register, login, logout, private +import MySQLdb + +class MySite(RootDirectory): + _q_exports = ["register", "login", "logout", "mainpage", "hello"] + def __init__(self): + self.cx = MySQLdb.connect(db="site_db") + register = register + login = login + logout = logout + + @private + def hello(self): + return "hello" + +if __name__ == "__main__": + site = MySite() + site.set_default(Publisher=SessionPublisher) + site.publish_show("hello") diff --git a/pypers/bolzano/db/mysql/prova.py b/pypers/bolzano/db/mysql/prova.py new file mode 100755 index 0000000..7f69e78 --- /dev/null +++ b/pypers/bolzano/db/mysql/prova.py @@ -0,0 +1,9 @@ +import MySQLdb +cx = MySQLdb.connect(db="books") +cu = cx.cursor() + +def getfields(cu, tablename): + cu.execute("describe %s;" % tablename) + return [tupl[0] for tupl in cu.fetchall()] + +print getfields(cu, "books") diff --git a/pypers/bolzano/db/mysql/quixote_utils.py b/pypers/bolzano/db/mysql/quixote_utils.py new file mode 100755 index 0000000..0a93d42 --- /dev/null +++ b/pypers/bolzano/db/mysql/quixote_utils.py @@ -0,0 +1,191 @@ +import os, sys, time, webbrowser +from quixote.directory import Directory +from quixote.publish import Publisher, SessionPublisher +from quixote.session import Session, SessionManager +from quixote.server import simple_server +from quixote.errors import AccessError +from quixote import get_response, get_user +from quixote.html import href, htmltext +from quixote.form.form import Form +from quixote.form.widget import * + +webbrowser.register("konqueror", webbrowser.Konqueror) +elinks = webbrowser.GenericBrowser('xterm -e elinks %s') +lynx = webbrowser.GenericBrowser('xterm -e lynx -accept_all_cookies %s') +webbrowser.register("elinks", webbrowser.GenericBrowser, elinks) +webbrowser.register("lynx", webbrowser.GenericBrowser, lynx) # second choice + +class RecognizeExports(type): + def __init__(cls, name, bases, dic): + super(RecognizeExports, cls).__init__(cls, name, bases, dic) + for k in dic: setattr(cls, k, dic[k]) + def __setattr__(cls, name, value): + if hasattr(value, "_q_exported"): + cls._q_exports.append(name) + super(RecognizeExports, cls).__setattr__(name, value) + +# by definition, the root directory is a singleton +class RootDirectory(Directory): + _q_exports = [""] + __metaclass__ = RecognizeExports + __Publisher = Publisher + __server = simple_server + __port = 7080 + + def _q_index(self): + return "Welcome to the root of your application." + + def set_default(self, server=simple_server, Publisher=Publisher, + Session=Session, session_mapping=None, port=7080): + self.__server = server + self.__Publisher = Publisher + self.__Session = Session + self.__session_mapping = session_mapping + self.__port = port + + __init__ = set_default + + def publish(self): + if issubclass(self.__Publisher, SessionPublisher): + create_pub = lambda : self.__Publisher( + self, SessionManager(self.__Session, self.__session_mapping)) + else: + create_pub = lambda : self.__Publisher(self) + self.__server.run(create_pub, '', self.__port) + + def publish_show(self, page="", browser="mozilla"): + if os.fork(): # parent + self.publish() + else: # child + webbrowser.get(browser).open( + "http://localhost:%s/%s" % (self.__port, page)) + + +class UnauthorizedError(AccessError): + """The request requires user authentication. + + This subclass of AccessError sends a 401 instead of a 403, + hinting that the client should try again with authentication. + """ + status_code = 401 + title = "Unauthorized" + description = "You are not authorized to access this resource." + + def __init__(self, realm='Protected', public_msg=None, private_msg=None): + self.realm = realm + AccessError.__init__(self, public_msg, private_msg) + + def format(self): + get_response().set_header( + 'WWW-Authenticate', 'Basic realm="%s"' % self.realm) + return AccessError.format(self) + + +class User(object): + def __init__(self, username, password): + self.username = username + self.password = password + def __str__(self): + return "<User: %s %s>" % (self.username, self.password) + def permissions(self): + """Returns the list of methods starting with 'can_'.""" + return [perm for perm in dir(self) if perm.startswith("can_")] + +def public(f): + f._q_exported = True + return f + +class private(object): + """Redirect to the login page if the user is not logged in or if he does + not have the right permissions.""" + # obviously, this assumes a login page exists and is called 'login' + def __init__(self, *groups_with_access): + self.valid_groups = groups_with_access or (User,) + def __call__(self, method): + def wrapper(root): + user = get_user() + if not user or not isinstance(user, self.valid_groups): + root.resume = meth_name + valid_groups = ", ".join([ + cls.__name__ for cls in self.valid_groups]) + return "You are trying to access a page restricted to %s. " % \ + valid_groups + href( + "login", "Please login as a valid user.") + else: + return method(root) + meth_name = method.func_name + wrapper.func_name = meth_name + wrapper._q_exported = True + return wrapper + +######################## deprecated ############################ + +def old_public(f): + """Append f.__name__ to the caller's _q_exports. If the caller has + no _q_exports, creates it.""" + _q_exports = sys._getframe(1).f_locals.setdefault("_q_exports",[""]) + _q_exports.append(f.__name__) + return f + +class old_private(object): + """Redirect to the login page if the user is not logged in or if he does + not have the right permissions.""" + # obviously, this assumes a login page exists and is called 'login' + def __init__(self, *groups_with_access): + self.valid_groups = groups_with_access or (User,) + def __call__(self, method): + def wrapper(root): + user = get_user() + if not user or not isinstance(user, self.valid_groups): + root.resume = meth_name + valid_groups = ", ".join([cls.__name__ for cls + in self.valid_groups]) + return "You are trying to access a page restricted to %s. " % \ + valid_groups + href("login", "Please login as a valid user.") + else: + return method(root) + meth_name = method.func_name + _q_exports = sys._getframe(1).f_locals.setdefault("_q_exports",[""]) + _q_exports.append(meth_name) + wrapper.func_name = meth_name + return wrapper + +from iter_utils import Cycle, chop + +class MultipageTable(object): + # use Quixote forms + def __init__(self, body, header=[], maxsize=20): + self.header = header + self.maxsize = maxsize + self.section = Cycle(chop(body, maxsize)) + self.sect = self.section[0] # default + self.ismultipage = len(self.section) > 1 + + def makerow(self, row, header=False): + if header: + r = " ".join(["<th>%s</th>" % col for col in row]) + else: + r = " ".join(["<td>%s</td>" % col for col in row]) + return "<tr>%s</tr>" % r + + def maketable(self): + if self.ismultipage: + form = Form() + form.add(SubmitWidget, "prev", "Prev") + form.add(SubmitWidget, "next", "Next") + if form["next"]: # is submitted + self.sect = self.section.next() + if form["prev"]: # is submitted + self.sect = self.section.prev() + yield "Page #%s of %s" % (self.section.index+1, len(self.section)) + yield "<table border='1'>" + if self.header: + yield self.makerow(self.header) + for row in self.sect: + yield self.makerow(row) + yield "</table>" + if self.ismultipage: + yield form.render() + + def render(self): + return htmltext("\n").join(map(htmltext, self.maketable())) diff --git a/pypers/bolzano/db/mysql/quixote_utils24.py b/pypers/bolzano/db/mysql/quixote_utils24.py new file mode 100755 index 0000000..6288b1b --- /dev/null +++ b/pypers/bolzano/db/mysql/quixote_utils24.py @@ -0,0 +1,259 @@ +""" +Example of usage: + +from ms.quixote_utils24 import SimpleDirectory, Publish +from quixote.server import twisted_server + +class Root(SimpleDirectory): + def _q_index(self): + return "hello" + +Publish(Root(), showpage="", server=twisted_server) +""" +import os, sys, threading, webbrowser +from quixote.directory import Directory +from quixote.session import Session, SessionManager +from quixote.server import simple_server +from quixote.errors import AccessError +from quixote.form.form import Form +from quixote.form.widget import StringWidget, PasswordWidget, SubmitWidget +from quixote import get_response, get_user, get_session +from quixote.publish import Publisher +from quixote.html import href, htmltext + +################## PUBLICATION MACHINERY ########################### + +elinks = webbrowser.GenericBrowser('xterm -e elinks %s') +lynx = webbrowser.GenericBrowser('xterm -e lynx -accept_all_cookies %s') +webbrowser.register("elinks", webbrowser.GenericBrowser, elinks) +webbrowser.register("lynx", webbrowser.GenericBrowser, lynx) # second choice +webbrowser.register("konqueror", webbrowser.Konqueror) + +class Publish(object): + def __init__(self, root, Publisher=Publisher, Session=Session, + session_mapping=None, server=simple_server, + showpage=None, browser="mozilla", host='', port=7080): + self.root = root + self.Publisher = Publisher + self.Session = Session + self.session_mapping = session_mapping + self.server = server + self.host = host + self.port = port + self.showpage = showpage + self.browser = browser + if showpage is not None: # wait a bit and then open a browser + threading.Timer(0.1, self.show).start() + self.publish() + + def make_publisher(self): + return self.Publisher(self.root, session_manager=SessionManager( + self.Session, self.session_mapping)) + + def publish(self): + try: + self.server.run(self.make_publisher, self.host, self.port) + except KeyboardInterrupt: + print "Server stopped by CTRL-C." + + def show(self): + webbrowser.get(self.browser).open("http://localhost:%s/%s" % ( + self.port, self.showpage)) + +def public(f): + f._q_exported = True + return f + +class AutoExport(type): + """Attributes of instances of AutoExport with a "_q_exported" + flag are automatically added to the class _q_exports list. + """ + def __init__(cls, name, bases, dic): + cls._q_exports = sum( + (getattr(base, "_q_exports", []) for base in bases), []) or [""] + for k in dic: + setattr(cls, k, dic[k]) + super(AutoExport, cls).__init__(name, bases, dic) + def __setattr__(cls, name, value): + if hasattr(value, "_q_exported"): + cls._q_exports.append(name) + super(AutoExport, cls).__setattr__(name, value) + +class SimpleDirectory(Directory): + __metaclass__ = AutoExport + + def _q_index(self): # to be overridden in subclasses + return "Welcome to the root of your application." + +################# AUTHENTICATION MACHINERY ##################### + +class User(object): + def __init__(self, username=None, password=None): + self.username = username + self.password = password + def __str__(self): + return "<User: %s %s>" % (self.username, self.password) + def permissions(self): + """Returns the list of methods starting with 'can_'.""" + return [perm for perm in dir(self) if perm.startswith("can_")] + +class private(object): + """Redirect to the login page if the user is not logged in or if he does + not have the right permissions.""" + # obviously, this assumes a login page exists and is called 'login' + msg = """\ +You are trying to access a page restricted to %r. +Please <a href='login'>login</a> as a valid user.""" + def __init__(self, *groups_with_access): + self.valid_groups = groups_with_access or (User,) + def __call__(self, method): + def wrapper(root): + user = get_user() + if not user or not isinstance(user, self.valid_groups): + root.resume = meth_name + valid_groups = ", ".join( + cls.__name__ for cls in self.valid_groups) + return self.msg % valid_groups + else: + return method(root) + meth_name = method.func_name + wrapper.func_name = meth_name + wrapper._q_exported = True + return wrapper + +import shelve + +def un_pw_form(): + form = Form() + form.add(StringWidget, 'username', title="Username") + form.add(PasswordWidget, 'password', title="Password") + form.add(SubmitWidget, "submit", "Submit") + return form + +class WebDirectory(SimpleDirectory): + """A simple directory plus a login form with a resume capability.""" + resume = None + registered_users = shelve.open("registered_users") + + @public + def mainpage(self): + if not get_user(): + self.resume = 'mainpage' + return """Welcome to the best site of the World! If this is + your first visit, please <a href='register'>register</a> else + <a href='login'>login</a>.""" + else: + return htmltext( + "Content of the site." + "Click <a href='logout'>here</a> to logout.") + + _q_index = mainpage + + @public + def register(self): + form = un_pw_form() + if not form.is_submitted(): + return htmltext("<h1>Registration form</h1>") + form.render() + else: + self.registered_users[form["username"]] = form["password"] + self.registered_users.sync() + return htmltext("Thank you for registering. ") + self.login() + + @public + def login(self, User=User): + """Subclassess are free to override the login form. This is an example + of how to do it: + + class MyWebDirectory(WebDirectory): + @public + def login(self, User=MyUserClass): + return super(MyWebDirectory, self).login(MyUserClass) + """ + form = un_pw_form() + if not form.is_submitted(): + return htmltext("<h1>Login form</h1>") + form.render() + un, pw = form["username"], form["password"] + if un not in self.registered_users: + return """\ + You are not a registered user. + Please <a href='register'>register</a> first.""" + elif pw != self.registered_users[un]: + return "Wrong password. Please <a href='login'>retry</a>.""" + + user = User(un, pw) + get_session().set_user(user) + msg = "Now you are logged in as %r. " % user.username + if self.resume is not None: + msg += htmltext( + "You can <a href=%r>resume</a> from where you left." % self.resume) + return msg + + @private() + def logout(self): + get_session().set_user(None) + return "You are now logged out." + +########################### NOT ESSENTIAL STUFF ############################ + +class UnauthorizedError(AccessError): + """The request requires user authentication. + + This subclass of AccessError sends a 401 instead of a 403, + hinting that the client should try again with authentication. + """ + status_code = 401 + title = "Unauthorized" + description = "You are not authorized to access this resource." + + def __init__(self, realm='Protected', public_msg=None, private_msg=None): + self.realm = realm + AccessError.__init__(self, public_msg, private_msg) + + def format(self): + get_response().set_header( + 'WWW-Authenticate', 'Basic realm="%s"' % self.realm) + return AccessError.format(self) + +################## UI STUFF ################################## + +from ms.iter_utils import Cycle, chop + +class MultipageTable(object): + # use Quixote forms + def __init__(self, body, header=[], maxsize=20): + self.header = header + self.maxsize = maxsize + self.section = Cycle(chop(body, maxsize)) + self.sect = self.section[0] # default + self.ismultipage = len(self.section) > 1 + + def makerow(self, row, header=False): + if header: + r = " ".join("<th>%s</th>" % col for col in row) + else: + r = " ".join("<td>%s</td>" % col for col in row) + return "<tr>%s</tr>" % r + + def maketable(self): + #yield "<div align='center'>" + if self.ismultipage: + form = Form() + form.add(SubmitWidget, "prev", "Prev") + form.add(SubmitWidget, "next", "Next") + if form["next"]: # is submitted + self.sect = self.section.next() + if form["prev"]: # is submitted + self.sect = self.section.prev() + yield "Page #%s of %s" % (self.section.index+1, len(self.section)) + yield "<table border='1'>" + if self.header: + yield self.makerow(self.header) + for row in self.sect: + yield self.makerow(row) + yield "</table>" + if self.ismultipage: + yield form.render() + #yield "</div>" + + def render(self): + return htmltext("\n").join(map(htmltext, self.maketable())) diff --git a/pypers/bolzano/db/mysql/registration.py b/pypers/bolzano/db/mysql/registration.py new file mode 100755 index 0000000..7de5c09 --- /dev/null +++ b/pypers/bolzano/db/mysql/registration.py @@ -0,0 +1,55 @@ +"""Method to be added to MySite.""" + +from quixote.form.form import Form +from quixote.form.widget import * +from quixote.html import htmltext +from user_passwd_db import add_user_passwd, valid_user,ErrorAlreadyExistingUser +from quixote import get_user, get_session + +def user_passwd_form(): + form = Form() + form.add(StringWidget, "un", title = "Username") + form.add(PasswordWidget, "pw", title = "Password") + form.add(SubmitWidget, "submit", "Submit") + return form + +def register(self): + form = user_passwd_form() + if form.is_submitted(): + try: + add_user_passwd(self.cx.cursor(), form["un"], form["pw"]) + except ErrorAlreadyExistingUser, e: + return str(e) + return "You are now registered!" + else: + return htmltext("<h1>Registration Form</h1>") + form.render() + +def login(self): + user = get_user() + if user is None: + form = user_passwd_form() + if form.is_submitted(): + if valid_user(self.cx.cursor(), form["un"], form["pw"]): + get_session().set_user(form["un"]) # this is the point! + return "You are logged in." + else: + return "You are not registered or your password is invalid!" + else: + return htmltext("<h1>Login Form</h1>") + form.render() + else: + return "You are already logged in!" + +def logout(self): + get_session().set_user(None) + return "Now you are logged out." + +def private(page): + def private_page(self): + user = get_user() + if user: + return page(self) + else: + return "This page can only be accessed by registered members. " \ + "Please <a href='login'>login</a>." + private_page.__name__ = page.__name__ + return private_page diff --git a/pypers/bolzano/db/mysql/stat_books.py b/pypers/bolzano/db/mysql/stat_books.py new file mode 100755 index 0000000..ad499b5 --- /dev/null +++ b/pypers/bolzano/db/mysql/stat_books.py @@ -0,0 +1,32 @@ +import MySQLdb, subprocess + +def percent(n, ntot): + return float(n)/ntot * 100 + +def gen_histo(cx, kind, datafile): + cu = cx.cursor() + cu.execute("""select %s, count(*) from books group by %s + order by %s;""" % (kind, kind, kind)) + books_per_kind = cu.fetchall() + xtics = []; i = 0 + f = file(datafile, "w") + for k, counts in books_per_kind: + print >> f, counts + xtics.append("%r %s" % (k, i)) + i += 1 + yield "set term png" + yield "set output '%s.png'" % datafile[:-4] + yield "set style fill solid" + yield "set style fill border 2" + yield "set xrange [-1:15]" + yield "set xtics (%s)" % ", ".join(xtics) + yield "plot %r with boxes" % datafile + +def make_plot(cx, kind, datafile): + gnuplot = subprocess.Popen(["gnuplot"], stdin=subprocess.PIPE) + # for line in gen_histo(cx, kind, datafile): print line + gnuplot.communicate("\n".join(gen_histo(cx, kind, datafile))) + +if __name__ == "__main__": + cx = MySQLdb.connect(db="books") + make_plot(cx, "nation", "nation.dat") diff --git a/pypers/bolzano/db/mysql/stat_books_OO.py b/pypers/bolzano/db/mysql/stat_books_OO.py new file mode 100755 index 0000000..c8a9883 --- /dev/null +++ b/pypers/bolzano/db/mysql/stat_books_OO.py @@ -0,0 +1,41 @@ +import MySQLdb, subprocess, os, memoize + +def percent(n, ntot): + return float(n)/ntot * 100 + +class BookPlotter(object): + def __init__(self, cx): + self.cx = cx + + @ memoize.memoize + def plot(self, kind, datafile): + gnuplot = subprocess.Popen(["gnuplot"], stdin=subprocess.PIPE) + gnuplot.communicate("\n".join(self.gen_histo(kind, datafile))) + + def gen_histo(self, kind, datafile): + cu = self.cx.cursor() + cu.execute("""select %s, count(*) from books group by %s + order by %s;""" % (kind, kind, kind)) + books_per_kind = cu.fetchall() + xtics = []; i = 0 + f = file(datafile, "w") + for k, counts in books_per_kind: + print >> f, counts + xtics.append("%r %s" % (k, i)) + i += 1 + self.imagefile = os.path.abspath(datafile[:-4] + ".png") + yield "set term png" + yield "set output %r" % self.imagefile + yield "set style fill solid" + yield "set style fill border 2" + yield "set xrange [-1:15]" + yield "set xtics (%s)" % ", ".join(xtics) + yield "plot %r with boxes" % datafile + + def show(self): + subprocess.call(["display", self.imagefile]) + +if __name__ == "__main__": + plotter = BookPlotter(MySQLdb.connect(db="books")) + plotter.plot("genre", "genre.dat") + plotter.show() diff --git a/pypers/bolzano/db/mysql/ui/HTMLTable.py b/pypers/bolzano/db/mysql/ui/HTMLTable.py new file mode 100755 index 0000000..5b6fe53 --- /dev/null +++ b/pypers/bolzano/db/mysql/ui/HTMLTable.py @@ -0,0 +1,47 @@ +import os +from cycle import Cycle, chop +from quixote.form.form import Form +import quixote.form.widget as w +from quixote_utils import RootDirectory, htmltext + +class HTMLTable(object): + def __init__(self, body, header=None, maxsize=20): + self.header = header or [] + self.body = body + self.maxsize = maxsize + self.cycle = Cycle(chop(self.body, maxsize)) + + def make_row(self, row, typ="td"): + return "<tr>%s</tr>" % "".join(["<%s>%s</%s>" % + (typ, col, typ) for col in row]) + def gen_table(self): + yield "<table border='1'>" + yield self.make_row(self.header, "th") + for row in self.cycle(): + yield self.make_row(row) + yield "</table>" + + + def render(self): + return "\n".join(self.gen_table()) + +if __name__ == "__main__": # test + + + class Root(RootDirectory): + _q_exports = ["show_table"] + table = HTMLTable([["a", i] for i in range(100)]) + def show_table(self): + form = Form() + form.add(w.SubmitWidget, "prev", "prev") + form.add(w.SubmitWidget, "next", "next") + if form.is_submitted(): + if form["prev"]: + self.table.cycle.prev() + elif form["next"]: + self.table.cycle.next() + return htmltext(self.table.render()) + form.render() + + Root().publish_show("show_table") + + diff --git a/pypers/bolzano/db/mysql/ui/__init__.py b/pypers/bolzano/db/mysql/ui/__init__.py new file mode 100755 index 0000000..e69de29 --- /dev/null +++ b/pypers/bolzano/db/mysql/ui/__init__.py diff --git a/pypers/bolzano/db/mysql/ui/cycle.py b/pypers/bolzano/db/mysql/ui/cycle.py new file mode 100755 index 0000000..d3d8c80 --- /dev/null +++ b/pypers/bolzano/db/mysql/ui/cycle.py @@ -0,0 +1,66 @@ +#from itertools import cycle + +class CycleOld(object): + def __init__(self, seq): + self.seq = list(seq) + self.index = 0 + self.min_index = 0 + self.max_index = len(self.seq) - 1 + def __call__(self): + return self.seq[self.index] + def prev(self): + if self.index == self.min_index: + self.index = self.max_index + else: + self.index -= 1 + return self() + def next(self): + if self.index == self.max_index: + self.index = self.min_index + else: + self.index += 1 + return self() + +class Cycle(object): + def __init__(self, seq): + self.seq = list(seq) + self.len = len(self.seq) + self.index = 0 + def __call__(self): + return self.seq[self.index % self.len] + def prev(self): + self.index -= 1 + return self() + def next(self): + self.index += 1 + return self() + +def chop(seq, binsize): + bin = [] + for i, el in enumerate(seq): + bin.append(el) + if i % binsize == binsize - 1: + yield bin; bin = [] + if bin: + yield bin + +if __name__ == "__main__": + print list(chop("precipitevolissimevolmente", 3)) + +# chop([1,2,3,4,5,6], 2) +# [[1,2], [3,4], [4.6]] + + +## cycle = Cycle2([1,2,3]) +## print cycle() +## print cycle.prev() +## print cycle.prev() +## print cycle.prev() +## print cycle.prev() +## print "-"*10 +## print cycle.next() +## print cycle.next() +## print cycle.next() +## print cycle.next() + + diff --git a/pypers/bolzano/db/mysql/ui/iter_utils.py b/pypers/bolzano/db/mysql/ui/iter_utils.py new file mode 100755 index 0000000..78ce0ec --- /dev/null +++ b/pypers/bolzano/db/mysql/ui/iter_utils.py @@ -0,0 +1,151 @@ +"""General utilities involving iterables.""" + +import sets, itertools, os +try: # Python 2.4 vs. Python 2.3 + set +except NameError: + from sets import Set as set + +def check(it): + """ + Checks if an iterator is empty. Returns a copy of the original iterator. + + >>> it = check(iter([1])) + >>> if it: it.next() + 1 + """ + try: + first = it.next() + except StopIteration: + return False + else: + return itertools.chain([first], it) + +def skip_redundant(iterable, skipset=None): + "Redundant items are repeated items or items in the original skipset." + if skipset is None: skipset = set() + for item in iterable: + if item not in skipset: + skipset.add(item) + yield item + +def chop(iterable, batchsize): + """Chop an iterable. For instance + + >>> list(chop([1,2,3,4], 2)) + [[1, 2], [3, 4]] + >>> list(chop([1,2,3,4,5,6,7],3)) + [[1, 2, 3], [4, 5, 6], [7]] + + It trunks the remainder elements, if the + iterable is not divisible by batchsize. + """ + it = iter(iterable) + while True: + batch = list(itertools.islice(it, batchsize)) + if batch: yield batch + else: break + +# used in the voting package +def first_duplicate_ls(it): + """Returns None or a list with the duplicated element.""" + dupl = sets.Set() + for el in it: + if el in dupl: + return [el] + else: + dupl.add(el) + +# useful to display the list of votes in a short form +class PackedList(list): + """Take a list with repetitions and pack it in the form + + PackedList([elements ..]) --> [(number_of_repetitions, element) ...] + + Gives a nice printing representation. Usage: + PackedList(<list>, <string-repr-method> = str) + It is possible to specify a custom string representation for + the list elements.""" + + def __init__(self, ls, to_str = str): + self.to_str = to_str + self.packedls = [] + self.pack(list(ls)) + self.extend(self.packedls) + + def pack(self, lst): + """Recursive packer. At each call removes an element from ls and + adds it to self.packedls. Returns when ls is fully depleted. + """ + if not lst: return + el, ls= lst[0], lst[1:] + count = 1 # number of repetitions + for i, elem in enumerate(ls[:]): + if elem == el: # remove the duplicated element + del ls[i+1-count] # in the right position + count += 1 + self.packedls.append((count, el)) + self.pack(ls) # recurse until ls is empty + + def __str__(self): + """Returns a table <number of repetions>: <element>""" + return "\n".join(["%s: %s" % (t[0], self.to_str(t[1])) for t in self]) + +# a reiterable cycle going in both directions +class Cycle(object): + def __init__(self, seq): + self._list = list(seq) + self._len = len(self._list) + self.index = 0 + def __iter__(self): + return itertools.cycle(self._list) + def next(self): + self.index += 1 + return self() + def prev(self): + self.index -= 1 + return self() + def __len__(self): + return self._len + def __call__(self): + return self._list[self.index % self._len] + def __getitem__(self, i): + return self._list[i % self._len] + def __setitem__(self, i, v): + self._list[i % self._len] = v + +############ OLD VERSIONS ############### + +## def chop_trunk(it, n = 2): +## tup = (iter(it), ) * n +## return itertools.izip(*tup) + +## def chop_notrunk(iterable, binsize): +## bin = [] +## for i, el in enumerate(iterable): +## bin.append(el) +## if i % binsize == binsize-1: +## yield bin; bin = [] +## if bin: +## yield bin + +## def chop(iterable, binsize, trunk=False): +## if trunk: +## return chop_trunk(iterable, binsize) +## else: +## return chop_notrunk(iterable, binsize) + +if __name__ == "__main__": # test Cycle + c = Cycle([1,2,3]) + print c() + print c.next() + print c.next() + print c.next() + print c.next() + print c.next() + print c.prev() + print c.prev() + print c.prev() + print c.prev() + print c.prev() + print c.prev() diff --git a/pypers/bolzano/db/mysql/ui/quixote_utils.py b/pypers/bolzano/db/mysql/ui/quixote_utils.py new file mode 100755 index 0000000..0a93d42 --- /dev/null +++ b/pypers/bolzano/db/mysql/ui/quixote_utils.py @@ -0,0 +1,191 @@ +import os, sys, time, webbrowser +from quixote.directory import Directory +from quixote.publish import Publisher, SessionPublisher +from quixote.session import Session, SessionManager +from quixote.server import simple_server +from quixote.errors import AccessError +from quixote import get_response, get_user +from quixote.html import href, htmltext +from quixote.form.form import Form +from quixote.form.widget import * + +webbrowser.register("konqueror", webbrowser.Konqueror) +elinks = webbrowser.GenericBrowser('xterm -e elinks %s') +lynx = webbrowser.GenericBrowser('xterm -e lynx -accept_all_cookies %s') +webbrowser.register("elinks", webbrowser.GenericBrowser, elinks) +webbrowser.register("lynx", webbrowser.GenericBrowser, lynx) # second choice + +class RecognizeExports(type): + def __init__(cls, name, bases, dic): + super(RecognizeExports, cls).__init__(cls, name, bases, dic) + for k in dic: setattr(cls, k, dic[k]) + def __setattr__(cls, name, value): + if hasattr(value, "_q_exported"): + cls._q_exports.append(name) + super(RecognizeExports, cls).__setattr__(name, value) + +# by definition, the root directory is a singleton +class RootDirectory(Directory): + _q_exports = [""] + __metaclass__ = RecognizeExports + __Publisher = Publisher + __server = simple_server + __port = 7080 + + def _q_index(self): + return "Welcome to the root of your application." + + def set_default(self, server=simple_server, Publisher=Publisher, + Session=Session, session_mapping=None, port=7080): + self.__server = server + self.__Publisher = Publisher + self.__Session = Session + self.__session_mapping = session_mapping + self.__port = port + + __init__ = set_default + + def publish(self): + if issubclass(self.__Publisher, SessionPublisher): + create_pub = lambda : self.__Publisher( + self, SessionManager(self.__Session, self.__session_mapping)) + else: + create_pub = lambda : self.__Publisher(self) + self.__server.run(create_pub, '', self.__port) + + def publish_show(self, page="", browser="mozilla"): + if os.fork(): # parent + self.publish() + else: # child + webbrowser.get(browser).open( + "http://localhost:%s/%s" % (self.__port, page)) + + +class UnauthorizedError(AccessError): + """The request requires user authentication. + + This subclass of AccessError sends a 401 instead of a 403, + hinting that the client should try again with authentication. + """ + status_code = 401 + title = "Unauthorized" + description = "You are not authorized to access this resource." + + def __init__(self, realm='Protected', public_msg=None, private_msg=None): + self.realm = realm + AccessError.__init__(self, public_msg, private_msg) + + def format(self): + get_response().set_header( + 'WWW-Authenticate', 'Basic realm="%s"' % self.realm) + return AccessError.format(self) + + +class User(object): + def __init__(self, username, password): + self.username = username + self.password = password + def __str__(self): + return "<User: %s %s>" % (self.username, self.password) + def permissions(self): + """Returns the list of methods starting with 'can_'.""" + return [perm for perm in dir(self) if perm.startswith("can_")] + +def public(f): + f._q_exported = True + return f + +class private(object): + """Redirect to the login page if the user is not logged in or if he does + not have the right permissions.""" + # obviously, this assumes a login page exists and is called 'login' + def __init__(self, *groups_with_access): + self.valid_groups = groups_with_access or (User,) + def __call__(self, method): + def wrapper(root): + user = get_user() + if not user or not isinstance(user, self.valid_groups): + root.resume = meth_name + valid_groups = ", ".join([ + cls.__name__ for cls in self.valid_groups]) + return "You are trying to access a page restricted to %s. " % \ + valid_groups + href( + "login", "Please login as a valid user.") + else: + return method(root) + meth_name = method.func_name + wrapper.func_name = meth_name + wrapper._q_exported = True + return wrapper + +######################## deprecated ############################ + +def old_public(f): + """Append f.__name__ to the caller's _q_exports. If the caller has + no _q_exports, creates it.""" + _q_exports = sys._getframe(1).f_locals.setdefault("_q_exports",[""]) + _q_exports.append(f.__name__) + return f + +class old_private(object): + """Redirect to the login page if the user is not logged in or if he does + not have the right permissions.""" + # obviously, this assumes a login page exists and is called 'login' + def __init__(self, *groups_with_access): + self.valid_groups = groups_with_access or (User,) + def __call__(self, method): + def wrapper(root): + user = get_user() + if not user or not isinstance(user, self.valid_groups): + root.resume = meth_name + valid_groups = ", ".join([cls.__name__ for cls + in self.valid_groups]) + return "You are trying to access a page restricted to %s. " % \ + valid_groups + href("login", "Please login as a valid user.") + else: + return method(root) + meth_name = method.func_name + _q_exports = sys._getframe(1).f_locals.setdefault("_q_exports",[""]) + _q_exports.append(meth_name) + wrapper.func_name = meth_name + return wrapper + +from iter_utils import Cycle, chop + +class MultipageTable(object): + # use Quixote forms + def __init__(self, body, header=[], maxsize=20): + self.header = header + self.maxsize = maxsize + self.section = Cycle(chop(body, maxsize)) + self.sect = self.section[0] # default + self.ismultipage = len(self.section) > 1 + + def makerow(self, row, header=False): + if header: + r = " ".join(["<th>%s</th>" % col for col in row]) + else: + r = " ".join(["<td>%s</td>" % col for col in row]) + return "<tr>%s</tr>" % r + + def maketable(self): + if self.ismultipage: + form = Form() + form.add(SubmitWidget, "prev", "Prev") + form.add(SubmitWidget, "next", "Next") + if form["next"]: # is submitted + self.sect = self.section.next() + if form["prev"]: # is submitted + self.sect = self.section.prev() + yield "Page #%s of %s" % (self.section.index+1, len(self.section)) + yield "<table border='1'>" + if self.header: + yield self.makerow(self.header) + for row in self.sect: + yield self.makerow(row) + yield "</table>" + if self.ismultipage: + yield form.render() + + def render(self): + return htmltext("\n").join(map(htmltext, self.maketable())) diff --git a/pypers/bolzano/db/mysql/ui/table.html b/pypers/bolzano/db/mysql/ui/table.html new file mode 100755 index 0000000..c914c52 --- /dev/null +++ b/pypers/bolzano/db/mysql/ui/table.html @@ -0,0 +1,23 @@ +<table border='1'> +<tr><th>Variable</th><th>Value</th></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +</table> diff --git a/pypers/bolzano/db/mysql/ui/x.html b/pypers/bolzano/db/mysql/ui/x.html new file mode 100755 index 0000000..999462e --- /dev/null +++ b/pypers/bolzano/db/mysql/ui/x.html @@ -0,0 +1,104 @@ +[['p', 'r', 'e'], ['c', 'i', 'p'], ['i', 't', 'e'], ['v', 'o', 'l'], ['i', 's', 's'], ['i', 'm', 'e'], ['v', 'o', 'l'], ['m', 'e', 'n'], ['t', 'e']] +<table border='1'> +<tr><th>Variable</th><th>Value</th></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +<tr><td>a</td><td>1</td></tr> +</table> diff --git a/pypers/bolzano/db/mysql/user_passwd_db.py b/pypers/bolzano/db/mysql/user_passwd_db.py new file mode 100755 index 0000000..4493b7e --- /dev/null +++ b/pypers/bolzano/db/mysql/user_passwd_db.py @@ -0,0 +1,36 @@ +"""Interface to a Username/Password database implemented via MySQL.""" + +import MySQLdb + +class ErrorAlreadyExistingUser(Exception): + pass + +def create_users_db(): + cx = MySQLdb.connect() + cu = cx.cursor() + cu.execute("create database if not exists site_db;") + cu.execute("use site_db;") + cu.execute("""create table if not exists site_users + (username varchar(10), password varchar(10));""") + return cx + +def valid_user(cu, username, password): + return cu.execute("""select * from site_users where username=%r and + password=%r;""" % (username, password)) + +def already_exists(cu, username): + return cu.execute("select * from site_users where username=%r;" % username) + +def add_user_passwd(cu, username, password): + if already_exists(cu, username): + raise ErrorAlreadyExistingUser("This username is already taken!") + cu.execute("insert into site_users values (%r, %r);" % ( + username, password)) + + +if __name__ == "__main__": + cx = create_users_db() + cu = cx.cursor() + add_user_passwd(cu, "simona", "simona") + cx.close() + diff --git a/pypers/bolzano/db/mysql/website.py b/pypers/bolzano/db/mysql/website.py new file mode 100755 index 0000000..9044207 --- /dev/null +++ b/pypers/bolzano/db/mysql/website.py @@ -0,0 +1,59 @@ +import MySQLdb +from quixote_utils import RootDirectory, MultipageTable +from ui.HTMLTable import HTMLTable +from quixote.html import htmltext +from cycle import Cycle, chop +from quixote.form.form import Form +import quixote.form.widget as w +from quixote_utils import RootDirectory, htmltext +from stat_books_OO import BookPlotter + +def getfields(cu, tablename): + cu.execute("describe %s;" % tablename) + return [tupl[0] for tupl in cu.fetchall()] + +class Archive(RootDirectory): + _q_exports = ["show_books", "show_table", "show_histo", "select_histo"] + + def __init__(self, db): + self.cx = MySQLdb.connect(db=db) + self.plotter = BookPlotter(self.cx) + + def _q_index(self): + return "Archivio libri" + + def show_books(self): + cu = self.cx.cursor() + hits = cu.execute("select * from books;") + self.table = HTMLTable(cu.fetchall(), + header=getfields(cu, "books")) + return """Found %s hits. + Click <a href='show_table'>here</a> to see the results.""" % hits + + def show_table(self): + form = Form() + form.add(w.SubmitWidget, "prev", "prev") + form.add(w.SubmitWidget, "next", "next") + if form.is_submitted(): + if form["prev"]: + self.table.cycle.prev() + elif form["next"]: + self.table.cycle.next() + return htmltext(self.table.render()) + form.render() + + def select_histo(self): + form = Form() + form.add(w.SingleSelectWidget, "kind", options=["genre", "nation"]) + form.add(w.SubmitWidget, "submit", "Choose!") + if form.is_submitted(): + return self.show_histo(form["kind"]) + else: + return form.render() + + def show_histo(self, kind="genre"): + self.plotter.plot(kind, kind + ".dat") + return """<h1>Histogram by %s</h1> + <img src='file://%s'> + """ % (kind, self.plotter.imagefile) + +Archive("books").publish_show("select_histo") diff --git a/pypers/bolzano/db/mysql/x.html b/pypers/bolzano/db/mysql/x.html new file mode 100755 index 0000000..4a29f1c --- /dev/null +++ b/pypers/bolzano/db/mysql/x.html @@ -0,0 +1,2 @@ +<h1>Histogram by genre</h1> + <img src='genre.png'> diff --git a/pypers/bolzano/db/nomi.txt b/pypers/bolzano/db/nomi.txt new file mode 100755 index 0000000..2add17e --- /dev/null +++ b/pypers/bolzano/db/nomi.txt @@ -0,0 +1,4 @@ +Michele Simionato 0699XXXXX +Antonio Russo 333XXXXXX +Pinco Pallino 347XXXXXX + diff --git a/pypers/bolzano/db/populate_db.py b/pypers/bolzano/db/populate_db.py new file mode 100755 index 0000000..bb0753e --- /dev/null +++ b/pypers/bolzano/db/populate_db.py @@ -0,0 +1,4 @@ +from bookdb import BookDatabase +bd = BookDatabase("books") +bd.add_from_file("books87.txt") +bd.close() diff --git a/pypers/bolzano/db/quixote_utils.py b/pypers/bolzano/db/quixote_utils.py new file mode 100755 index 0000000..8614109 --- /dev/null +++ b/pypers/bolzano/db/quixote_utils.py @@ -0,0 +1,185 @@ +import os, sys, time, webbrowser +from quixote.directory import Directory +from quixote.publish import Publisher +from quixote.session import Session, SessionManager +from quixote.server import simple_server +from quixote.errors import AccessError +from quixote import get_response, get_user +from quixote.html import href + +elinks = webbrowser.GenericBrowser('xterm -e elinks %s') +lynx = webbrowser.GenericBrowser('xterm -e lynx -accept_all_cookies %s') +webbrowser.register("elinks", webbrowser.GenericBrowser, elinks) +webbrowser.register("lynx", webbrowser.GenericBrowser, lynx) # second choice +webbrowser.register("konqueror", webbrowser.Konqueror) + +class RecognizeExports(type): + def __init__(cls, name, bases, dic): + super(RecognizeExports, cls).__init__(cls, name, bases, dic) + for k in dic: setattr(cls, k, dic[k]) + def __setattr__(cls, name, value): + if hasattr(value, "_q_exported"): + cls._q_exports.append(name) + super(RecognizeExports, cls).__setattr__(name, value) + +# by definition, the root directory is a singleton +class RootDirectory(Directory): + _q_exports = [""] + __metaclass__ = RecognizeExports + __Publisher = Publisher + __port = 7080 + + def _q_index(self): + return "Welcome to the root of your application." + + def __init__(self, server=simple_server, Publisher=Publisher, + Session=Session, session_mapping=None, port=7080): + self.__server = server + self.__Publisher = Publisher + self.__Session = Session + self.__session_mapping = session_mapping + self.__port = port + + #set_default == __init__ + + def publish(self): + create_pub = lambda : self.__Publisher(self) + self.__server.run(create_pub, '', self.__port) + + def publish_show(self, page="", browser="mozilla"): + if os.fork(): # parent + self.publish() + else: # child + webbrowser.get(browser).open( + "http://localhost:%s/%s" % (self.__port, page)) + + +class UnauthorizedError(AccessError): + """The request requires user authentication. + + This subclass of AccessError sends a 401 instead of a 403, + hinting that the client should try again with authentication. + """ + status_code = 401 + title = "Unauthorized" + description = "You are not authorized to access this resource." + + def __init__(self, realm='Protected', public_msg=None, private_msg=None): + self.realm = realm + AccessError.__init__(self, public_msg, private_msg) + + def format(self): + get_response().set_header( + 'WWW-Authenticate', 'Basic realm="%s"' % self.realm) + return AccessError.format(self) + + +class User(object): + def __init__(self, username, password): + self.username = username + self.password = password + def __str__(self): + return "<User: %s %s>" % (self.username, self.password) + def permissions(self): + """Returns the list of methods starting with 'can_'.""" + return [perm for perm in dir(self) if perm.startswith("can_")] + +def public(f): + f._q_exported = True + return f + +class private(object): + """Redirect to the login page if the user is not logged in or if he does + not have the right permissions.""" + # obviously, this assumes a login page exists and is called 'login' + def __init__(self, *groups_with_access): + self.valid_groups = groups_with_access or (User,) + def __call__(self, method): + def wrapper(root): + user = get_user() + if not user or not isinstance(user, self.valid_groups): + root.resume = meth_name + valid_groups = ", ".join( + cls.__name__ for cls in self.valid_groups) + return "You are trying to access a page restricted to %s. " % \ + valid_groups + href( + "login", "Please login as a valid user.") + else: + return method(root) + meth_name = method.func_name + wrapper.func_name = meth_name + wrapper._q_exported = True + return wrapper + +######################## deprecated ############################ + +def old_public(f): + """Append f.__name__ to the caller's _q_exports. If the caller has + no _q_exports, creates it.""" + _q_exports = sys._getframe(1).f_locals.setdefault("_q_exports",[""]) + _q_exports.append(f.__name__) + return f + +class old_private(object): + """Redirect to the login page if the user is not logged in or if he does + not have the right permissions.""" + # obviously, this assumes a login page exists and is called 'login' + def __init__(self, *groups_with_access): + self.valid_groups = groups_with_access or (User,) + def __call__(self, method): + def wrapper(root): + user = get_user() + if not user or not isinstance(user, self.valid_groups): + root.resume = meth_name + valid_groups = ", ".join(cls.__name__ for cls in self.valid_groups) + return "You are trying to access a page restricted to %s. " % \ + valid_groups + href("login", "Please login as a valid user.") + else: + return method(root) + meth_name = method.func_name + _q_exports = sys._getframe(1).f_locals.setdefault("_q_exports",[""]) + _q_exports.append(meth_name) + wrapper.func_name = meth_name + return wrapper + +from ms.iter_utils import Cycle, chop + +class MultipageTable(object): + # use Quixote forms + def __init__(self, body, header=[], maxsize=20): + self.header = header + self.maxsize = maxsize + self.section = Cycle(chop(body, maxsize)) + self.sect = self.section[0] # default + self.ismultipage = len(self.section) > 1 + + def makerow(self, row, header=False): + if header: + r = " ".join("<th>%s</th>" % col for col in row) + else: + r = " ".join("<td>%s</td>" % col for col in row) + return "<tr>%s</tr>" % r + + def maketable(self): + #yield "<div align='center'>" + if self.ismultipage: + form = Form() + form.add(SubmitWidget, "prev", "Prev") + form.add(SubmitWidget, "next", "Next") + if form["next"]: # is submitted + self.sect = self.section.next() + if form["prev"]: # is submitted + self.sect = self.section.prev() + yield "Page #%s of %s" % (self.section.index+1, len(self.section)) + yield "<table border='1'>" + if self.header: + yield self.makerow(self.header) + for row in self.sect: + yield self.makerow(row) + yield "</table>" + if self.ismultipage: + yield form.render() + #yield "</div>" + + def render(self): + return htmltext("\n").join(map(htmltext, self.maketable())) diff --git a/pypers/bolzano/db/readbooks.py b/pypers/bolzano/db/readbooks.py new file mode 100755 index 0000000..bf5ec16 --- /dev/null +++ b/pypers/bolzano/db/readbooks.py @@ -0,0 +1,36 @@ +class Book(object): + title_span = 0, 33 + rate_span = 33, 38 + author_span = 38, 51 + date_span = 51, 61 + genre_span = 61, 65 + nation_span = 65, 67 + + def __init__(self, title, rate, author, date, genre, nation): + self.title = title + self.rate = rate + self.author = author + self.date = date + self.genre = genre + self.nation = nation + + def __repr__(self): + return self.title + self.rate + self.author + self.date + \ + self.genre + self.nation + +class Library(object): + def __init__(self): + self.books = [] + def read(self, fname): + for line in file(fname): + title = line.__getslice__(*Book.title_span) + rate = line.__getslice__(*Book.rate_span) + author = line.__getslice__(*Book.author_span) + date = line.__getslice__(*Book.date_span) + genre = line.__getslice__(*Book.genre_span) + nation = line.__getslice__(*Book.nation_span) + self.books.append(Book(title, rate, author, date, genre, nation)) + +lib = Library() +lib.read("books87.txt") + diff --git a/pypers/bolzano/db/simpledb.py b/pypers/bolzano/db/simpledb.py new file mode 100755 index 0000000..3ebe760 --- /dev/null +++ b/pypers/bolzano/db/simpledb.py @@ -0,0 +1,71 @@ +import os, shelve + +from Tkinter import * +from Tkconstants import * + +class NameNumber(Frame): + def __init__(self, db, name, number, row, **kw): + Frame.__init__(self, db.root, **kw) + self.namelabel = Entry(db.root) + self.phonelabel = Entry(db.root) + + def delete_key(name=name): db.del_data(name) + + self.deletebutton = Button(db.root, text="del", command=delete_key) + self.namelabel.insert(END, name) + self.phonelabel.insert(END, number) + self.namelabel.grid(row=row, column=0) + self.phonelabel.grid(row=row, column=1) + self.deletebutton.grid(row=row, column=2) + +class SimpleDatabase(object): + def __init__(self): + self.root = Tk() + def read_data(self, datafile): + self.phone = shelve.open(datafile) + def read_text(self, datafile): + self.phone = shelve.open(datafile[:-4]) + for line in file(datafile): + if not line.strip(): continue + name, number = line[:18].strip(), line[18:-1] + self.phone[name] = number + def change_data(self, key): + pass + def add_data(self, key): + pass + def del_data(self, key): + del self.phone[key] + i = self.entrydict[key] + del self.entrywidget[i] + + def commit(self): + for entry in self.entrywidget: + name = entry.namelabel.get() + number = entry.phonelabel.get() + self.phone[name] = number + self.phone.sync() + print "Committed!" + + def show_data(self): + row = 0 + self.entrywidget = [] + self.entrydict = {} + for name in self.phone: + namenumber = NameNumber(self, name, self.phone[name], row) + namenumber.grid() + self.entrywidget.append(namenumber) + self.entrydict[name]=row + row += 1 + + self.commit_button = Button( + self.root, + text = "Commit", + command = self.commit) + self.commit_button.grid() + +if __name__ == "__main__": + phonebook = SimpleDatabase() + # phonebook.read_text("nomi.txt") + phonebook.read_data("nomi") + phonebook.show_data() + phonebook.root.mainloop() diff --git a/pypers/bolzano/db/sqlbooks.py b/pypers/bolzano/db/sqlbooks.py new file mode 100755 index 0000000..215aebe --- /dev/null +++ b/pypers/bolzano/db/sqlbooks.py @@ -0,0 +1,30 @@ +""" +Add into the books database a books table generated from text files. +""" + +def book_from(filename): + for id, line in enumerate(file(filename)): + title = line[0:33].strip() + score = line[33:38].strip() + author = line[38:51].strip() + dd, mm, aa = line[51:61].strip().split("-") + genre = line[61:65].strip() + nation = line[65:67] + if "87" <= aa <= "99": + aaaa = "19" + aa + else: + aaaa = "20" + aa + date = "-".join([aaaa, mm, dd]) + yield id + 1, title, score, author, date, genre, nation + +def db_from_file(fname): + print "CREATE DATABASE IF NOT EXISTS books; use books;" + print """CREATE TABLE IF NOT EXISTS books + (id SMALLINT(3) NOT NULL, title VARCHAR(30), score CHAR(4), + author VARCHAR(20), date CHAR(10), genre CHAR(2), nation char(2), + PRIMARY KEY (id));""" + print "INSERT INTO books VALUES %s" % ",".join( + [str(vals) for vals in book_from(fname)]) + +if __name__ == "__main__": + db_from_file("books87.txt") diff --git a/pypers/bolzano/db/sqlreader.py b/pypers/bolzano/db/sqlreader.py new file mode 100755 index 0000000..8d373dc --- /dev/null +++ b/pypers/bolzano/db/sqlreader.py @@ -0,0 +1,10 @@ +import MySQLdb as m + +conn = m.connect() +c = conn.cursor() +print dir(c) +print c.execute("use books;") +print c.execute("select * from books;") +print c.fetchone() +print c.fetchmany(3) +print c.fetchall() diff --git a/pypers/bolzano/gui/canvas.py b/pypers/bolzano/gui/canvas.py new file mode 100755 index 0000000..ffb89f3 --- /dev/null +++ b/pypers/bolzano/gui/canvas.py @@ -0,0 +1,18 @@ +from Tkinter import * + +def on_click(event): + print event + print event.x, event.y + +root = Tk() + +c = Canvas() + +c.config(background="red", selectforeground="green") +c.create_rectangle(0, 0, 100, 100) +c.create_line(0, 0, 10, 100, 200, 300) + +c.bind("<Button-1>", on_click) +c.pack() + +mainloop() diff --git a/pypers/bolzano/gui/canvas2.py b/pypers/bolzano/gui/canvas2.py new file mode 100755 index 0000000..c10b476 --- /dev/null +++ b/pypers/bolzano/gui/canvas2.py @@ -0,0 +1,19 @@ +from Tkinter import * + +def on_keypress(event): + print dir(event) + + +root = Tk() + +c = Canvas(takefocus=1) + +c.config(background="red", selectforeground="green") +c.create_rectangle(0, 0, 100, 100) +c.create_line(0, 0, 10, 100, 200, 300) + +c.bind("<KeyPress>", on_keypress) +c.focus() +c.pack() + +mainloop() diff --git a/pypers/bolzano/gui/keys.py b/pypers/bolzano/gui/keys.py new file mode 100755 index 0000000..bc1d9de --- /dev/null +++ b/pypers/bolzano/gui/keys.py @@ -0,0 +1,15 @@ +from Tkinter import * + +class Output(Label): + def printkey(self, event): + self.config(text=event.keysym) + +root = Tk() +label = Label(root, text='Press a key...') +output = Output(root, takefocus=1) +label.pack() +output.pack() +output.focus() +output.bind('<KeyPress>', output.printkey) +root.mainloop() + diff --git a/pypers/bolzano/gui/menus.py b/pypers/bolzano/gui/menus.py new file mode 100755 index 0000000..dc10596 --- /dev/null +++ b/pypers/bolzano/gui/menus.py @@ -0,0 +1,33 @@ +from Tkinter import * + +root = Tk() + +def hello(): + print "hello!" + +menubar = Menu(root) + +# create a pulldown menu, and add it to the menu bar +filemenu = Menu(menubar, tearoff=0) + +filemenu.add_command(label="Open", command=hello) +filemenu.add_command(label="Save", command=hello) +filemenu.add_separator() +filemenu.add_command(label="Exit", command=root.quit) +menubar.add_cascade(label="File", menu=filemenu) + +# create more pulldown menus +editmenu = Menu(menubar, tearoff=0) +editmenu.add_command(label="Cut", command=hello) +editmenu.add_command(label="Copy", command=hello) +editmenu.add_command(label="Paste", command=hello) +menubar.add_cascade(label="Edit", menu=editmenu) + +helpmenu = Menu(menubar, tearoff=0) +helpmenu.add_command(label="About", command=hello) +menubar.add_cascade(label="Help", menu=helpmenu) + +# display the menu +root.config(menu=menubar) + +mainloop() diff --git a/pypers/bolzano/gui/menus2.py b/pypers/bolzano/gui/menus2.py new file mode 100755 index 0000000..f1f660e --- /dev/null +++ b/pypers/bolzano/gui/menus2.py @@ -0,0 +1,23 @@ +from Tkinter import * + +root = Tk() + +def hello(): + print "hello!" + +# create a popup menu +menu = Menu(root, tearoff=0) +menu.add_command(label="Undo", command=hello) +menu.add_command(label="Redo", command=hello) + +# create a canvas +frame = Frame(root, width=512, height=512) +frame.pack() + +def popup(event): + menu.post(event.x_root, event.y_root) + +# attach popup to canvas +frame.bind("<Button-3>", popup) + +mainloop() diff --git a/pypers/bolzano/kirby_ex.py b/pypers/bolzano/kirby_ex.py new file mode 100755 index 0000000..4fa9893 --- /dev/null +++ b/pypers/bolzano/kirby_ex.py @@ -0,0 +1,5 @@ +from kirbybase import KirbyBase + +db = KirbyBase() +print db.select('/home/micheles/packages/KirbyBase-1.8/plane.tbl', + ['country','speed'],['USA','>400']) diff --git a/pypers/bolzano/links.html b/pypers/bolzano/links.html new file mode 100755 index 0000000..eee92cc --- /dev/null +++ b/pypers/bolzano/links.html @@ -0,0 +1,58 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> +<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> +<meta name="generator" content="Docutils 0.3.7: http://docutils.sourceforge.net/" /> +<title>RIFERIMENTI</title> +<link rel="stylesheet" href="default.css" type="text/css" /> +</head> +<body> +<div class="document" id="riferimenti"> +<h1 class="title">RIFERIMENTI</h1> +<div class="section" id="in-inglese"> +<h1><a name="in-inglese">In Inglese</a></h1> +<p>Home Page Ufficiale:: www.python.org +Newsgroup: groups-beta.google.com/group/comp.lang.python +Tutor:</p> +</div> +<div class="section" id="in-italiano"> +<h1><a name="in-italiano">In Italiano</a></h1> +<p>Home Page Ufficiale: www.python.it +Newsgroup: groups-beta.google.com/group/it.comp.lang.python</p> +</div> +<div class="section" id="libri-tutorials-in-rete"> +<h1><a name="libri-tutorials-in-rete">Libri/Tutorials in rete</a></h1> +<p>Tradotti in italiano in www.zonapython.it/doc/</p> +<blockquote> +<ul class="simple"> +<li>How to Think Like a Computer Scientist</li> +<li>Dive Into Python</li> +</ul> +</blockquote> +</div> +<div class="section" id="articoli-riviste"> +<h1><a name="articoli-riviste">Articoli/riviste</a></h1> +<ol class="arabic simple"> +<li>la rivista italiana di Python: www.pyj.it</li> +<li>IBMdeveloperWorks: www-130.ibm.com/developerworks/linux</li> +<li>O' Reilly On LAMP: www.onlamp.com</li> +</ol> +</div> +<div class="section" id="libri-cartacei"> +<h1><a name="libri-cartacei">Libri cartacei</a></h1> +<p>Due soli libri in Italiano:</p> +<ol class="arabic simple"> +<li>David Brueck, Stephan Tanner, Python 2.1 Tutto e oltre (Apogeo)</li> +<li>Mark Lutz, David Asher, Programmare con Python (Hoeply)</li> +</ol> +<p>Decine di libri in inglesi. Consigliati:</p> +<ol class="arabic simple"> +<li>Alex Martelli, Python in a Nushell (O' Reilly)</li> +<li>Alex Martelli, Python Cookbook (O' Reilly)</li> +<li>Mark Lutz, David Asher, Learning Python</li> +</ol> +</div> +</div> +</body> +</html> diff --git a/pypers/bolzano/links.tex b/pypers/bolzano/links.tex new file mode 100755 index 0000000..cac4cb1 --- /dev/null +++ b/pypers/bolzano/links.tex @@ -0,0 +1,176 @@ +\documentclass[10pt,a4paper,english]{article} +\usepackage{babel} +\usepackage{ae} +\usepackage{aeguill} +\usepackage{shortvrb} +\usepackage[latin1]{inputenc} +\usepackage{tabularx} +\usepackage{longtable} +\setlength{\extrarowheight}{2pt} +\usepackage{amsmath} +\usepackage{graphicx} +\usepackage{color} +\usepackage{multirow} +\usepackage{ifthen} +\usepackage[colorlinks=true,linkcolor=blue,urlcolor=blue]{hyperref} +\usepackage[DIV12]{typearea} +%% generator Docutils: http://docutils.sourceforge.net/ +\newlength{\admonitionwidth} +\setlength{\admonitionwidth}{0.9\textwidth} +\newlength{\docinfowidth} +\setlength{\docinfowidth}{0.9\textwidth} +\newlength{\locallinewidth} +\newcommand{\optionlistlabel}[1]{\bf #1 \hfill} +\newenvironment{optionlist}[1] +{\begin{list}{} + {\setlength{\labelwidth}{#1} + \setlength{\rightmargin}{1cm} + \setlength{\leftmargin}{\rightmargin} + \addtolength{\leftmargin}{\labelwidth} + \addtolength{\leftmargin}{\labelsep} + \renewcommand{\makelabel}{\optionlistlabel}} +}{\end{list}} +\newlength{\lineblockindentation} +\setlength{\lineblockindentation}{2.5em} +\newenvironment{lineblock}[1] +{\begin{list}{} + {\setlength{\partopsep}{\parskip} + \addtolength{\partopsep}{\baselineskip} + \topsep0pt\itemsep0.15\baselineskip\parsep0pt + \leftmargin#1} + \raggedright} +{\end{list}} +% begin: floats for footnotes tweaking. +\setlength{\floatsep}{0.5em} +\setlength{\textfloatsep}{\fill} +\addtolength{\textfloatsep}{3em} +\renewcommand{\textfraction}{0.5} +\renewcommand{\topfraction}{0.5} +\renewcommand{\bottomfraction}{0.5} +\setcounter{totalnumber}{50} +\setcounter{topnumber}{50} +\setcounter{bottomnumber}{50} +% end floats for footnotes +% some commands, that could be overwritten in the style file. +\newcommand{\rubric}[1]{\subsection*{~\hfill {\it #1} \hfill ~}} +\newcommand{\titlereference}[1]{\textsl{#1}} +% end of "some commands" +\input{style.tex} +\title{RIFERIMENTI} +\author{} +\date{} +\hypersetup{ +pdftitle={RIFERIMENTI} +} +\raggedbottom +\begin{document} +\maketitle + + +\setlength{\locallinewidth}{\linewidth} + + +%___________________________________________________________________________ + +\hypertarget{in-inglese}{} +\pdfbookmark[0]{In Inglese}{in-inglese} +\section*{In Inglese} + +Home Page Ufficiale:: www.python.org +Newsgroup: groups-beta.google.com/group/comp.lang.python +Tutor: + + +%___________________________________________________________________________ + +\hypertarget{in-italiano}{} +\pdfbookmark[0]{In Italiano}{in-italiano} +\section*{In Italiano} + +Home Page Ufficiale: www.python.it +Newsgroup: groups-beta.google.com/group/it.comp.lang.python + + +%___________________________________________________________________________ + +\hypertarget{libri-tutorials-in-rete}{} +\pdfbookmark[0]{Libri/Tutorials in rete}{libri-tutorials-in-rete} +\section*{Libri/Tutorials in rete} + +Tradotti in italiano in www.zonapython.it/doc/ +\begin{quote} +\begin{itemize} +\item {} +How to Think Like a Computer Scientist + +\item {} +Dive Into Python + +\end{itemize} +\end{quote} + + +%___________________________________________________________________________ + +\hypertarget{articoli-riviste}{} +\pdfbookmark[0]{Articoli/riviste}{articoli-riviste} +\section*{Articoli/riviste} +\newcounter{listcnt1} +\begin{list}{\arabic{listcnt1}.} +{ +\usecounter{listcnt1} +\setlength{\rightmargin}{\leftmargin} +} +\item {} +la rivista italiana di Python: www.pyj.it + +\item {} +IBMdeveloperWorks: www-130.ibm.com/developerworks/linux + +\item {} +O' Reilly On LAMP: www.onlamp.com + +\end{list} + + +%___________________________________________________________________________ + +\hypertarget{libri-cartacei}{} +\pdfbookmark[0]{Libri cartacei}{libri-cartacei} +\section*{Libri cartacei} + +Due soli libri in Italiano: +\newcounter{listcnt2} +\begin{list}{\arabic{listcnt2}.} +{ +\usecounter{listcnt2} +\setlength{\rightmargin}{\leftmargin} +} +\item {} +David Brueck, Stephan Tanner, Python 2.1 Tutto e oltre (Apogeo) + +\item {} +Mark Lutz, David Asher, Programmare con Python (Hoeply) + +\end{list} + +Decine di libri in inglesi. Consigliati: +\newcounter{listcnt3} +\begin{list}{\arabic{listcnt3}.} +{ +\usecounter{listcnt3} +\setlength{\rightmargin}{\leftmargin} +} +\item {} +Alex Martelli, Python in a Nushell (O' Reilly) + +\item {} +Alex Martelli, Python Cookbook (O' Reilly) + +\item {} +Mark Lutz, David Asher, Learning Python + +\end{list} + +\end{document} + diff --git a/pypers/bolzano/links.txt b/pypers/bolzano/links.txt new file mode 100755 index 0000000..ce520bf --- /dev/null +++ b/pypers/bolzano/links.txt @@ -0,0 +1,44 @@ +RIFERIMENTI +=========== + +In Inglese +---------------------------- + +Home Page Ufficiale:: www.python.org +Newsgroup: groups-beta.google.com/group/comp.lang.python +Tutor: + +In Italiano +------------------------------- + +Home Page Ufficiale: www.python.it +Newsgroup: groups-beta.google.com/group/it.comp.lang.python + +Libri/Tutorials in rete +------------------------ + +Tradotti in italiano in www.zonapython.it/doc/ + + - How to Think Like a Computer Scientist + - Dive Into Python + +Articoli/riviste +----------------------- + +1. la rivista italiana di Python: www.pyj.it +2. IBMdeveloperWorks: www-130.ibm.com/developerworks/linux +3. O' Reilly On LAMP: www.onlamp.com + +Libri cartacei +------------------ + +Due soli libri in Italiano: + +1. David Brueck, Stephan Tanner, Python 2.1 Tutto e oltre (Apogeo) +2. Mark Lutz, David Asher, Programmare con Python (Hoeply) + +Decine di libri in inglesi. Consigliati: + +1. Alex Martelli, Python in a Nushell (O' Reilly) +2. Alex Martelli, Python Cookbook (O' Reilly) +3. Mark Lutz, David Asher, Learning Python diff --git a/pypers/bolzano/player/LabelWithImages.py b/pypers/bolzano/player/LabelWithImages.py new file mode 100755 index 0000000..a4c740a --- /dev/null +++ b/pypers/bolzano/player/LabelWithImages.py @@ -0,0 +1,14 @@ +from Tkinter import * +from itertools import cycle + +class LabelWithImages(Label): + + def __init__(self, master, images, **kw): + Label.__init__(self, master, **kw) + self.images = cycle(images) + + def start_animation(self): + self.config(image = self.images.next()) + self.after(2000, self.start_animation) + + diff --git a/pypers/bolzano/player/animated_text1.py b/pypers/bolzano/player/animated_text1.py new file mode 100755 index 0000000..cfc8b1e --- /dev/null +++ b/pypers/bolzano/player/animated_text1.py @@ -0,0 +1,33 @@ +from Tkinter import * +word = "Anime" +DELTA_T = 100 + +class Spacer(object): + nspaces = 0 + action = "increment" + MAXSPACES = 10 + def manage_spaces(self): + if self.action == "increment": + self.nspaces += 1 + elif self.action == "decrement": + self.nspaces -= 1 + if self.nspaces > self.MAXSPACES: + self.action = "decrement" + if self.nspaces < 0: + self.action = "increment" + return " " * self.nspaces + +spacer = Spacer() + +def make_animation(label): + spaces = spacer.manage_spaces() + centered_word = spaces.join(word).center(50) + label.config(text=centered_word) + root.after(DELTA_T, make_animation, label) + +if __name__ == "__main__": + root = Tk() + lab = Label(root) + lab.pack() + root.after(DELTA_T, make_animation, lab) + root.mainloop() diff --git a/pypers/bolzano/player/animated_text2.py b/pypers/bolzano/player/animated_text2.py new file mode 100755 index 0000000..5743a70 --- /dev/null +++ b/pypers/bolzano/player/animated_text2.py @@ -0,0 +1,38 @@ +from Tkinter import * + +class Spacer(object): + nspaces = 0 + action = "increment" + MAXSPACES = 10 + def manage_spaces(self): + if self.action == "increment": + self.nspaces += 1 + elif self.action == "decrement": + self.nspaces -= 1 + if self.nspaces > self.MAXSPACES: + self.action = "decrement" + if self.nspaces < 0: + self.action = "increment" + return " " * self.nspaces + +spacer = Spacer() + +class AnimatedLabel(Label): + DELTA_T = 100 + def __init__(self, master, **kw): + Label.__init__(self, master, **kw) + self.master = master + self.word = self.cget("text") + + def start_animation(self): + spaces = spacer.manage_spaces() + centered_word = spaces.join(self.word).center(50) + self.config(text=centered_word) + self.master.after(self.DELTA_T, self.start_animation) + +if __name__ == "__main__": + root = Tk() + lab = AnimatedLabel(root, text="Anime") + lab.pack() + lab.start_animation() + root.mainloop() diff --git a/pypers/bolzano/player/animeplayer.py b/pypers/bolzano/player/animeplayer.py new file mode 100755 index 0000000..321036b --- /dev/null +++ b/pypers/bolzano/player/animeplayer.py @@ -0,0 +1,40 @@ +import os +from Tkinter import * +from Tkconstants import * +from animated_text2 import AnimatedLabel +from LabelWithImages import LabelWithImages +from musicbox import Musicbox, ScrollableMusicbox + +def get_photoimages(directory): + for fname in os.listdir(directory): + if fname.endswith(".gif"): + yield PhotoImage(file=fname) + + +root = Tk() +label = LabelWithImages(root, + images = get_photoimages("."), + height = 100) +label.start_animation() +label.pack() + +a1 = AnimatedLabel(root, text = "Anime", fg="red") +a2 = AnimatedLabel(root, text = "Music", fg="green") +a1.pack() +a2.pack() + +a1.start_animation() +a2.start_animation() +musicbox = Musicbox( + root, [f for f in os.listdir(".") if f.endswith(".mp3")]) +musicframe = ScrollableMusicbox(root, musicbox) + +musicframe.pack() + +exit_label = Label(text = "Click here to exit") +exit_label.bind("<Button-1>", lambda e: musicbox.quit()) +exit_label.pack(side=BOTTOM) + +root.protocol("WM_DELETE_WINDOW", musicbox.quit) +root.mainloop() + diff --git a/pypers/bolzano/player/bind_example.py b/pypers/bolzano/player/bind_example.py new file mode 100755 index 0000000..73d0dfe --- /dev/null +++ b/pypers/bolzano/player/bind_example.py @@ -0,0 +1,15 @@ +from Tkinter import * + +root = Tk() + +def callback(event): + print "clicked at", event.x, event.y + +def quit(event): + root.quit() + +lab = Label(root, bg="red") +lab.bind("<1>", quit) +lab.pack() + +root.mainloop() diff --git a/pypers/bolzano/player/call_mpg123.py b/pypers/bolzano/player/call_mpg123.py new file mode 100755 index 0000000..c06b4b0 --- /dev/null +++ b/pypers/bolzano/player/call_mpg123.py @@ -0,0 +1,6 @@ +import os, time +from subprocess import Popen + +def play(fname): + player = Popen(["/usr/bin/mpg123", fname]) + return player.pid diff --git a/pypers/bolzano/player/change_spacing.py b/pypers/bolzano/player/change_spacing.py new file mode 100755 index 0000000..38e4ad7 --- /dev/null +++ b/pypers/bolzano/player/change_spacing.py @@ -0,0 +1,12 @@ +word = "Anime" + +for n in range(3): + spaces = " " * n + print spaces.join(word) + +for n in range(3)[::-1]: + spaces = " " * n + print spaces.join(word) + +print range(3) +print range(3)[::-1] diff --git a/pypers/bolzano/player/clickable_label.py b/pypers/bolzano/player/clickable_label.py new file mode 100755 index 0000000..efb0d1d --- /dev/null +++ b/pypers/bolzano/player/clickable_label.py @@ -0,0 +1,12 @@ +from Tkinter import * + +class ClickableLabel(Label): + def __init__(self, master, **kw): + Label.__init__(self, master, **kw) + self.bind('<Button-1>', lambda e : self.quit()) + +if __name__ == "__main__": + root = Tk() + cl = ClickableLabel(root) + cl.pack() + root.mainloop() diff --git a/pypers/bolzano/player/cycle.py b/pypers/bolzano/player/cycle.py new file mode 100755 index 0000000..467746f --- /dev/null +++ b/pypers/bolzano/player/cycle.py @@ -0,0 +1,13 @@ +from itertools import cycle + +c = cycle("abcd") + +print c.next() + +print c.next() +print c.next() +print c.next() + +print c.next() + +print c.next() diff --git a/pypers/bolzano/player/global.py b/pypers/bolzano/player/global.py new file mode 100755 index 0000000..62e30ae --- /dev/null +++ b/pypers/bolzano/player/global.py @@ -0,0 +1,9 @@ +x = 0 + +def cambia_x(): + global x + x = 1 + + +cambia_x() +print x diff --git a/pypers/bolzano/player/kw.py b/pypers/bolzano/player/kw.py new file mode 100755 index 0000000..9c019ca --- /dev/null +++ b/pypers/bolzano/player/kw.py @@ -0,0 +1,6 @@ +def f(**kw): + print kw + +f(a="qualcosa", b="qualcos'altro", c="") + +Label(text="", bg="", colfff) diff --git a/pypers/bolzano/player/label.py b/pypers/bolzano/player/label.py new file mode 100755 index 0000000..f6616b5 --- /dev/null +++ b/pypers/bolzano/player/label.py @@ -0,0 +1,29 @@ +from Tkinter import * +from Tkconstants import * + +fg, bg = "red", "green" + +def simple_label(master): + mylabel = Label(master, text="ciao!", fg="red", font="Courier 36 bold", + bg="green") + mylabel.pack(side=LEFT) + +def flashing_label(master): + label = Label(master, text="ciao!", + foreground=fg, background=bg, + font="Courier 36 bold") + label.pack(side=RIGHT) + label.after(1000, flash, label) + +def flash(mylabel): + global fg, bg + fg, bg = bg, fg + mylabel.config(foreground=fg, background=bg) + mylabel.after(1000, flash, mylabel) + + +if __name__ == "__main__": + root = Tk() + simple_label(root) + flashing_label(root) + root.mainloop() diff --git a/pypers/bolzano/player/listbox.py b/pypers/bolzano/player/listbox.py new file mode 100755 index 0000000..4492884 --- /dev/null +++ b/pypers/bolzano/player/listbox.py @@ -0,0 +1,37 @@ +import os +from Tkinter import * +from call_mpg123 import play +from signal import SIGTERM + +mp3s = [f for f in os.listdir(".") if f.endswith(".mp3")] + +is_playing = False +pid = None + +def playsong(e): + global is_playing, pid + i = int(listbox.curselection()[0]) + if not is_playing: + is_playing = True + pid = play(mp3s[i]) + else: + os.kill(pid, SIGTERM) + is_playing = True + pid = play(mp3s[i]) + +def quit(): + master.quit() + if is_playing: + os.kill(pid, SIGTERM) + +master = Tk() +listbox = Listbox(master) + +for mp3 in mp3s: + listbox.insert('end', mp3) + +listbox.pack() +listbox.bind("<Double-Button-1>", playsong) + +master.protocol("WM_DELETE_WINDOW", quit) +master.mainloop() diff --git a/pypers/bolzano/player/musicbox.py b/pypers/bolzano/player/musicbox.py new file mode 100755 index 0000000..5eb7f8e --- /dev/null +++ b/pypers/bolzano/player/musicbox.py @@ -0,0 +1,53 @@ +import os +from Tkinter import * +from call_mpg123 import play +from signal import SIGTERM + +class Musicbox(Listbox): + + def __init__(self, master, mp3s, **kw): + Listbox.__init__(self, master, **kw) + self.master = master + self.mp3s = mp3s + for mp3 in mp3s: + self.insert("end", mp3) + self.is_playing = False + self.pid = None + self.bind("<Double-Button-1>", self.playsong) + + def playsong(self, e): + i = int(self.curselection()[0]) + if not self.is_playing: + self.is_playing = True + self.pid = play(self.mp3s[i]) + else: + os.kill(self.pid, SIGTERM) + self.is_playing = True + self.pid = play(self.mp3s[i]) + + def quit(self): + self.master.quit() + if self.is_playing: + os.kill(self.pid, SIGTERM) + +class ScrollableMusicbox(Frame): + def __init__(self, master, musicbox, **kw): + Frame.__init__(self, master, **kw) + self.master = master + self.musicbox = musicbox + self.scrollbar = Scrollbar(self) + self.scrollbar.config( + command=self.musicbox.yview) + self.musicbox.config( + yscrollcommand=self.scrollbar.set) + self.musicbox.pack(side=LEFT, fill=BOTH) + self.scrollbar.pack(side=RIGHT, fill=Y) + + +if __name__ == "__main__": + master = Tk() + musicbox = Musicbox(master, [f for f in os.listdir(".") + if f.endswith(".mp3")]) + musicbox.pack() + master.protocol("WM_DELETE_WINDOW", musicbox.quit) + master.mainloop() diff --git a/pypers/bolzano/player/scrollbar.py b/pypers/bolzano/player/scrollbar.py new file mode 100755 index 0000000..9500355 --- /dev/null +++ b/pypers/bolzano/player/scrollbar.py @@ -0,0 +1,17 @@ +from Tkinter import * + +root = Tk() + +scrollbar = Scrollbar(root) +scrollbar.pack(side=RIGHT, fill=Y) + +listbox = Listbox(root, yscrollcommand=scrollbar.set) + +for i in range(1000): + listbox.insert(END, str(i)) +listbox.pack(side=LEFT, fill=BOTH) + +scrollbar.config(command=listbox.yview) + +mainloop() + diff --git a/pypers/bolzano/player/subprocess.py b/pypers/bolzano/player/subprocess.py new file mode 100755 index 0000000..d115e87 --- /dev/null +++ b/pypers/bolzano/player/subprocess.py @@ -0,0 +1,1165 @@ +# subprocess - Subprocesses with accessible I/O streams +# +# For more information about this module, see PEP 324. +# +# Copyright (c) 2003-2004 by Peter Astrand <astrand@lysator.liu.se> +# +# By obtaining, using, and/or copying this software and/or its +# associated documentation, you agree that you have read, understood, +# and will comply with the following terms and conditions: +# +# Permission to use, copy, modify, and distribute this software and +# its associated documentation for any purpose and without fee is +# hereby granted, provided that the above copyright notice appears in +# all copies, and that both that copyright notice and this permission +# notice appear in supporting documentation, and that the name of the +# author not be used in advertising or publicity pertaining to +# distribution of the software without specific, written prior +# permission. +# +# THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR +# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, +# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION +# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +r"""subprocess - Subprocesses with accessible I/O streams + +This module allows you to spawn processes, connect to their +input/output/error pipes, and obtain their return codes. This module +intends to replace several other, older modules and functions, like: + +os.system +os.spawn* +os.popen* +popen2.* +commands.* + +Information about how the subprocess module can be used to replace these +modules and functions can be found below. + + + +Using the subprocess module +=========================== +This module defines one class called Popen: + +class Popen(args, bufsize=0, executable=None, + stdin=None, stdout=None, stderr=None, + preexec_fn=None, close_fds=False, shell=False, + cwd=None, env=None, universal_newlines=False, + startupinfo=None, creationflags=0): + + +Arguments are: + +args should be a string, or a sequence of program arguments. The +program to execute is normally the first item in the args sequence or +string, but can be explicitly set by using the executable argument. + +On UNIX, with shell=False (default): In this case, the Popen class +uses os.execvp() to execute the child program. args should normally +be a sequence. A string will be treated as a sequence with the string +as the only item (the program to execute). + +On UNIX, with shell=True: If args is a string, it specifies the +command string to execute through the shell. If args is a sequence, +the first item specifies the command string, and any additional items +will be treated as additional shell arguments. + +On Windows: the Popen class uses CreateProcess() to execute the child +program, which operates on strings. If args is a sequence, it will be +converted to a string using the list2cmdline method. Please note that +not all MS Windows applications interpret the command line the same +way: The list2cmdline is designed for applications using the same +rules as the MS C runtime. + +bufsize, if given, has the same meaning as the corresponding argument +to the built-in open() function: 0 means unbuffered, 1 means line +buffered, any other positive value means use a buffer of +(approximately) that size. A negative bufsize means to use the system +default, which usually means fully buffered. The default value for +bufsize is 0 (unbuffered). + +stdin, stdout and stderr specify the executed programs' standard +input, standard output and standard error file handles, respectively. +Valid values are PIPE, an existing file descriptor (a positive +integer), an existing file object, and None. PIPE indicates that a +new pipe to the child should be created. With None, no redirection +will occur; the child's file handles will be inherited from the +parent. Additionally, stderr can be STDOUT, which indicates that the +stderr data from the applications should be captured into the same +file handle as for stdout. + +If preexec_fn is set to a callable object, this object will be called +in the child process just before the child is executed. + +If close_fds is true, all file descriptors except 0, 1 and 2 will be +closed before the child process is executed. + +if shell is true, the specified command will be executed through the +shell. + +If cwd is not None, the current directory will be changed to cwd +before the child is executed. + +If env is not None, it defines the environment variables for the new +process. + +If universal_newlines is true, the file objects stdout and stderr are +opened as a text files, but lines may be terminated by any of '\n', +the Unix end-of-line convention, '\r', the Macintosh convention or +'\r\n', the Windows convention. All of these external representations +are seen as '\n' by the Python program. Note: This feature is only +available if Python is built with universal newline support (the +default). Also, the newlines attribute of the file objects stdout, +stdin and stderr are not updated by the communicate() method. + +The startupinfo and creationflags, if given, will be passed to the +underlying CreateProcess() function. They can specify things such as +appearance of the main window and priority for the new process. +(Windows only) + + +This module also defines two shortcut functions: + +call(*args, **kwargs): + Run command with arguments. Wait for command to complete, then + return the returncode attribute. + + The arguments are the same as for the Popen constructor. Example: + + retcode = call(["ls", "-l"]) + + +Exceptions +---------- +Exceptions raised in the child process, before the new program has +started to execute, will be re-raised in the parent. Additionally, +the exception object will have one extra attribute called +'child_traceback', which is a string containing traceback information +from the childs point of view. + +The most common exception raised is OSError. This occurs, for +example, when trying to execute a non-existent file. Applications +should prepare for OSErrors. + +A ValueError will be raised if Popen is called with invalid arguments. + + +Security +-------- +Unlike some other popen functions, this implementation will never call +/bin/sh implicitly. This means that all characters, including shell +metacharacters, can safely be passed to child processes. + + +Popen objects +============= +Instances of the Popen class have the following methods: + +poll() + Check if child process has terminated. Returns returncode + attribute. + +wait() + Wait for child process to terminate. Returns returncode attribute. + +communicate(input=None) + Interact with process: Send data to stdin. Read data from stdout + and stderr, until end-of-file is reached. Wait for process to + terminate. The optional stdin argument should be a string to be + sent to the child process, or None, if no data should be sent to + the child. + + communicate() returns a tuple (stdout, stderr). + + Note: The data read is buffered in memory, so do not use this + method if the data size is large or unlimited. + +The following attributes are also available: + +stdin + If the stdin argument is PIPE, this attribute is a file object + that provides input to the child process. Otherwise, it is None. + +stdout + If the stdout argument is PIPE, this attribute is a file object + that provides output from the child process. Otherwise, it is + None. + +stderr + If the stderr argument is PIPE, this attribute is file object that + provides error output from the child process. Otherwise, it is + None. + +pid + The process ID of the child process. + +returncode + The child return code. A None value indicates that the process + hasn't terminated yet. A negative value -N indicates that the + child was terminated by signal N (UNIX only). + + +Replacing older functions with the subprocess module +==================================================== +In this section, "a ==> b" means that b can be used as a replacement +for a. + +Note: All functions in this section fail (more or less) silently if +the executed program cannot be found; this module raises an OSError +exception. + +In the following examples, we assume that the subprocess module is +imported with "from subprocess import *". + + +Replacing /bin/sh shell backquote +--------------------------------- +output=`mycmd myarg` +==> +output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] + + +Replacing shell pipe line +------------------------- +output=`dmesg | grep hda` +==> +p1 = Popen(["dmesg"], stdout=PIPE) +p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) +output = p2.communicate()[0] + + +Replacing os.system() +--------------------- +sts = os.system("mycmd" + " myarg") +==> +p = Popen("mycmd" + " myarg", shell=True) +sts = os.waitpid(p.pid, 0) + +Note: + +* Calling the program through the shell is usually not required. + +* It's easier to look at the returncode attribute than the + exitstatus. + +A more real-world example would look like this: + +try: + retcode = call("mycmd" + " myarg", shell=True) + if retcode < 0: + print >>sys.stderr, "Child was terminated by signal", -retcode + else: + print >>sys.stderr, "Child returned", retcode +except OSError, e: + print >>sys.stderr, "Execution failed:", e + + +Replacing os.spawn* +------------------- +P_NOWAIT example: + +pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") +==> +pid = Popen(["/bin/mycmd", "myarg"]).pid + + +P_WAIT example: + +retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") +==> +retcode = call(["/bin/mycmd", "myarg"]) + + +Vector example: + +os.spawnvp(os.P_NOWAIT, path, args) +==> +Popen([path] + args[1:]) + + +Environment example: + +os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) +==> +Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) + + +Replacing os.popen* +------------------- +pipe = os.popen(cmd, mode='r', bufsize) +==> +pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout + +pipe = os.popen(cmd, mode='w', bufsize) +==> +pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin + + +(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize) +==> +p = Popen(cmd, shell=True, bufsize=bufsize, + stdin=PIPE, stdout=PIPE, close_fds=True) +(child_stdin, child_stdout) = (p.stdin, p.stdout) + + +(child_stdin, + child_stdout, + child_stderr) = os.popen3(cmd, mode, bufsize) +==> +p = Popen(cmd, shell=True, bufsize=bufsize, + stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) +(child_stdin, + child_stdout, + child_stderr) = (p.stdin, p.stdout, p.stderr) + + +(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize) +==> +p = Popen(cmd, shell=True, bufsize=bufsize, + stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) +(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) + + +Replacing popen2.* +------------------ +Note: If the cmd argument to popen2 functions is a string, the command +is executed through /bin/sh. If it is a list, the command is directly +executed. + +(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) +==> +p = Popen(["somestring"], shell=True, bufsize=bufsize + stdin=PIPE, stdout=PIPE, close_fds=True) +(child_stdout, child_stdin) = (p.stdout, p.stdin) + + +(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode) +==> +p = Popen(["mycmd", "myarg"], bufsize=bufsize, + stdin=PIPE, stdout=PIPE, close_fds=True) +(child_stdout, child_stdin) = (p.stdout, p.stdin) + +The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen, +except that: + +* subprocess.Popen raises an exception if the execution fails +* the capturestderr argument is replaced with the stderr argument. +* stdin=PIPE and stdout=PIPE must be specified. +* popen2 closes all filedescriptors by default, but you have to specify + close_fds=True with subprocess.Popen. + + +""" + +import sys +mswindows = (sys.platform == "win32") + +import os +import types +import traceback + +if mswindows: + import threading + import msvcrt + if 0: # <-- change this to use pywin32 instead of the _subprocess driver + import pywintypes + from win32api import GetStdHandle, STD_INPUT_HANDLE, \ + STD_OUTPUT_HANDLE, STD_ERROR_HANDLE + from win32api import GetCurrentProcess, DuplicateHandle, \ + GetModuleFileName, GetVersion + from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE + from win32pipe import CreatePipe + from win32process import CreateProcess, STARTUPINFO, \ + GetExitCodeProcess, STARTF_USESTDHANDLES, \ + STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE + from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0 + else: + from _subprocess import * + class STARTUPINFO: + dwFlags = 0 + hStdInput = None + hStdOutput = None + hStdError = None + class pywintypes: + error = IOError +else: + import select + import errno + import fcntl + import pickle + +__all__ = ["Popen", "PIPE", "STDOUT", "call"] + +try: + MAXFD = os.sysconf("SC_OPEN_MAX") +except: + MAXFD = 256 + +# True/False does not exist on 2.2.0 +try: + False +except NameError: + False = 0 + True = 1 + +_active = [] + +def _cleanup(): + for inst in _active[:]: + inst.poll() + +PIPE = -1 +STDOUT = -2 + + +def call(*args, **kwargs): + """Run command with arguments. Wait for command to complete, then + return the returncode attribute. + + The arguments are the same as for the Popen constructor. Example: + + retcode = call(["ls", "-l"]) + """ + return Popen(*args, **kwargs).wait() + + +def list2cmdline(seq): + """ + Translate a sequence of arguments into a command line + string, using the same rules as the MS C runtime: + + 1) Arguments are delimited by white space, which is either a + space or a tab. + + 2) A string surrounded by double quotation marks is + interpreted as a single argument, regardless of white space + contained within. A quoted string can be embedded in an + argument. + + 3) A double quotation mark preceded by a backslash is + interpreted as a literal double quotation mark. + + 4) Backslashes are interpreted literally, unless they + immediately precede a double quotation mark. + + 5) If backslashes immediately precede a double quotation mark, + every pair of backslashes is interpreted as a literal + backslash. If the number of backslashes is odd, the last + backslash escapes the next double quotation mark as + described in rule 3. + """ + + # See + # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp + result = [] + needquote = False + for arg in seq: + bs_buf = [] + + # Add a space to separate this argument from the others + if result: + result.append(' ') + + needquote = (" " in arg) or ("\t" in arg) + if needquote: + result.append('"') + + for c in arg: + if c == '\\': + # Don't know if we need to double yet. + bs_buf.append(c) + elif c == '"': + # Double backspaces. + result.append('\\' * len(bs_buf)*2) + bs_buf = [] + result.append('\\"') + else: + # Normal char + if bs_buf: + result.extend(bs_buf) + bs_buf = [] + result.append(c) + + # Add remaining backspaces, if any. + if bs_buf: + result.extend(bs_buf) + + if needquote: + result.extend(bs_buf) + result.append('"') + + return ''.join(result) + + +class Popen(object): + def __init__(self, args, bufsize=0, executable=None, + stdin=None, stdout=None, stderr=None, + preexec_fn=None, close_fds=False, shell=False, + cwd=None, env=None, universal_newlines=False, + startupinfo=None, creationflags=0): + """Create new Popen instance.""" + _cleanup() + + if not isinstance(bufsize, (int, long)): + raise TypeError("bufsize must be an integer") + + if mswindows: + if preexec_fn is not None: + raise ValueError("preexec_fn is not supported on Windows " + "platforms") + if close_fds: + raise ValueError("close_fds is not supported on Windows " + "platforms") + else: + # POSIX + if startupinfo is not None: + raise ValueError("startupinfo is only supported on Windows " + "platforms") + if creationflags != 0: + raise ValueError("creationflags is only supported on Windows " + "platforms") + + self.stdin = None + self.stdout = None + self.stderr = None + self.pid = None + self.returncode = None + self.universal_newlines = universal_newlines + + # Input and output objects. The general principle is like + # this: + # + # Parent Child + # ------ ----- + # p2cwrite ---stdin---> p2cread + # c2pread <--stdout--- c2pwrite + # errread <--stderr--- errwrite + # + # On POSIX, the child objects are file descriptors. On + # Windows, these are Windows file handles. The parent objects + # are file descriptors on both platforms. The parent objects + # are None when not using PIPEs. The child objects are None + # when not redirecting. + + (p2cread, p2cwrite, + c2pread, c2pwrite, + errread, errwrite) = self._get_handles(stdin, stdout, stderr) + + self._execute_child(args, executable, preexec_fn, close_fds, + cwd, env, universal_newlines, + startupinfo, creationflags, shell, + p2cread, p2cwrite, + c2pread, c2pwrite, + errread, errwrite) + + if p2cwrite: + self.stdin = os.fdopen(p2cwrite, 'wb', bufsize) + if c2pread: + if universal_newlines: + self.stdout = os.fdopen(c2pread, 'rU', bufsize) + else: + self.stdout = os.fdopen(c2pread, 'rb', bufsize) + if errread: + if universal_newlines: + self.stderr = os.fdopen(errread, 'rU', bufsize) + else: + self.stderr = os.fdopen(errread, 'rb', bufsize) + + _active.append(self) + + + def _translate_newlines(self, data): + data = data.replace("\r\n", "\n") + data = data.replace("\r", "\n") + return data + + + if mswindows: + # + # Windows methods + # + def _get_handles(self, stdin, stdout, stderr): + """Construct and return tupel with IO objects: + p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite + """ + if stdin == None and stdout == None and stderr == None: + return (None, None, None, None, None, None) + + p2cread, p2cwrite = None, None + c2pread, c2pwrite = None, None + errread, errwrite = None, None + + if stdin == None: + p2cread = GetStdHandle(STD_INPUT_HANDLE) + elif stdin == PIPE: + p2cread, p2cwrite = CreatePipe(None, 0) + # Detach and turn into fd + p2cwrite = p2cwrite.Detach() + p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0) + elif type(stdin) == types.IntType: + p2cread = msvcrt.get_osfhandle(stdin) + else: + # Assuming file-like object + p2cread = msvcrt.get_osfhandle(stdin.fileno()) + p2cread = self._make_inheritable(p2cread) + + if stdout == None: + c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE) + elif stdout == PIPE: + c2pread, c2pwrite = CreatePipe(None, 0) + # Detach and turn into fd + c2pread = c2pread.Detach() + c2pread = msvcrt.open_osfhandle(c2pread, 0) + elif type(stdout) == types.IntType: + c2pwrite = msvcrt.get_osfhandle(stdout) + else: + # Assuming file-like object + c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) + c2pwrite = self._make_inheritable(c2pwrite) + + if stderr == None: + errwrite = GetStdHandle(STD_ERROR_HANDLE) + elif stderr == PIPE: + errread, errwrite = CreatePipe(None, 0) + # Detach and turn into fd + errread = errread.Detach() + errread = msvcrt.open_osfhandle(errread, 0) + elif stderr == STDOUT: + errwrite = c2pwrite + elif type(stderr) == types.IntType: + errwrite = msvcrt.get_osfhandle(stderr) + else: + # Assuming file-like object + errwrite = msvcrt.get_osfhandle(stderr.fileno()) + errwrite = self._make_inheritable(errwrite) + + return (p2cread, p2cwrite, + c2pread, c2pwrite, + errread, errwrite) + + + def _make_inheritable(self, handle): + """Return a duplicate of handle, which is inheritable""" + return DuplicateHandle(GetCurrentProcess(), handle, + GetCurrentProcess(), 0, 1, + DUPLICATE_SAME_ACCESS) + + + def _find_w9xpopen(self): + """Find and return absolut path to w9xpopen.exe""" + w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), + "w9xpopen.exe") + if not os.path.exists(w9xpopen): + # Eeek - file-not-found - possibly an embedding + # situation - see if we can locate it in sys.exec_prefix + w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), + "w9xpopen.exe") + if not os.path.exists(w9xpopen): + raise RuntimeError("Cannot locate w9xpopen.exe, which is " + "needed for Popen to work with your " + "shell or platform.") + return w9xpopen + + + def _execute_child(self, args, executable, preexec_fn, close_fds, + cwd, env, universal_newlines, + startupinfo, creationflags, shell, + p2cread, p2cwrite, + c2pread, c2pwrite, + errread, errwrite): + """Execute program (MS Windows version)""" + + if not isinstance(args, types.StringTypes): + args = list2cmdline(args) + + # Process startup details + default_startupinfo = STARTUPINFO() + if startupinfo == None: + startupinfo = default_startupinfo + if not None in (p2cread, c2pwrite, errwrite): + startupinfo.dwFlags |= STARTF_USESTDHANDLES + startupinfo.hStdInput = p2cread + startupinfo.hStdOutput = c2pwrite + startupinfo.hStdError = errwrite + + if shell: + default_startupinfo.dwFlags |= STARTF_USESHOWWINDOW + default_startupinfo.wShowWindow = SW_HIDE + comspec = os.environ.get("COMSPEC", "cmd.exe") + args = comspec + " /c " + args + if (GetVersion() >= 0x80000000L or + os.path.basename(comspec).lower() == "command.com"): + # Win9x, or using command.com on NT. We need to + # use the w9xpopen intermediate program. For more + # information, see KB Q150956 + # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp) + w9xpopen = self._find_w9xpopen() + args = '"%s" %s' % (w9xpopen, args) + # Not passing CREATE_NEW_CONSOLE has been known to + # cause random failures on win9x. Specifically a + # dialog: "Your program accessed mem currently in + # use at xxx" and a hopeful warning about the + # stability of your system. Cost is Ctrl+C wont + # kill children. + creationflags |= CREATE_NEW_CONSOLE + + # Start the process + try: + hp, ht, pid, tid = CreateProcess(executable, args, + # no special security + None, None, + # must inherit handles to pass std + # handles + 1, + creationflags, + env, + cwd, + startupinfo) + except pywintypes.error, e: + # Translate pywintypes.error to WindowsError, which is + # a subclass of OSError. FIXME: We should really + # translate errno using _sys_errlist (or simliar), but + # how can this be done from Python? + raise WindowsError(*e.args) + + # Retain the process handle, but close the thread handle + self._handle = hp + self.pid = pid + ht.Close() + + # Child is launched. Close the parent's copy of those pipe + # handles that only the child should have open. You need + # to make sure that no handles to the write end of the + # output pipe are maintained in this process or else the + # pipe will not close when the child process exits and the + # ReadFile will hang. + if p2cread != None: + p2cread.Close() + if c2pwrite != None: + c2pwrite.Close() + if errwrite != None: + errwrite.Close() + + + def poll(self): + """Check if child process has terminated. Returns returncode + attribute.""" + if self.returncode == None: + if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0: + self.returncode = GetExitCodeProcess(self._handle) + _active.remove(self) + return self.returncode + + + def wait(self): + """Wait for child process to terminate. Returns returncode + attribute.""" + if self.returncode == None: + obj = WaitForSingleObject(self._handle, INFINITE) + self.returncode = GetExitCodeProcess(self._handle) + _active.remove(self) + return self.returncode + + + def _readerthread(self, fh, buffer): + buffer.append(fh.read()) + + + def communicate(self, input=None): + """Interact with process: Send data to stdin. Read data from + stdout and stderr, until end-of-file is reached. Wait for + process to terminate. The optional input argument should be a + string to be sent to the child process, or None, if no data + should be sent to the child. + + communicate() returns a tuple (stdout, stderr).""" + stdout = None # Return + stderr = None # Return + + if self.stdout: + stdout = [] + stdout_thread = threading.Thread(target=self._readerthread, + args=(self.stdout, stdout)) + stdout_thread.setDaemon(True) + stdout_thread.start() + if self.stderr: + stderr = [] + stderr_thread = threading.Thread(target=self._readerthread, + args=(self.stderr, stderr)) + stderr_thread.setDaemon(True) + stderr_thread.start() + + if self.stdin: + if input != None: + self.stdin.write(input) + self.stdin.close() + + if self.stdout: + stdout_thread.join() + if self.stderr: + stderr_thread.join() + + # All data exchanged. Translate lists into strings. + if stdout != None: + stdout = stdout[0] + if stderr != None: + stderr = stderr[0] + + # Translate newlines, if requested. We cannot let the file + # object do the translation: It is based on stdio, which is + # impossible to combine with select (unless forcing no + # buffering). + if self.universal_newlines and hasattr(open, 'newlines'): + if stdout: + stdout = self._translate_newlines(stdout) + if stderr: + stderr = self._translate_newlines(stderr) + + self.wait() + return (stdout, stderr) + + else: + # + # POSIX methods + # + def _get_handles(self, stdin, stdout, stderr): + """Construct and return tupel with IO objects: + p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite + """ + p2cread, p2cwrite = None, None + c2pread, c2pwrite = None, None + errread, errwrite = None, None + + if stdin == None: + pass + elif stdin == PIPE: + p2cread, p2cwrite = os.pipe() + elif type(stdin) == types.IntType: + p2cread = stdin + else: + # Assuming file-like object + p2cread = stdin.fileno() + + if stdout == None: + pass + elif stdout == PIPE: + c2pread, c2pwrite = os.pipe() + elif type(stdout) == types.IntType: + c2pwrite = stdout + else: + # Assuming file-like object + c2pwrite = stdout.fileno() + + if stderr == None: + pass + elif stderr == PIPE: + errread, errwrite = os.pipe() + elif stderr == STDOUT: + errwrite = c2pwrite + elif type(stderr) == types.IntType: + errwrite = stderr + else: + # Assuming file-like object + errwrite = stderr.fileno() + + return (p2cread, p2cwrite, + c2pread, c2pwrite, + errread, errwrite) + + + def _set_cloexec_flag(self, fd): + try: + cloexec_flag = fcntl.FD_CLOEXEC + except AttributeError: + cloexec_flag = 1 + + old = fcntl.fcntl(fd, fcntl.F_GETFD) + fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag) + + + def _close_fds(self, but): + for i in range(3, MAXFD): + if i == but: + continue + try: + os.close(i) + except: + pass + + + def _execute_child(self, args, executable, preexec_fn, close_fds, + cwd, env, universal_newlines, + startupinfo, creationflags, shell, + p2cread, p2cwrite, + c2pread, c2pwrite, + errread, errwrite): + """Execute program (POSIX version)""" + + if isinstance(args, types.StringTypes): + args = [args] + + if shell: + args = ["/bin/sh", "-c"] + args + + if executable == None: + executable = args[0] + + # For transferring possible exec failure from child to parent + # The first char specifies the exception type: 0 means + # OSError, 1 means some other error. + errpipe_read, errpipe_write = os.pipe() + self._set_cloexec_flag(errpipe_write) + + self.pid = os.fork() + if self.pid == 0: + # Child + try: + # Close parent's pipe ends + if p2cwrite: + os.close(p2cwrite) + if c2pread: + os.close(c2pread) + if errread: + os.close(errread) + os.close(errpipe_read) + + # Dup fds for child + if p2cread: + os.dup2(p2cread, 0) + if c2pwrite: + os.dup2(c2pwrite, 1) + if errwrite: + os.dup2(errwrite, 2) + + # Close pipe fds. Make sure we doesn't close the same + # fd more than once. + if p2cread: + os.close(p2cread) + if c2pwrite and c2pwrite not in (p2cread,): + os.close(c2pwrite) + if errwrite and errwrite not in (p2cread, c2pwrite): + os.close(errwrite) + + # Close all other fds, if asked for + if close_fds: + self._close_fds(but=errpipe_write) + + if cwd != None: + os.chdir(cwd) + + if preexec_fn: + apply(preexec_fn) + + if env == None: + os.execvp(executable, args) + else: + os.execvpe(executable, args, env) + + except: + exc_type, exc_value, tb = sys.exc_info() + # Save the traceback and attach it to the exception object + exc_lines = traceback.format_exception(exc_type, + exc_value, + tb) + exc_value.child_traceback = ''.join(exc_lines) + os.write(errpipe_write, pickle.dumps(exc_value)) + + # This exitcode won't be reported to applications, so it + # really doesn't matter what we return. + os._exit(255) + + # Parent + os.close(errpipe_write) + if p2cread and p2cwrite: + os.close(p2cread) + if c2pwrite and c2pread: + os.close(c2pwrite) + if errwrite and errread: + os.close(errwrite) + + # Wait for exec to fail or succeed; possibly raising exception + data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB + os.close(errpipe_read) + if data != "": + os.waitpid(self.pid, 0) + child_exception = pickle.loads(data) + raise child_exception + + + def _handle_exitstatus(self, sts): + if os.WIFSIGNALED(sts): + self.returncode = -os.WTERMSIG(sts) + elif os.WIFEXITED(sts): + self.returncode = os.WEXITSTATUS(sts) + else: + # Should never happen + raise RuntimeError("Unknown child exit status!") + + _active.remove(self) + + + def poll(self): + """Check if child process has terminated. Returns returncode + attribute.""" + if self.returncode == None: + try: + pid, sts = os.waitpid(self.pid, os.WNOHANG) + if pid == self.pid: + self._handle_exitstatus(sts) + except os.error: + pass + return self.returncode + + + def wait(self): + """Wait for child process to terminate. Returns returncode + attribute.""" + if self.returncode == None: + pid, sts = os.waitpid(self.pid, 0) + self._handle_exitstatus(sts) + return self.returncode + + + def communicate(self, input=None): + """Interact with process: Send data to stdin. Read data from + stdout and stderr, until end-of-file is reached. Wait for + process to terminate. The optional input argument should be a + string to be sent to the child process, or None, if no data + should be sent to the child. + + communicate() returns a tuple (stdout, stderr).""" + read_set = [] + write_set = [] + stdout = None # Return + stderr = None # Return + + if self.stdin: + # Flush stdio buffer. This might block, if the user has + # been writing to .stdin in an uncontrolled fashion. + self.stdin.flush() + if input: + write_set.append(self.stdin) + else: + self.stdin.close() + if self.stdout: + read_set.append(self.stdout) + stdout = [] + if self.stderr: + read_set.append(self.stderr) + stderr = [] + + while read_set or write_set: + rlist, wlist, xlist = select.select(read_set, write_set, []) + + if self.stdin in wlist: + # When select has indicated that the file is writable, + # we can write up to PIPE_BUF bytes without risk + # blocking. POSIX defines PIPE_BUF >= 512 + bytes_written = os.write(self.stdin.fileno(), input[:512]) + input = input[bytes_written:] + if not input: + self.stdin.close() + write_set.remove(self.stdin) + + if self.stdout in rlist: + data = os.read(self.stdout.fileno(), 1024) + if data == "": + self.stdout.close() + read_set.remove(self.stdout) + stdout.append(data) + + if self.stderr in rlist: + data = os.read(self.stderr.fileno(), 1024) + if data == "": + self.stderr.close() + read_set.remove(self.stderr) + stderr.append(data) + + # All data exchanged. Translate lists into strings. + if stdout != None: + stdout = ''.join(stdout) + if stderr != None: + stderr = ''.join(stderr) + + # Translate newlines, if requested. We cannot let the file + # object do the translation: It is based on stdio, which is + # impossible to combine with select (unless forcing no + # buffering). + if self.universal_newlines and hasattr(open, 'newlines'): + if stdout: + stdout = self._translate_newlines(stdout) + if stderr: + stderr = self._translate_newlines(stderr) + + self.wait() + return (stdout, stderr) + + +def _demo_posix(): + # + # Example 1: Simple redirection: Get process list + # + plist = Popen(["ps"], stdout=PIPE).communicate()[0] + print "Process list:" + print plist + + # + # Example 2: Change uid before executing child + # + if os.getuid() == 0: + p = Popen(["id"], preexec_fn=lambda: os.setuid(100)) + p.wait() + + # + # Example 3: Connecting several subprocesses + # + print "Looking for 'hda'..." + p1 = Popen(["dmesg"], stdout=PIPE) + p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) + print repr(p2.communicate()[0]) + + # + # Example 4: Catch execution error + # + print + print "Trying a weird file..." + try: + print Popen(["/this/path/does/not/exist"]).communicate() + except OSError, e: + if e.errno == errno.ENOENT: + print "The file didn't exist. I thought so..." + print "Child traceback:" + print e.child_traceback + else: + print "Error", e.errno + else: + print >>sys.stderr, "Gosh. No error." + + +def _demo_windows(): + # + # Example 1: Connecting several subprocesses + # + print "Looking for 'PROMPT' in set output..." + p1 = Popen("set", stdout=PIPE, shell=True) + p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE) + print repr(p2.communicate()[0]) + + # + # Example 2: Simple execution of program + # + print "Executing calc..." + p = Popen("calc") + p.wait() + + +if __name__ == "__main__": + if mswindows: + _demo_windows() + else: + _demo_posix() diff --git a/pypers/bolzano/web/biancheria.py b/pypers/bolzano/web/biancheria.py new file mode 100755 index 0000000..750fb7c --- /dev/null +++ b/pypers/bolzano/web/biancheria.py @@ -0,0 +1,51 @@ +from quixote_utils import RootDirectory +from quixote.form.widget import StringWidget, SubmitWidget, CheckboxWidget, \ + RadiobuttonsWidget +from quixote.form.form import Form +from quixote.util import htmltext + +class BiancheriaOnLine(RootDirectory): + _q_exports = ["", "magliette", "maglioni", "calzini", "mutande"] + + def _q_index(self): + return "Benvenuti al nostro negozio di biancheria online!!" + + def magliette(self): + return "<h1>magliette</h1>" + + def maglioni(self): + return "maglioni" + + def calzini(self): + msg = htmltext(""" + Abbiamo disponili i seguenti modelli: <br/> <br/> + A. Calzettone lungo da neve <br/> + B. Calzino di seta estivo <br/> + C. Calzino nero lutto <br/> + """) + form = Form() + form.add(RadiobuttonsWidget, "calzini", options=list("ABC")) + form.add(SubmitWidget, "submit", "Compra!") + return msg + form.render() + + def mutande(self): + msg = htmltext(""" + Abbiamo disponili i seguenti modelli: <br/> <br/> + A. mutanda modello base <br/> + B. mutandina di pizzo per signore <br/> + C. mutandone ascellare modello Fantozzi <br/> + """) + form = Form() + form.add(CheckboxWidget, "modelloA", value=0) + form.add(CheckboxWidget, "modelloB", value=0) + form.add(CheckboxWidget, "modelloC", value=1) + form.add(SubmitWidget, "submit", "Compra!") + return msg + form.render() + + def oxe(self): + return "XXX" + + + +if __name__ == "__main__": + BiancheriaOnLine().publish_show("calzini", browser="mozilla") diff --git a/pypers/bolzano/web/cgi-bin/esempio1.py b/pypers/bolzano/web/cgi-bin/esempio1.py new file mode 100755 index 0000000..49c850f --- /dev/null +++ b/pypers/bolzano/web/cgi-bin/esempio1.py @@ -0,0 +1 @@ +print "hello!" diff --git a/pypers/bolzano/web/cgi-bin/ex_form.html b/pypers/bolzano/web/cgi-bin/ex_form.html new file mode 100755 index 0000000..323edf8 --- /dev/null +++ b/pypers/bolzano/web/cgi-bin/ex_form.html @@ -0,0 +1,10 @@ +<html> +<head> +</head> +<body> +<form action="hello.py"> +<input type="text" name="phonenumber" value="XXXXX"><br/> +<input type="submit" name="submit" value="ok"> +</form> +</body> +</html> diff --git a/pypers/bolzano/web/cgi-bin/ex_form.py b/pypers/bolzano/web/cgi-bin/ex_form.py new file mode 100755 index 0000000..4926574 --- /dev/null +++ b/pypers/bolzano/web/cgi-bin/ex_form.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +print "Content-type: text/html\n" +form = """ +<html> +<head> +</head> +<body> +<form action="save_phonenumber.py"> +<input type="text" name="phonenumber" value="XXXXX"><br/> +<input type="submit" name="submit" value="ok"> +</form> +</body> +</html> +""" +print form diff --git a/pypers/bolzano/web/cgi-bin/hello.py b/pypers/bolzano/web/cgi-bin/hello.py new file mode 100755 index 0000000..212415d --- /dev/null +++ b/pypers/bolzano/web/cgi-bin/hello.py @@ -0,0 +1,9 @@ +#!/usr/bin/env python +print "Content-type: text/html\n" +print "<html>" +print "<head>" +print "</head>" +print "<body>" +print "<h1>HELLO!</h1>" +print "</body>" +print "</html>" diff --git a/pypers/bolzano/web/cgi-bin/hello_quixote.py b/pypers/bolzano/web/cgi-bin/hello_quixote.py new file mode 100755 index 0000000..63f20bb --- /dev/null +++ b/pypers/bolzano/web/cgi-bin/hello_quixote.py @@ -0,0 +1,25 @@ +from quixote_utils import RootDirectory + +class BiancheriaOnLine(RootDirectory): + _q_exports = ["", "magliette", "maglioni", "calzini", "mutande"] + + def _q_index(self): + return "Benvenuti al nostro negozio di biancheria online!!" + + def magliette(self): + return "magliette" + + def maglioni(self): + return "maglioni" + + def calzini(self): + return "calzini" + + def mutande(self): + return "mutande" + + def oxe(self): + return "XXX" + +if __name__ == "__main__": + BiancheriaOnLine().publish_show() diff --git a/pypers/bolzano/web/cgi-bin/save_phonenumber.py b/pypers/bolzano/web/cgi-bin/save_phonenumber.py new file mode 100755 index 0000000..2d7b121 --- /dev/null +++ b/pypers/bolzano/web/cgi-bin/save_phonenumber.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python +import cgi +print "Content-type: text/plain\n" + + +form = cgi.FieldStorage() +number = form["phonenumber"].value +print "The submitted phone number (%s) has been saved!" % number diff --git a/pypers/bolzano/web/for.py b/pypers/bolzano/web/for.py new file mode 100755 index 0000000..c352bf3 --- /dev/null +++ b/pypers/bolzano/web/for.py @@ -0,0 +1,16 @@ +class MyClass(object): + pass + +myobj = MyClass() + +for i in 1,2,3: + def f(default=i): + print default + setattr(myobj, "a%s" % i, f) + f() + +print "-------" +myobj.a1() +myobj.a2() +myobj.a3() + diff --git a/pypers/bolzano/web/monitor.py b/pypers/bolzano/web/monitor.py new file mode 100755 index 0000000..0ab3411 --- /dev/null +++ b/pypers/bolzano/web/monitor.py @@ -0,0 +1,29 @@ +from quixote_utils import RootDirectory + +import os, time + +def second_counter(): + global nsec + nsec = 0 + while True: + nsec += 1 + os.NSEC = str(nsec) + time.sleep(1) + + +class Root(RootDirectory): + def _q_index(self): + return "Numero di secondi passati: %s" % os.NSEC + +if __name__ == "__main__": + os.NSEC = "0" + result = os.fork() + if result: + print "This the pid of the child process: %s. Now I am in the parent."\ + % result + Root().publish_show("") + else: + print "I am in the child process." + second_counter() + + diff --git a/pypers/bolzano/web/monitor_fork.py b/pypers/bolzano/web/monitor_fork.py new file mode 100755 index 0000000..3139ed9 --- /dev/null +++ b/pypers/bolzano/web/monitor_fork.py @@ -0,0 +1,17 @@ +import os, time +from subprocess import call +from SimpleHTTPServer import test + +if __name__ == "__main__": + result = os.fork() + if result: + time.sleep(0.5) + print "This the pid of the child process: %s. Now I am in the parent."\ + % result + call(["konqueror", "http://localhost:8000"]) + else: + print "I am in the child process." + test() + + + diff --git a/pypers/bolzano/web/monitor_thread.py b/pypers/bolzano/web/monitor_thread.py new file mode 100755 index 0000000..f60e1ff --- /dev/null +++ b/pypers/bolzano/web/monitor_thread.py @@ -0,0 +1,27 @@ +from quixote_utils import RootDirectory +import os, time, threading + +class Counter(threading.Thread): + def run(self): + global nsec + nsec = 0 + self.running = True + while self.running: + nsec += 1 + time.sleep(1) + def stop(self): + self.running = False + + +class Root(RootDirectory): + def _q_index(self): + return "Numero di secondi passati: %s" % nsec + +if __name__ == "__main__": + counter = Counter() + counter.start() + try: + Root().publish_show("") + finally: + counter.stop() + diff --git a/pypers/bolzano/web/prova.html b/pypers/bolzano/web/prova.html new file mode 100755 index 0000000..882f46c --- /dev/null +++ b/pypers/bolzano/web/prova.html @@ -0,0 +1 @@ +<img src="file:///home/micheles/Desktop/photos-images/images/baldios.jpg"> diff --git a/pypers/bolzano/web/q_forms.py b/pypers/bolzano/web/q_forms.py new file mode 100755 index 0000000..e3decf1 --- /dev/null +++ b/pypers/bolzano/web/q_forms.py @@ -0,0 +1,27 @@ +from quixote_utils import RootDirectory +from quixote.form.widget import StringWidget, SubmitWidget +from quixote.form.form import Form + +class Root(RootDirectory): + _q_exports = ["string_widget", "submit_button", "form_with_submit", + "thank_you"] + + def string_widget(self): + return StringWidget("Telefono", value="0699944857").render() + + def submit_button(self): + return SubmitWidget("submit", value="ok").render() + + def thank_you(self, number): + return "Thank you for submitting %s" % number + + def form_with_submit(self): + form = Form() + form.add(StringWidget, "Telefono", value="XXX") + form.add(SubmitWidget, "submit", value="ok") + if not form.is_submitted(): + return form.render() + else: + return self.thank_you(form["Telefono"]) + +Root().publish_show("form_with_submit") diff --git a/pypers/bolzano/web/quixote_utils.py b/pypers/bolzano/web/quixote_utils.py new file mode 100755 index 0000000..dc7005a --- /dev/null +++ b/pypers/bolzano/web/quixote_utils.py @@ -0,0 +1,189 @@ +import os, sys, time, webbrowser +from quixote.directory import Directory +from quixote.publish import Publisher +from quixote.session import Session, SessionManager +from quixote.server import simple_server +from quixote.errors import AccessError +from quixote import get_response, get_user +from quixote.html import href + +elinks = webbrowser.GenericBrowser('xterm -e elinks %s') +lynx = webbrowser.GenericBrowser('xterm -e lynx -accept_all_cookies %s') +webbrowser.register("elinks", webbrowser.GenericBrowser, elinks) +webbrowser.register("lynx", webbrowser.GenericBrowser, lynx) # second choice +webbrowser.register("konqueror", webbrowser.Konqueror) + +class RecognizeExports(type): + def __init__(cls, name, bases, dic): + super(RecognizeExports, cls).__init__(cls, name, bases, dic) + for k in dic: setattr(cls, k, dic[k]) + def __setattr__(cls, name, value): + if hasattr(value, "_q_exported"): + cls._q_exports.append(name) + super(RecognizeExports, cls).__setattr__(name, value) + +# by definition, the root directory is a singleton +class RootDirectory(Directory): + _q_exports = [""] + __metaclass__ = RecognizeExports + __Publisher = Publisher + __port = 7080 + + def _q_index(self): + return "Welcome to the root of your application." + + def set_default(self, server=simple_server, Publisher=Publisher, + Session=Session, session_mapping=None, port=7080): + self.__server = server + self.__Publisher = Publisher + self.__Session = Session + self.__session_mapping = session_mapping + self.__port = port + + __init__ = set_default + + def publish(self): + if issubclass(self.__Publisher, SessionPublisher): + create_pub = lambda : self.__Publisher( + self, SessionManager(self.__Session, self.__session_mapping)) + else: + create_pub = lambda : self.__Publisher(self) + self.__server.run(create_pub, '', self.__port) + + def publish_show(self, page="", browser="mozilla"): + if os.fork(): # parent + self.publish() + else: # child + webbrowser.get(browser).open( + "http://localhost:%s/%s" % (self.__port, page)) + + +class UnauthorizedError(AccessError): + """The request requires user authentication. + + This subclass of AccessError sends a 401 instead of a 403, + hinting that the client should try again with authentication. + """ + status_code = 401 + title = "Unauthorized" + description = "You are not authorized to access this resource." + + def __init__(self, realm='Protected', public_msg=None, private_msg=None): + self.realm = realm + AccessError.__init__(self, public_msg, private_msg) + + def format(self): + get_response().set_header( + 'WWW-Authenticate', 'Basic realm="%s"' % self.realm) + return AccessError.format(self) + + +class User(object): + def __init__(self, username, password): + self.username = username + self.password = password + def __str__(self): + return "<User: %s %s>" % (self.username, self.password) + def permissions(self): + """Returns the list of methods starting with 'can_'.""" + return [perm for perm in dir(self) if perm.startswith("can_")] + +def public(f): + f._q_exported = True + return f + +class private(object): + """Redirect to the login page if the user is not logged in or if he does + not have the right permissions.""" + # obviously, this assumes a login page exists and is called 'login' + def __init__(self, *groups_with_access): + self.valid_groups = groups_with_access or (User,) + def __call__(self, method): + def wrapper(root): + user = get_user() + if not user or not isinstance(user, self.valid_groups): + root.resume = meth_name + valid_groups = ", ".join( + cls.__name__ for cls in self.valid_groups) + return "You are trying to access a page restricted to %s. " % \ + valid_groups + href( + "login", "Please login as a valid user.") + else: + return method(root) + meth_name = method.func_name + wrapper.func_name = meth_name + wrapper._q_exported = True + return wrapper + +######################## deprecated ############################ + +def old_public(f): + """Append f.__name__ to the caller's _q_exports. If the caller has + no _q_exports, creates it.""" + _q_exports = sys._getframe(1).f_locals.setdefault("_q_exports",[""]) + _q_exports.append(f.__name__) + return f + +class old_private(object): + """Redirect to the login page if the user is not logged in or if he does + not have the right permissions.""" + # obviously, this assumes a login page exists and is called 'login' + def __init__(self, *groups_with_access): + self.valid_groups = groups_with_access or (User,) + def __call__(self, method): + def wrapper(root): + user = get_user() + if not user or not isinstance(user, self.valid_groups): + root.resume = meth_name + valid_groups = ", ".join(cls.__name__ for cls in self.valid_groups) + return "You are trying to access a page restricted to %s. " % \ + valid_groups + href("login", "Please login as a valid user.") + else: + return method(root) + meth_name = method.func_name + _q_exports = sys._getframe(1).f_locals.setdefault("_q_exports",[""]) + _q_exports.append(meth_name) + wrapper.func_name = meth_name + return wrapper + +from ms.iter_utils import Cycle, chop + +class MultipageTable(object): + # use Quixote forms + def __init__(self, body, header=[], maxsize=20): + self.header = header + self.maxsize = maxsize + self.section = Cycle(chop(body, maxsize)) + self.sect = self.section[0] # default + self.ismultipage = len(self.section) > 1 + + def makerow(self, row, header=False): + if header: + r = " ".join("<th>%s</th>" % col for col in row) + else: + r = " ".join("<td>%s</td>" % col for col in row) + return "<tr>%s</tr>" % r + + def maketable(self): + #yield "<div align='center'>" + if self.ismultipage: + form = Form() + form.add(SubmitWidget, "prev", "Prev") + form.add(SubmitWidget, "next", "Next") + if form["next"]: # is submitted + self.sect = self.section.next() + if form["prev"]: # is submitted + self.sect = self.section.prev() + yield "Page #%s of %s" % (self.section.index+1, len(self.section)) + yield "<table border='1'>" + if self.header: + yield self.makerow(self.header) + for row in self.sect: + yield self.makerow(row) + yield "</table>" + if self.ismultipage: + yield form.render() + #yield "</div>" + + def render(self): + return htmltext("\n").join(map(htmltext, self.maketable())) diff --git a/pypers/bolzano/web/viewer.py b/pypers/bolzano/web/viewer.py new file mode 100755 index 0000000..d9b3299 --- /dev/null +++ b/pypers/bolzano/web/viewer.py @@ -0,0 +1,28 @@ +from quixote_utils import RootDirectory +from quixote.util import htmltext +from quixote.html import href +import os + +imagedir = "/mnt/sda1/photos-images/images" + +class ImageViewer(RootDirectory): + _q_exports = [""] + def __init__(self, images): + self.images = images + self.links = [] + for name in self.images: + nospaces_name = name.replace(" ", "_") + self._q_exports.append(nospaces_name) + self.links.append(href(nospaces_name, name)) + def imagesrc(name=name): + return "<image src='file://%s'>" % \ + os.path.join(imagedir, name) + setattr(self, nospaces_name, imagesrc) + def _q_index(self): + return htmltext("<h1>Available images</h1>")+ \ + htmltext("<br/>").join(self.links) + +viewer = ImageViewer([img for img in os.listdir(imagedir) + if img.endswith(".jpg")]) + +viewer.publish_show() diff --git a/pypers/bolzano/web/viewer2.py b/pypers/bolzano/web/viewer2.py new file mode 100755 index 0000000..1ba26c9 --- /dev/null +++ b/pypers/bolzano/web/viewer2.py @@ -0,0 +1,35 @@ +from quixote_utils import RootDirectory +from quixote.util import htmltext +from quixote.html import href +import os + +imagedir = "/home/micheles/Desktop/photos-images/images" + +class ImageViewer(RootDirectory): + _q_exports = ["", "prev", "next"] + def __init__(self, images): + self.images = images + self.current_image = 0 + + def prev(self): + self.current_image -= 1 + return self._q_index() + + def next(self): + self.current_image += 1 + return self._q_index() + + def _q_index(self): + name = self.images[self.current_image] + return '''<html><head></head><body> + <a href="prev">prev</a> + <a href="next">next</a><br/> + Current image: %s <br/> + <img src="file://%s"> + </body><html> + ''' % (self.current_image, os.path.join(imagedir, name)) + +viewer = ImageViewer([img for img in os.listdir(imagedir) + if img.endswith(".jpg")]) + +viewer.publish_show(browser="mozilla") diff --git a/pypers/bolzano/webplayer.py b/pypers/bolzano/webplayer.py new file mode 100755 index 0000000..5a46f52 --- /dev/null +++ b/pypers/bolzano/webplayer.py @@ -0,0 +1,67 @@ +import os +from quixote.directory import Directory +from ms.html_utils import simplepage, makelink +from quixote.publish import Publisher +from quixote import get_field, redirect +from quixote.server.simple_server import run +from quixote.form.form import Form +from ms.misc_utils import Popen # fix Popen + +MUSIC = "/mnt/smb/Music" +PLAYER = "/usr/bin/mpg123" + +class Current: + player = None + song = None + +def play(song, player = PLAYER): + print "Playing %s ..." % song + return Popen([player, song]) + +def add_to(obj): + def wrapper(f): + setattr(obj, f.__name__, f) + return f + return wrapper + +top = Directory() + +top._q_exports= ["", "stopper"] + +songs=[os.path.join(MUSIC, x) for x in os.listdir(MUSIC) if x.endswith(".mp3")] + +@add_to(top) +def _q_index(): + return simplepage( + title="Welcome to the Web player!", + body=selector(songs)) + +def selector(songs): + global player, song + chosen = get_field("select") + if chosen: + song = chosen + player = play(song) + redirect("stopper") # works with Mozilla, but not with lynx/elinks + else: + f = Form() + f.add_single_select("select", options=songs) + f.add_submit("play", "Play!") + return f.render() + +def stopper(): + stop = get_field("stop") + if stop: + player.kill() + return simplepage(body = "%s stopped." % song) + else: + f = Form() + f.add_submit("stop", "Stop") + return simplepage(body= ("Playing %s" % song) + + f.render()) + +top.stopper = lambda : stopper() + +if __name__ == '__main__': + print 'Listening on http://localhost:8080 ...' + run(lambda : Publisher(top), '', 8080) |