python shelve on win vs unix
Hi, Have a problem using shelve on windows and unix. While my windows box supports dbhash, my unix box supports gdbm, and neither supports what the other does. The problem arises when I try to use the shelve generated in unix on my windows box. Hoepfully there are alternatives to installing the berkeley db (needed by dbhash) on unix, which I'm looking at now. I'm no unix guru and would probably use "forever" to get it up and running. Any suggestions for a quick and dirty solution (such as alternatives to shelve for persistent storage) to this problem would be appreciated. regards, Tor Erik -- http://mail.python.org/mailman/listinfo/python-list
str and __setitem__
Hi, What do I need to do to make the code below work as expected: class str2(str): def __setitem__(self, i, y): assert type(y) is str assert type(i) is int assert i < len(self) self = self[:i] + y + self[1+i:] a = str2('123') a[1] = '1' print a 123 The print statement should return 113 Regards tores -- http://mail.python.org/mailman/listinfo/python-list
Re: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?
Steven D'Aprano <[EMAIL PROTECTED]> wrote in news:[EMAIL PROTECTED]: > On Thu, 23 Nov 2006 10:48:32 +0000, Tor Erik Soenvisen wrote: > >> Hi, >> >> >> (len(['']) is 1) == (len(['']) == 1) => True > > You shouldn't rely on this behaviour: > >>>> x = 10 >>>> len('a' * x) == x > True >>>> len('a' * x) is x > False > > (Your results may vary -- this depends on the implementation.) > > > >> Is this the case for all numbers? I've tried running the following: >> >> for i in range(1): >> for j in range(1): >> if i != j: >>assert id(i) != id(j), 'i=%d, j=%d, id=%d' % (i, j, id >> (i)) >> >> which executes fine. Hence, 0- is okey... > > This doesn't necessarily hold for all integers -- again, it depends on > the implementation, the precise version of Python, and other factors. > Don't rely on "is" giving the same results as "==". > >>>> (1+2+3+4+5)**7 == 15**7 > True >>>> (1+2+3+4+5)**7 is 15**7 > False > >> But this is a relatively >> small range, and sooner or later you probably get two numbers with >> the same id... Thoughts anyone? > > No, you will never get two objects existing at the same time with the > same id. You will get two objects that exist at different times with > the same id, since ids may be reused when the object is deleted. > >> PS: For those of you who don't know: keyword is compares object >> identities > > Exactly. There is no guarantee that any specific integer object "1" > must be the same object as another integer object "1". It may be, but > it isn't guaranteed. > > I think the only object that is guaranteed to hold for is None. None > is a singleton, so there is only ever one instance. Hence, you should > test for None with "obj is None" rather than ==, because some custom > classes may do silly things with __eq__: > > class Blank(object): > """Compares equal to anything false, including None.""" > def __eq__(self, other): > return not other > > I've seen code like this: if type([]) is list: print 'Is list' which seem to work. And also I've seen "var is None", as you mention. -- http://mail.python.org/mailman/listinfo/python-list
len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?
Hi, (len(['']) is 1) == (len(['']) == 1) => True Is this the case for all numbers? I've tried running the following: for i in range(1): for j in range(1): if i != j: assert id(i) != id(j), 'i=%d, j=%d, id=%d' % (i, j, id (i)) which executes fine. Hence, 0- is okey... But this is a relatively small range, and sooner or later you probably get two numbers with the same id... Thoughts anyone? Regards Tor Erik PS: For those of you who don't know: keyword is compares object identities -- http://mail.python.org/mailman/listinfo/python-list
Code feedback
Hi, all I would like some feedback on a multithreaded HTTP server I've written. The server serves python-scripts by dynamically loading scripts in the same directory as itself. When a request is made to one of these scripts the script is executed and its output is returned to the requester. Here is the server code, HTTPServer.py: # Basic, threaded HTTP server, serving requests via python scripts # Author: Tor Erik Soenvisen # Std lib imports import BaseHTTPServer, os, threading, Queue class HTTPServer(BaseHTTPServer.HTTPServer): """ A threaded HTTP server """ port = 80 # Maximum requests on hold request_queue_size = 250 # Maximum requests serviced concurrently workers = 20 def __init__(self, port=None, reqSize=None, workers=None): if port is not None: self.port = port if reqSize is not None: self.request_queue_size = reqSize if workers is not None: self.workers = workers self.sharedPath = os.path.dirname(os.path.abspath(__file__)) # self.sharedPath must be set before calling self.getHandlers self.handler = self.getHandlers() self.jobQueue = Queue.Queue(self.request_queue_size) addr = ('', self.port) BaseHTTPServer.HTTPServer.__init__(self, addr, HTTPRequestHandler) # Exit threads when application exits self.daemon_threads = True self.createThreadPool() self.serve_forever() def getHandlers(self): """ Imports all python scripts in the current directory except this one. These scripts are the response generators corresponding to all valid path requests. The idea is to comprise something similar to a lightweight CGI, where each script generate HTTP responses to HTTP requests """ import inspect # 1. List all files in current directory # 2. Skip files not having a .py extension, in addition to this file # 3. Slice of .py extension handler = dict.fromkeys([x[:-3] for x in os.listdir (self.sharedPath) \ if x.endswith('.py') and \ x != os.path.basename(__file__)]) for name in handler: handler[name] = __import__(name) # Make sure the handler contains a run function accepting at least # one parameter if not hasattr(handler[name], 'run') or \ len(inspect.getargspec(handler[name].run)[0]) != 2: print 'Handler %s.py dropped because it lacks ' % name + \ 'a function named run accepting two arguments' del handler[name] return handler def createThreadPool(self): """ Creates pool of worker threads, servicing requests """ self.tpool = [] for i in range(self.workers): self.tpool.append(threading.Thread (target=self.process_request_thread, args=())) if self.daemon_threads: self.tpool[-1].setDaemon(1) self.tpool[-1].start() def serve_forever(self): """ Handle requests "forever" """ while 1: self.handle_request() def process_request(self, request, client_address): """ Task source: dispath requests to job queue """ self.jobQueue.put((request, client_address)) def process_request_thread(self): """ Task sink: process requests from job queue """ while 1: request, client_address = self.jobQueue.get() try: self.finish_request(request, client_address) self.close_request(request) except: self.handle_error(request, client_address) self.close_request(request) class HTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """ Handles HTTP requests. GET is the only method currently supported """ # Set HTTP protocol version 1.1 protocol_version = 'HTTP/1.1' # Set default response headers responseHeaders = {'Content-Type': 'text/html', 'Content-Length': '', 'Connection': 'close'} def log_message(self, format, *args): """ Log function: see BaseHTTPServer.py for info on arguments """ pass def do_GET(self): """ Handles HTTP GET requests """ name = self.path.lstrip('/') try: handler = self.server.handler[name].ru
Protecting against SQL injection
Hi, How safe is the following code against SQL injection: # Get user privilege digest = sha.new(pw).hexdigest() # Protect against SQL injection by escaping quotes uname = uname.replace("'", "''") sql = 'SELECT privilege FROM staff WHERE ' + \ 'username=\'%s\' AND password=\'%s\'' % (uname, digest) res = self.oraDB.query(sql) pw is the supplied password abd uname is the supplied password. regards -- http://mail.python.org/mailman/listinfo/python-list
FTP over SSL
Hi, Anyone know about existing code supporting FTP over SSL? I guess pycurl http://pycurl.sourceforge.net/ could be used, but that requires knowledge of libcurl, which I haven't. regards -- http://mail.python.org/mailman/listinfo/python-list
Assigning different Exception message
try: self.cursor.execute(sql) except AttributeError, e: if e.message == "oracleDB instance has no attribute 'cursor'": e.message = 'oracleDB.open() must be called before' + \ ' oracleDB.query()' raise AttributeError, e This code does not re-assign e's message when the conditional is satisfied. Why not? regards -- http://mail.python.org/mailman/listinfo/python-list
Oracle database export
Hi, I need to export an Oracle database to a DDL-formated file. On the Web, I found a Python script that did exactly this for a MS Access database, but not one for Oracle databases. Does anyone know of such a tool or Python script. regards tores -- http://mail.python.org/mailman/listinfo/python-list