title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
python logarithm
961,972
<p>i want to find out a log10 of an integer in python and i get an error like math domain error </p> <p>my code is this w=math.log10(q*q1)/math.log10(2)</p> <p>where q1,q2 are integers</p> <p>yeah q1 is 0 sometimes</p>
1
2009-06-07T14:29:43Z
27,588,519
<p>try to make sure the value whose log you are trying to find can never be 0. As log(0) tends to negative infinity, the function call will give you a math domain error. Correct that and I think you'll be fine.</p>
0
2014-12-21T10:27:22Z
[ "python" ]
How can I speed up a web-application? (Avoid rebuilding a structure.)
961,981
<p>After having successfully build a static data structure (<a href="http://stackoverflow.com/questions/960963/trie-prefix-tree-in-python">see here</a>), I would want to avoid having to build it from scratch every time a user requests an operation on it. My naïv first idea was to dump the structure (using python's pickle) into a file and load this file for each query. Needless to say (as I figured out), this turns out to be too time-consuming, as the file is rather large.</p> <p>Any ideas how I can easily speed up this thing? Splitting the file into multiple files? Or a program running on the server? (How difficult is this to implement?)</p> <p>Thanks for your help!</p>
1
2009-06-07T14:34:19Z
962,006
<p>My suggestion would be not to rely on having an object structure. Instead have a byte array (or mmap'd file etc) which you can do random access operations on and implement the cross-referencing using pointers inside that structure.</p> <p>True, it will introduce the concept of pointers to your code, but it will mean that you don't need to unpickle it each time the handler process starts up, and it will also use a lot less memory (as there won't be the overhead of python objects).</p> <p>As your database is going to be fixed during the lifetime of a handler process (I imagine), you won't need to worry about concurrent modifications or locking etc.</p> <p>Even if you did what you suggest, you shouldn't have to rebuild it on every user request, just keep an instance in memory in your worker process(es), which means it won't take too long to build as you only build it when a new worker process starts.</p>
2
2009-06-07T14:45:46Z
[ "python", "apache", "web-applications", "pickle" ]
How can I speed up a web-application? (Avoid rebuilding a structure.)
961,981
<p>After having successfully build a static data structure (<a href="http://stackoverflow.com/questions/960963/trie-prefix-tree-in-python">see here</a>), I would want to avoid having to build it from scratch every time a user requests an operation on it. My naïv first idea was to dump the structure (using python's pickle) into a file and load this file for each query. Needless to say (as I figured out), this turns out to be too time-consuming, as the file is rather large.</p> <p>Any ideas how I can easily speed up this thing? Splitting the file into multiple files? Or a program running on the server? (How difficult is this to implement?)</p> <p>Thanks for your help!</p>
1
2009-06-07T14:34:19Z
962,011
<p>You can dump it in a memory cache (such as <a href="http://www.danga.com/memcached/" rel="nofollow">memcached</a>).</p> <p>This method has the advantage of cache key invalidation. When underlying data changes you can invalidate your cached data.</p> <h3>EDIT</h3> <p>Here's the python implementation of memcached: <a href="http://www.tummy.com/Community/software/python-memcached/" rel="nofollow">python-memcached</a>. Thanks <a href="http://stackoverflow.com/users/115023/nicdumz">NicDumZ</a>.</p>
4
2009-06-07T14:46:53Z
[ "python", "apache", "web-applications", "pickle" ]
How can I speed up a web-application? (Avoid rebuilding a structure.)
961,981
<p>After having successfully build a static data structure (<a href="http://stackoverflow.com/questions/960963/trie-prefix-tree-in-python">see here</a>), I would want to avoid having to build it from scratch every time a user requests an operation on it. My naïv first idea was to dump the structure (using python's pickle) into a file and load this file for each query. Needless to say (as I figured out), this turns out to be too time-consuming, as the file is rather large.</p> <p>Any ideas how I can easily speed up this thing? Splitting the file into multiple files? Or a program running on the server? (How difficult is this to implement?)</p> <p>Thanks for your help!</p>
1
2009-06-07T14:34:19Z
962,041
<p>If you can rebuild your Python runtime with the patches offered in the <a href="http://code.google.com/p/unladen-swallow/" rel="nofollow">Unladen Swallow</a> project, you should see speedups of 40% to 150% in pickling, 36% to 56% in unpickling, according to <a href="http://code.google.com/p/unladen-swallow/wiki/Releases" rel="nofollow">their benchmarks</a>; maybe that might help. </p>
3
2009-06-07T15:02:05Z
[ "python", "apache", "web-applications", "pickle" ]
How can I speed up a web-application? (Avoid rebuilding a structure.)
961,981
<p>After having successfully build a static data structure (<a href="http://stackoverflow.com/questions/960963/trie-prefix-tree-in-python">see here</a>), I would want to avoid having to build it from scratch every time a user requests an operation on it. My naïv first idea was to dump the structure (using python's pickle) into a file and load this file for each query. Needless to say (as I figured out), this turns out to be too time-consuming, as the file is rather large.</p> <p>Any ideas how I can easily speed up this thing? Splitting the file into multiple files? Or a program running on the server? (How difficult is this to implement?)</p> <p>Thanks for your help!</p>
1
2009-06-07T14:34:19Z
962,510
<p>The number one way to speed up your web application, especially when you have lots of mostly-static modules, classes and objects that need to be initialized: use a way of serving files that supports serving multiple requests from a single interpreter, such as mod_wsgi, mod_python, SCGI, FastCGI, Google App Engine, a Python web server... basically anything <em>except</em> a standard CGI script that starts a new Python process for every request. With this approach, you can make your data structure a global object that only needs to be read from a serialized format for each new <em>process</em>—which is much less frequent.</p>
2
2009-06-07T18:40:06Z
[ "python", "apache", "web-applications", "pickle" ]
How to enumerate a list of non-string objects in Python?
962,082
<p>There is a nice class <code>Enum</code> from <code>enum</code>, but it only works for strings. I'm currently using:</p> <pre><code> for index in range(len(objects)): # do something with index and objects[index] </code></pre> <p>I guess it's not the optimal solution due to the premature use of <code>len</code>. How is it possible to do it more efficiently?</p>
5
2009-06-07T15:18:15Z
962,087
<p>Here is the pythonic way to write this loop:</p> <pre><code>for index, obj in enumerate(objects): # Use index, obj. </code></pre> <p><a href="http://docs.python.org/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> works on any sequence regardless of the types of its elements. It is a builtin function.</p> <p><strong>Edit:</strong></p> <p>After running some <code>timeit</code> tests using Python 2.5, I found <code>enumerate</code> to be slightly slower:</p> <pre><code>&gt;&gt;&gt; timeit.Timer('for i in xrange(len(seq)): x = i + seq[i]', 'seq = range(100)').timeit() 10.322299003601074 &gt;&gt;&gt; timeit.Timer('for i, e in enumerate(seq): x = i + e', 'seq = range(100)').timeit() 11.850601196289062 </code></pre>
11
2009-06-07T15:20:01Z
[ "python", "loops", "enumeration", "sequence" ]
Making a plain ASCII/UTF-8 request/stream HTTP POST request in Python?
962,179
<p>I'm reading some documentation on a service I'm trying to use, and it reads something like this:</p> <blockquote> <p>All requests must be sent using HTTP Post. </p> <p>The XML engine only accepts plain ASCII (text) UTF-8 requests/streams. Encoded streams are not acceptable.</p> </blockquote> <p>All requests/responses are XML.</p> <p>But I really just don't understand what it's asking for. From what I've been reading on <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml" rel="nofollow">HTTP POST in Python</a>, you still need to encode key=value pairs to make a request, where it sounds like they just want the plain XML itself (as a multipart, maybe? I am very confused). Are they giving me enough information and I'm just fundamentally misunderstanding their documentation, or should I ask for more details?</p>
0
2009-06-07T16:05:37Z
962,195
<p>"plain ASCII UTF-8" is a contradiction in terms, IMHO -- ASCII is a subset of UTF-8, though. Try sending UTF-8 including some "special" (non-ASCII) character and see what happens (or, if you can, do ask them to reword said contradition-in-terms!-).</p>
1
2009-06-07T16:12:28Z
[ "python", "http" ]
Making a plain ASCII/UTF-8 request/stream HTTP POST request in Python?
962,179
<p>I'm reading some documentation on a service I'm trying to use, and it reads something like this:</p> <blockquote> <p>All requests must be sent using HTTP Post. </p> <p>The XML engine only accepts plain ASCII (text) UTF-8 requests/streams. Encoded streams are not acceptable.</p> </blockquote> <p>All requests/responses are XML.</p> <p>But I really just don't understand what it's asking for. From what I've been reading on <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml" rel="nofollow">HTTP POST in Python</a>, you still need to encode key=value pairs to make a request, where it sounds like they just want the plain XML itself (as a multipart, maybe? I am very confused). Are they giving me enough information and I'm just fundamentally misunderstanding their documentation, or should I ask for more details?</p>
0
2009-06-07T16:05:37Z
962,212
<p>using <a href="http://docs.python.org/library/urllib2.html#urllib2.Request" rel="nofollow">urllib2.Request</a></p> <pre><code>import urllib2 req = urllib2.Request("http://foo.com/post_here", "&lt;xml data to post&gt;") response = urllib2.urlopen(req) the_page = response.read() </code></pre>
2
2009-06-07T16:21:32Z
[ "python", "http" ]
Bazaar: Modify file content before commit via hook?
962,228
<p>I'm switching from SVN to Bzr for my private projects. There is one feature missing for me, which SVN provides: The replacement of a $Id:$ placeholder with the latest version identification. So far, Bzr provides hooks to do some tricks within the commit process. I've managed to get a list of modified files an manipulate them on the local disk. The problem I encounter is that the snapshot, which is taken from the files that are part of the commit, is made before my modification. The result is, that I have a change of my files, but only local.</p> <p>The workflow I want to build is:</p> <ul> <li>Call Bzr commit </li> <li>modify the $Id:$ macro</li> <li>tell bzr that this modified set is the changeset</li> <li>let Bzr do the rest of it's work</li> </ul> <p>Any ideas?</p>
0
2009-06-07T16:28:15Z
962,697
<p>Use this extension: <a href="http://launchpad.net/bzr-keywords" rel="nofollow">http://launchpad.net/bzr-keywords</a></p>
3
2009-06-07T20:01:34Z
[ "python", "bazaar", "bazaar-plugins" ]
Instance methods called in a separate thread than the instantiation thread
962,323
<p>I'm trying to wrap my head around what is happening in <a href="http://code.activestate.com/recipes/286201/" rel="nofollow">this recipe</a>, because I'm planning on implementing a wx/twisted app similar to this (ie. wx and twisted running in separate threads). I understand that both twisted and wx event-loops need to be accessed in a thread-safe manner (ie. reactor.callFromThread, wx.PostEvent, etc). What I am questioning is the thread-safety of passing in instance methods of objects instantiated in one thread (in the case of this recipe, the GUI thread) as deferred callBack and errBack methods for a reactor running in a separate thread. Is that a good idea?</p> <p>There is a wxreactor available in twisted, but googling reveals that there have been numerous problems with it since it was introduced to the library. Even the person who initially came up with the wxreactor technique, <a href="http://twistedmatrix.com/pipermail/twisted-python/2005-April/010113.html" rel="nofollow">advocates running wx and twisted in separate threads</a>.</p> <p>I haven't been able to find any other examples of this technique, but I'd love to see some.</p>
1
2009-06-07T17:07:07Z
962,862
<p>The sole act of passing instance methods between threads is safe as long as you properly synchronize eventual destruction of those instances (threads share memory so it really doesn't matter which one did the allocation/initialization of a bit of it).</p> <p>The overall thread safety depends on what those methods actually do, so just make them "play nice" and you should be ok.</p>
0
2009-06-07T21:23:13Z
[ "python", "multithreading", "wxpython", "twisted" ]
Instance methods called in a separate thread than the instantiation thread
962,323
<p>I'm trying to wrap my head around what is happening in <a href="http://code.activestate.com/recipes/286201/" rel="nofollow">this recipe</a>, because I'm planning on implementing a wx/twisted app similar to this (ie. wx and twisted running in separate threads). I understand that both twisted and wx event-loops need to be accessed in a thread-safe manner (ie. reactor.callFromThread, wx.PostEvent, etc). What I am questioning is the thread-safety of passing in instance methods of objects instantiated in one thread (in the case of this recipe, the GUI thread) as deferred callBack and errBack methods for a reactor running in a separate thread. Is that a good idea?</p> <p>There is a wxreactor available in twisted, but googling reveals that there have been numerous problems with it since it was introduced to the library. Even the person who initially came up with the wxreactor technique, <a href="http://twistedmatrix.com/pipermail/twisted-python/2005-April/010113.html" rel="nofollow">advocates running wx and twisted in separate threads</a>.</p> <p>I haven't been able to find any other examples of this technique, but I'd love to see some.</p>
1
2009-06-07T17:07:07Z
1,004,947
<p>I wouldn't say that it's a "good idea". You should just run the reactor and the GUI in the same thread with wxreactor.</p> <p>The timer-driven event-loop starving approach described by Mr. Schroeder is the worst possible fail-safe way to implement event-loop integration. If you use <code>wxreactor</code> (not <code>wxsupport</code>) Twisted now uses an approach where multiplexing is shunted off to a thread internally so that nothing needs to use a timer. Better yet would be for wxpython to expose <code>wxSocket</code> and have someone base a reactor on it.</p> <p>However, if you're set on using a separate thread to communicate with Twisted, the one thing to keep in mind is that while you can use objects that originate from any thread you like as the value to pass to <code>Deferred.callback</code>, you must <em>call</em> <code>Deferred.callback</code> only in the reactor thread itself. Deferreds are not threadsafe; thanks to some debugging utilities, not even the <code>Deferred</code> <em>class</em> is threadsafe, so you need to be very careful when you are using them to never leave the Twisted main thread. i.e. when you have a result in the UI thread, use <code>reactor.callFromThread(myDeferred.callback, myresult)</code>.</p>
0
2009-06-17T03:20:12Z
[ "python", "multithreading", "wxpython", "twisted" ]
How to use numpy with 'None' value in Python?
962,343
<p>I'd like to calculate the mean of an array in Python in this form:</p> <pre><code>Matrice = [1, 2, None] </code></pre> <p>I'd just like to have my <code>None</code> value ignored by the <code>numpy.mean</code> calculation but I can't figure out how to do it.</p>
21
2009-06-07T17:21:44Z
962,359
<p>haven't used numpy, but in standard python you can filter out <code>None</code> using list comprehensions or the filter function</p> <pre><code>&gt;&gt;&gt; [i for i in [1, 2, None] if i != None] [1, 2] &gt;&gt;&gt; filter(lambda x: x != None, [1, 2, None]) [1, 2] </code></pre> <p>and then average the result to ignore the <code>None</code></p>
3
2009-06-07T17:28:06Z
[ "python", "numpy", "mean" ]
How to use numpy with 'None' value in Python?
962,343
<p>I'd like to calculate the mean of an array in Python in this form:</p> <pre><code>Matrice = [1, 2, None] </code></pre> <p>I'd just like to have my <code>None</code> value ignored by the <code>numpy.mean</code> calculation but I can't figure out how to do it.</p>
21
2009-06-07T17:21:44Z
962,442
<p>You are looking for <a href="http://docs.scipy.org/doc/numpy/reference/maskedarray.html" rel="nofollow">masked arrays</a>. Here's an example.</p> <pre><code>import MA a = MA.array([1, 2, None], mask = [0, 0, 1]) print "average =", MA.average(a) </code></pre> <p>Unfortunately, masked arrays aren't thoroughly supported in numpy, so you've got to look around to see what can and can't be done with them.</p>
11
2009-06-07T18:10:31Z
[ "python", "numpy", "mean" ]
How to use numpy with 'None' value in Python?
962,343
<p>I'd like to calculate the mean of an array in Python in this form:</p> <pre><code>Matrice = [1, 2, None] </code></pre> <p>I'd just like to have my <code>None</code> value ignored by the <code>numpy.mean</code> calculation but I can't figure out how to do it.</p>
21
2009-06-07T17:21:44Z
1,854,145
<p>You might also be able to kludge with values like NaN or Inf.</p> <pre><code>In [1]: array([1, 2, None]) Out[1]: array([1, 2, None], dtype=object) In [2]: array([1, 2, NaN]) Out[2]: array([ 1., 2., NaN]) </code></pre> <p>Actually, it might not even be a kludge. <a href="http://en.wikipedia.org/wiki/NaN" rel="nofollow">Wikipedia says</a>:</p> <blockquote> <p>NaNs may be used to represent missing values in computations.</p> </blockquote> <p>Actually, this doesn't work for the mean() function, though, so nevermind. :)</p> <pre><code>In [20]: mean([1, 2, NaN]) Out[20]: nan </code></pre>
3
2009-12-06T02:26:13Z
[ "python", "numpy", "mean" ]
How to use numpy with 'None' value in Python?
962,343
<p>I'd like to calculate the mean of an array in Python in this form:</p> <pre><code>Matrice = [1, 2, None] </code></pre> <p>I'd just like to have my <code>None</code> value ignored by the <code>numpy.mean</code> calculation but I can't figure out how to do it.</p>
21
2009-06-07T17:21:44Z
1,854,153
<p>You can also use filter, pass None to it, it will filter non True objects, also 0, :D So, use it when you dont need 0 too.</p> <pre><code>&gt;&gt;&gt; filter(None,[1, 2, None]) [1, 2] </code></pre>
1
2009-12-06T02:30:31Z
[ "python", "numpy", "mean" ]
How to use numpy with 'None' value in Python?
962,343
<p>I'd like to calculate the mean of an array in Python in this form:</p> <pre><code>Matrice = [1, 2, None] </code></pre> <p>I'd just like to have my <code>None</code> value ignored by the <code>numpy.mean</code> calculation but I can't figure out how to do it.</p>
21
2009-06-07T17:21:44Z
8,234,619
<p>You can use scipy for that:</p> <pre><code>import scipy.stats.stats as st m=st.nanmean(vec) </code></pre>
6
2011-11-22T22:15:38Z
[ "python", "numpy", "mean" ]
How can I speed up update/replace operations in PostgreSQL?
962,361
<p>We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects).</p> <p>For sanity reasons we have created our own <a href="http://martinfowler.com/eaaCatalog/dataMapper.html">Data Mapper</a>-like layer that works reasonably well, but it has one big bottleneck, the update performance. Of course, I'm not expecting the update/replace scenario to be as speedy as the 'insert to an empty table' one, but it would be nice to get a bit closer.</p> <p>Note that this system is free from concurrent updates</p> <p>We always set all the fields of each rows on an update, which can be seen in the terminology where I use the word 'replace' in my tests. I've so far tried two approaches to our update problem:</p> <ol> <li><p>Create a <code>replace()</code> procedure that takes an array of rows to update:</p> <pre><code>CREATE OR REPLACE FUNCTION replace_item(data item[]) RETURNS VOID AS $$ BEGIN FOR i IN COALESCE(array_lower(data,1),0) .. COALESCE(array_upper(data,1),-1) LOOP UPDATE item SET a0=data[i].a0,a1=data[i].a1,a2=data[i].a2 WHERE key=data[i].key; END LOOP; END; $$ LANGUAGE plpgsql </code></pre></li> <li><p>Create an <code>insert_or_replace</code> rule so that everything but the occasional delete becomes multi-row inserts</p> <pre><code>CREATE RULE "insert_or_replace" AS ON INSERT TO "item" WHERE EXISTS(SELECT 1 FROM item WHERE key=NEW.key) DO INSTEAD (UPDATE item SET a0=NEW.a0,a1=NEW.a1,a2=NEW.a2 WHERE key=NEW.key); </code></pre></li> </ol> <p>These both speeds up the updates a fair bit, although the latter slows down inserts a bit: </p> <pre><code>Multi-row insert : 50000 items inserted in 1.32 seconds averaging 37807.84 items/s executemany() update : 50000 items updated in 26.67 seconds averaging 1874.57 items/s update_andres : 50000 items updated in 3.84 seconds averaging 13028.51 items/s update_merlin83 (i/d/i) : 50000 items updated in 1.29 seconds averaging 38780.46 items/s update_merlin83 (i/u) : 50000 items updated in 1.24 seconds averaging 40313.28 items/s replace_item() procedure : 50000 items replaced in 3.10 seconds averaging 16151.42 items/s Multi-row insert_or_replace: 50000 items inserted in 2.73 seconds averaging 18296.30 items/s Multi-row insert_or_replace: 50000 items replaced in 2.02 seconds averaging 24729.94 items/s </code></pre> <p>Random notes about the test run:</p> <ul> <li>All tests are run on the same computer as the database resides; connecting to localhost.</li> <li>Inserts and updates are applied to the database in batches of of 500 items, each sent in its own transaction (<strong>UPDATED</strong>).</li> <li>All update/replace tests used the same values as were already in the database.</li> <li>All data was escaped using the psycopg2 adapt() function.</li> <li>All tables are truncated and vacuumed before use (<strong>ADDED</strong>, in previous runs only truncation happened)</li> <li><p>The table looks like this:</p> <pre><code>CREATE TABLE item ( key MACADDR PRIMARY KEY, a0 VARCHAR, a1 VARCHAR, a2 VARCHAR ) </code></pre></li> </ul> <p>So, the real question is: How can I speed up update/replace operations a bit more? (I think these findings might be 'good enough', but I don't want to give up without tapping the SO crowd :)</p> <p>Also anyones hints towards a more elegant replace_item(), or evidence that my tests are completely broken would be most welcome.</p> <p>The test script is available <a href="http://fnord.se/perftest.py">here</a> if you'd like to attempt to reproduce. Remember to check it first though...it WorksForMe, but...</p> <p>You will need to edit the db.connect() line to suit your setup.</p> <p><strong>EDIT</strong></p> <p>Thanks to andres in #postgresql @ freenode I have another test with a single-query update; much like a multi-row insert (listed as update_andres above).</p> <pre><code>UPDATE item SET a0=i.a0, a1=i.a1, a2=i.a2 FROM (VALUES ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ... ) AS i(key, a0, a1, a2) WHERE item.key=i.key::macaddr </code></pre> <p><strong>EDIT</strong></p> <p>Thanks to merlin83 in #postgresql @ freenode and jug/jwp below I have another test with an insert-to-temp/delete/insert approach (listed as "update_merlin83 (i/d/i)" above).</p> <pre><code>INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); DELETE FROM item USING temp_item WHERE item.key=temp_item.key; INSERT INTO item (key, a0, a1, a2) SELECT key, a0, a1, a2 FROM temp_item; </code></pre> <p>My gut feeling is that these tests are not very representative to the performance in the real-world scenario, but I think the differences are great enough to give an indication of the most promising approaches for further investigation. The perftest.py script contains all updates as well for those of you who want to check it out. It's fairly ugly though, so don't forget your goggles :)</p> <p><strong>EDIT</strong></p> <p>andres in #postgresql @ freenode pointed out that I should test with an insert-to-temp/update variant (listed as "update_merlin83 (i/u)" above).</p> <pre><code>INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); UPDATE item SET a0=temp_item.a0, a1=temp_item.a1, a2=temp_item.a2 FROM temp_item WHERE item.key=temp_item.key </code></pre> <p><strong>EDIT</strong></p> <p>Probably final edit: I changed my script to match our load scenario better, and it seems the numbers hold even when scaling things up a bit and adding some randomness. If anyone gets very different numbers from some other scenario I'd be interested in knowing about it.</p>
19
2009-06-07T17:28:56Z
962,379
<p>In your <code>insert_or_replace</code>. try this:</p> <pre><code>WHERE EXISTS(SELECT 1 FROM item WHERE key=NEW.key LIMIT 1) </code></pre> <p>instead of</p> <pre><code>WHERE EXISTS(SELECT 1 FROM item WHERE key=NEW.key) </code></pre> <p>As noted in comments, that will probably do nothing. All I have to add, then, is that you can always speed up INSERT/UPDATE performance by removing indexes. This will likely not be something you want to do unless you find your table is overindexed, but that should at least be checked out.</p>
1
2009-06-07T17:39:09Z
[ "python", "sql", "postgresql", "psycopg2" ]
How can I speed up update/replace operations in PostgreSQL?
962,361
<p>We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects).</p> <p>For sanity reasons we have created our own <a href="http://martinfowler.com/eaaCatalog/dataMapper.html">Data Mapper</a>-like layer that works reasonably well, but it has one big bottleneck, the update performance. Of course, I'm not expecting the update/replace scenario to be as speedy as the 'insert to an empty table' one, but it would be nice to get a bit closer.</p> <p>Note that this system is free from concurrent updates</p> <p>We always set all the fields of each rows on an update, which can be seen in the terminology where I use the word 'replace' in my tests. I've so far tried two approaches to our update problem:</p> <ol> <li><p>Create a <code>replace()</code> procedure that takes an array of rows to update:</p> <pre><code>CREATE OR REPLACE FUNCTION replace_item(data item[]) RETURNS VOID AS $$ BEGIN FOR i IN COALESCE(array_lower(data,1),0) .. COALESCE(array_upper(data,1),-1) LOOP UPDATE item SET a0=data[i].a0,a1=data[i].a1,a2=data[i].a2 WHERE key=data[i].key; END LOOP; END; $$ LANGUAGE plpgsql </code></pre></li> <li><p>Create an <code>insert_or_replace</code> rule so that everything but the occasional delete becomes multi-row inserts</p> <pre><code>CREATE RULE "insert_or_replace" AS ON INSERT TO "item" WHERE EXISTS(SELECT 1 FROM item WHERE key=NEW.key) DO INSTEAD (UPDATE item SET a0=NEW.a0,a1=NEW.a1,a2=NEW.a2 WHERE key=NEW.key); </code></pre></li> </ol> <p>These both speeds up the updates a fair bit, although the latter slows down inserts a bit: </p> <pre><code>Multi-row insert : 50000 items inserted in 1.32 seconds averaging 37807.84 items/s executemany() update : 50000 items updated in 26.67 seconds averaging 1874.57 items/s update_andres : 50000 items updated in 3.84 seconds averaging 13028.51 items/s update_merlin83 (i/d/i) : 50000 items updated in 1.29 seconds averaging 38780.46 items/s update_merlin83 (i/u) : 50000 items updated in 1.24 seconds averaging 40313.28 items/s replace_item() procedure : 50000 items replaced in 3.10 seconds averaging 16151.42 items/s Multi-row insert_or_replace: 50000 items inserted in 2.73 seconds averaging 18296.30 items/s Multi-row insert_or_replace: 50000 items replaced in 2.02 seconds averaging 24729.94 items/s </code></pre> <p>Random notes about the test run:</p> <ul> <li>All tests are run on the same computer as the database resides; connecting to localhost.</li> <li>Inserts and updates are applied to the database in batches of of 500 items, each sent in its own transaction (<strong>UPDATED</strong>).</li> <li>All update/replace tests used the same values as were already in the database.</li> <li>All data was escaped using the psycopg2 adapt() function.</li> <li>All tables are truncated and vacuumed before use (<strong>ADDED</strong>, in previous runs only truncation happened)</li> <li><p>The table looks like this:</p> <pre><code>CREATE TABLE item ( key MACADDR PRIMARY KEY, a0 VARCHAR, a1 VARCHAR, a2 VARCHAR ) </code></pre></li> </ul> <p>So, the real question is: How can I speed up update/replace operations a bit more? (I think these findings might be 'good enough', but I don't want to give up without tapping the SO crowd :)</p> <p>Also anyones hints towards a more elegant replace_item(), or evidence that my tests are completely broken would be most welcome.</p> <p>The test script is available <a href="http://fnord.se/perftest.py">here</a> if you'd like to attempt to reproduce. Remember to check it first though...it WorksForMe, but...</p> <p>You will need to edit the db.connect() line to suit your setup.</p> <p><strong>EDIT</strong></p> <p>Thanks to andres in #postgresql @ freenode I have another test with a single-query update; much like a multi-row insert (listed as update_andres above).</p> <pre><code>UPDATE item SET a0=i.a0, a1=i.a1, a2=i.a2 FROM (VALUES ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ... ) AS i(key, a0, a1, a2) WHERE item.key=i.key::macaddr </code></pre> <p><strong>EDIT</strong></p> <p>Thanks to merlin83 in #postgresql @ freenode and jug/jwp below I have another test with an insert-to-temp/delete/insert approach (listed as "update_merlin83 (i/d/i)" above).</p> <pre><code>INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); DELETE FROM item USING temp_item WHERE item.key=temp_item.key; INSERT INTO item (key, a0, a1, a2) SELECT key, a0, a1, a2 FROM temp_item; </code></pre> <p>My gut feeling is that these tests are not very representative to the performance in the real-world scenario, but I think the differences are great enough to give an indication of the most promising approaches for further investigation. The perftest.py script contains all updates as well for those of you who want to check it out. It's fairly ugly though, so don't forget your goggles :)</p> <p><strong>EDIT</strong></p> <p>andres in #postgresql @ freenode pointed out that I should test with an insert-to-temp/update variant (listed as "update_merlin83 (i/u)" above).</p> <pre><code>INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); UPDATE item SET a0=temp_item.a0, a1=temp_item.a1, a2=temp_item.a2 FROM temp_item WHERE item.key=temp_item.key </code></pre> <p><strong>EDIT</strong></p> <p>Probably final edit: I changed my script to match our load scenario better, and it seems the numbers hold even when scaling things up a bit and adding some randomness. If anyone gets very different numbers from some other scenario I'd be interested in knowing about it.</p>
19
2009-06-07T17:28:56Z
962,430
<p>In Oracle, locking the table would definitely help. You might want to try that with PostgreSQL, too.</p>
1
2009-06-07T18:05:02Z
[ "python", "sql", "postgresql", "psycopg2" ]
How can I speed up update/replace operations in PostgreSQL?
962,361
<p>We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects).</p> <p>For sanity reasons we have created our own <a href="http://martinfowler.com/eaaCatalog/dataMapper.html">Data Mapper</a>-like layer that works reasonably well, but it has one big bottleneck, the update performance. Of course, I'm not expecting the update/replace scenario to be as speedy as the 'insert to an empty table' one, but it would be nice to get a bit closer.</p> <p>Note that this system is free from concurrent updates</p> <p>We always set all the fields of each rows on an update, which can be seen in the terminology where I use the word 'replace' in my tests. I've so far tried two approaches to our update problem:</p> <ol> <li><p>Create a <code>replace()</code> procedure that takes an array of rows to update:</p> <pre><code>CREATE OR REPLACE FUNCTION replace_item(data item[]) RETURNS VOID AS $$ BEGIN FOR i IN COALESCE(array_lower(data,1),0) .. COALESCE(array_upper(data,1),-1) LOOP UPDATE item SET a0=data[i].a0,a1=data[i].a1,a2=data[i].a2 WHERE key=data[i].key; END LOOP; END; $$ LANGUAGE plpgsql </code></pre></li> <li><p>Create an <code>insert_or_replace</code> rule so that everything but the occasional delete becomes multi-row inserts</p> <pre><code>CREATE RULE "insert_or_replace" AS ON INSERT TO "item" WHERE EXISTS(SELECT 1 FROM item WHERE key=NEW.key) DO INSTEAD (UPDATE item SET a0=NEW.a0,a1=NEW.a1,a2=NEW.a2 WHERE key=NEW.key); </code></pre></li> </ol> <p>These both speeds up the updates a fair bit, although the latter slows down inserts a bit: </p> <pre><code>Multi-row insert : 50000 items inserted in 1.32 seconds averaging 37807.84 items/s executemany() update : 50000 items updated in 26.67 seconds averaging 1874.57 items/s update_andres : 50000 items updated in 3.84 seconds averaging 13028.51 items/s update_merlin83 (i/d/i) : 50000 items updated in 1.29 seconds averaging 38780.46 items/s update_merlin83 (i/u) : 50000 items updated in 1.24 seconds averaging 40313.28 items/s replace_item() procedure : 50000 items replaced in 3.10 seconds averaging 16151.42 items/s Multi-row insert_or_replace: 50000 items inserted in 2.73 seconds averaging 18296.30 items/s Multi-row insert_or_replace: 50000 items replaced in 2.02 seconds averaging 24729.94 items/s </code></pre> <p>Random notes about the test run:</p> <ul> <li>All tests are run on the same computer as the database resides; connecting to localhost.</li> <li>Inserts and updates are applied to the database in batches of of 500 items, each sent in its own transaction (<strong>UPDATED</strong>).</li> <li>All update/replace tests used the same values as were already in the database.</li> <li>All data was escaped using the psycopg2 adapt() function.</li> <li>All tables are truncated and vacuumed before use (<strong>ADDED</strong>, in previous runs only truncation happened)</li> <li><p>The table looks like this:</p> <pre><code>CREATE TABLE item ( key MACADDR PRIMARY KEY, a0 VARCHAR, a1 VARCHAR, a2 VARCHAR ) </code></pre></li> </ul> <p>So, the real question is: How can I speed up update/replace operations a bit more? (I think these findings might be 'good enough', but I don't want to give up without tapping the SO crowd :)</p> <p>Also anyones hints towards a more elegant replace_item(), or evidence that my tests are completely broken would be most welcome.</p> <p>The test script is available <a href="http://fnord.se/perftest.py">here</a> if you'd like to attempt to reproduce. Remember to check it first though...it WorksForMe, but...</p> <p>You will need to edit the db.connect() line to suit your setup.</p> <p><strong>EDIT</strong></p> <p>Thanks to andres in #postgresql @ freenode I have another test with a single-query update; much like a multi-row insert (listed as update_andres above).</p> <pre><code>UPDATE item SET a0=i.a0, a1=i.a1, a2=i.a2 FROM (VALUES ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ... ) AS i(key, a0, a1, a2) WHERE item.key=i.key::macaddr </code></pre> <p><strong>EDIT</strong></p> <p>Thanks to merlin83 in #postgresql @ freenode and jug/jwp below I have another test with an insert-to-temp/delete/insert approach (listed as "update_merlin83 (i/d/i)" above).</p> <pre><code>INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); DELETE FROM item USING temp_item WHERE item.key=temp_item.key; INSERT INTO item (key, a0, a1, a2) SELECT key, a0, a1, a2 FROM temp_item; </code></pre> <p>My gut feeling is that these tests are not very representative to the performance in the real-world scenario, but I think the differences are great enough to give an indication of the most promising approaches for further investigation. The perftest.py script contains all updates as well for those of you who want to check it out. It's fairly ugly though, so don't forget your goggles :)</p> <p><strong>EDIT</strong></p> <p>andres in #postgresql @ freenode pointed out that I should test with an insert-to-temp/update variant (listed as "update_merlin83 (i/u)" above).</p> <pre><code>INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); UPDATE item SET a0=temp_item.a0, a1=temp_item.a1, a2=temp_item.a2 FROM temp_item WHERE item.key=temp_item.key </code></pre> <p><strong>EDIT</strong></p> <p>Probably final edit: I changed my script to match our load scenario better, and it seems the numbers hold even when scaling things up a bit and adding some randomness. If anyone gets very different numbers from some other scenario I'd be interested in knowing about it.</p>
19
2009-06-07T17:28:56Z
962,535
<p>I had a similar situation a few months ago and ended up getting the largest speed boost from a tuned chunk/transaction size. You may also want to check the log for a checkpoint warning during the test and tune appropriately. </p>
2
2009-06-07T18:55:14Z
[ "python", "sql", "postgresql", "psycopg2" ]
How can I speed up update/replace operations in PostgreSQL?
962,361
<p>We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects).</p> <p>For sanity reasons we have created our own <a href="http://martinfowler.com/eaaCatalog/dataMapper.html">Data Mapper</a>-like layer that works reasonably well, but it has one big bottleneck, the update performance. Of course, I'm not expecting the update/replace scenario to be as speedy as the 'insert to an empty table' one, but it would be nice to get a bit closer.</p> <p>Note that this system is free from concurrent updates</p> <p>We always set all the fields of each rows on an update, which can be seen in the terminology where I use the word 'replace' in my tests. I've so far tried two approaches to our update problem:</p> <ol> <li><p>Create a <code>replace()</code> procedure that takes an array of rows to update:</p> <pre><code>CREATE OR REPLACE FUNCTION replace_item(data item[]) RETURNS VOID AS $$ BEGIN FOR i IN COALESCE(array_lower(data,1),0) .. COALESCE(array_upper(data,1),-1) LOOP UPDATE item SET a0=data[i].a0,a1=data[i].a1,a2=data[i].a2 WHERE key=data[i].key; END LOOP; END; $$ LANGUAGE plpgsql </code></pre></li> <li><p>Create an <code>insert_or_replace</code> rule so that everything but the occasional delete becomes multi-row inserts</p> <pre><code>CREATE RULE "insert_or_replace" AS ON INSERT TO "item" WHERE EXISTS(SELECT 1 FROM item WHERE key=NEW.key) DO INSTEAD (UPDATE item SET a0=NEW.a0,a1=NEW.a1,a2=NEW.a2 WHERE key=NEW.key); </code></pre></li> </ol> <p>These both speeds up the updates a fair bit, although the latter slows down inserts a bit: </p> <pre><code>Multi-row insert : 50000 items inserted in 1.32 seconds averaging 37807.84 items/s executemany() update : 50000 items updated in 26.67 seconds averaging 1874.57 items/s update_andres : 50000 items updated in 3.84 seconds averaging 13028.51 items/s update_merlin83 (i/d/i) : 50000 items updated in 1.29 seconds averaging 38780.46 items/s update_merlin83 (i/u) : 50000 items updated in 1.24 seconds averaging 40313.28 items/s replace_item() procedure : 50000 items replaced in 3.10 seconds averaging 16151.42 items/s Multi-row insert_or_replace: 50000 items inserted in 2.73 seconds averaging 18296.30 items/s Multi-row insert_or_replace: 50000 items replaced in 2.02 seconds averaging 24729.94 items/s </code></pre> <p>Random notes about the test run:</p> <ul> <li>All tests are run on the same computer as the database resides; connecting to localhost.</li> <li>Inserts and updates are applied to the database in batches of of 500 items, each sent in its own transaction (<strong>UPDATED</strong>).</li> <li>All update/replace tests used the same values as were already in the database.</li> <li>All data was escaped using the psycopg2 adapt() function.</li> <li>All tables are truncated and vacuumed before use (<strong>ADDED</strong>, in previous runs only truncation happened)</li> <li><p>The table looks like this:</p> <pre><code>CREATE TABLE item ( key MACADDR PRIMARY KEY, a0 VARCHAR, a1 VARCHAR, a2 VARCHAR ) </code></pre></li> </ul> <p>So, the real question is: How can I speed up update/replace operations a bit more? (I think these findings might be 'good enough', but I don't want to give up without tapping the SO crowd :)</p> <p>Also anyones hints towards a more elegant replace_item(), or evidence that my tests are completely broken would be most welcome.</p> <p>The test script is available <a href="http://fnord.se/perftest.py">here</a> if you'd like to attempt to reproduce. Remember to check it first though...it WorksForMe, but...</p> <p>You will need to edit the db.connect() line to suit your setup.</p> <p><strong>EDIT</strong></p> <p>Thanks to andres in #postgresql @ freenode I have another test with a single-query update; much like a multi-row insert (listed as update_andres above).</p> <pre><code>UPDATE item SET a0=i.a0, a1=i.a1, a2=i.a2 FROM (VALUES ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ... ) AS i(key, a0, a1, a2) WHERE item.key=i.key::macaddr </code></pre> <p><strong>EDIT</strong></p> <p>Thanks to merlin83 in #postgresql @ freenode and jug/jwp below I have another test with an insert-to-temp/delete/insert approach (listed as "update_merlin83 (i/d/i)" above).</p> <pre><code>INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); DELETE FROM item USING temp_item WHERE item.key=temp_item.key; INSERT INTO item (key, a0, a1, a2) SELECT key, a0, a1, a2 FROM temp_item; </code></pre> <p>My gut feeling is that these tests are not very representative to the performance in the real-world scenario, but I think the differences are great enough to give an indication of the most promising approaches for further investigation. The perftest.py script contains all updates as well for those of you who want to check it out. It's fairly ugly though, so don't forget your goggles :)</p> <p><strong>EDIT</strong></p> <p>andres in #postgresql @ freenode pointed out that I should test with an insert-to-temp/update variant (listed as "update_merlin83 (i/u)" above).</p> <pre><code>INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); UPDATE item SET a0=temp_item.a0, a1=temp_item.a1, a2=temp_item.a2 FROM temp_item WHERE item.key=temp_item.key </code></pre> <p><strong>EDIT</strong></p> <p>Probably final edit: I changed my script to match our load scenario better, and it seems the numbers hold even when scaling things up a bit and adding some randomness. If anyone gets very different numbers from some other scenario I'd be interested in knowing about it.</p>
19
2009-06-07T17:28:56Z
962,688
<p>Sounds like you'd see benefits from using WAL (Write Ahead Logging) with a UPS to cache your updates between disk writes.</p> <blockquote> <p>wal_buffers This setting decides the number of buffers WAL(Write ahead Log) can have. If your database has many write transactions, setting this value bit higher than default could result better usage of disk space. Experiment and decide. A good start would be around 32-64 corresponding to 256-512K memory. </p> </blockquote> <p><a href="http://www.varlena.com/GeneralBits/Tidbits/perf.html" rel="nofollow">http://www.varlena.com/GeneralBits/Tidbits/perf.html</a></p>
2
2009-06-07T19:59:32Z
[ "python", "sql", "postgresql", "psycopg2" ]
How can I speed up update/replace operations in PostgreSQL?
962,361
<p>We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects).</p> <p>For sanity reasons we have created our own <a href="http://martinfowler.com/eaaCatalog/dataMapper.html">Data Mapper</a>-like layer that works reasonably well, but it has one big bottleneck, the update performance. Of course, I'm not expecting the update/replace scenario to be as speedy as the 'insert to an empty table' one, but it would be nice to get a bit closer.</p> <p>Note that this system is free from concurrent updates</p> <p>We always set all the fields of each rows on an update, which can be seen in the terminology where I use the word 'replace' in my tests. I've so far tried two approaches to our update problem:</p> <ol> <li><p>Create a <code>replace()</code> procedure that takes an array of rows to update:</p> <pre><code>CREATE OR REPLACE FUNCTION replace_item(data item[]) RETURNS VOID AS $$ BEGIN FOR i IN COALESCE(array_lower(data,1),0) .. COALESCE(array_upper(data,1),-1) LOOP UPDATE item SET a0=data[i].a0,a1=data[i].a1,a2=data[i].a2 WHERE key=data[i].key; END LOOP; END; $$ LANGUAGE plpgsql </code></pre></li> <li><p>Create an <code>insert_or_replace</code> rule so that everything but the occasional delete becomes multi-row inserts</p> <pre><code>CREATE RULE "insert_or_replace" AS ON INSERT TO "item" WHERE EXISTS(SELECT 1 FROM item WHERE key=NEW.key) DO INSTEAD (UPDATE item SET a0=NEW.a0,a1=NEW.a1,a2=NEW.a2 WHERE key=NEW.key); </code></pre></li> </ol> <p>These both speeds up the updates a fair bit, although the latter slows down inserts a bit: </p> <pre><code>Multi-row insert : 50000 items inserted in 1.32 seconds averaging 37807.84 items/s executemany() update : 50000 items updated in 26.67 seconds averaging 1874.57 items/s update_andres : 50000 items updated in 3.84 seconds averaging 13028.51 items/s update_merlin83 (i/d/i) : 50000 items updated in 1.29 seconds averaging 38780.46 items/s update_merlin83 (i/u) : 50000 items updated in 1.24 seconds averaging 40313.28 items/s replace_item() procedure : 50000 items replaced in 3.10 seconds averaging 16151.42 items/s Multi-row insert_or_replace: 50000 items inserted in 2.73 seconds averaging 18296.30 items/s Multi-row insert_or_replace: 50000 items replaced in 2.02 seconds averaging 24729.94 items/s </code></pre> <p>Random notes about the test run:</p> <ul> <li>All tests are run on the same computer as the database resides; connecting to localhost.</li> <li>Inserts and updates are applied to the database in batches of of 500 items, each sent in its own transaction (<strong>UPDATED</strong>).</li> <li>All update/replace tests used the same values as were already in the database.</li> <li>All data was escaped using the psycopg2 adapt() function.</li> <li>All tables are truncated and vacuumed before use (<strong>ADDED</strong>, in previous runs only truncation happened)</li> <li><p>The table looks like this:</p> <pre><code>CREATE TABLE item ( key MACADDR PRIMARY KEY, a0 VARCHAR, a1 VARCHAR, a2 VARCHAR ) </code></pre></li> </ul> <p>So, the real question is: How can I speed up update/replace operations a bit more? (I think these findings might be 'good enough', but I don't want to give up without tapping the SO crowd :)</p> <p>Also anyones hints towards a more elegant replace_item(), or evidence that my tests are completely broken would be most welcome.</p> <p>The test script is available <a href="http://fnord.se/perftest.py">here</a> if you'd like to attempt to reproduce. Remember to check it first though...it WorksForMe, but...</p> <p>You will need to edit the db.connect() line to suit your setup.</p> <p><strong>EDIT</strong></p> <p>Thanks to andres in #postgresql @ freenode I have another test with a single-query update; much like a multi-row insert (listed as update_andres above).</p> <pre><code>UPDATE item SET a0=i.a0, a1=i.a1, a2=i.a2 FROM (VALUES ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ... ) AS i(key, a0, a1, a2) WHERE item.key=i.key::macaddr </code></pre> <p><strong>EDIT</strong></p> <p>Thanks to merlin83 in #postgresql @ freenode and jug/jwp below I have another test with an insert-to-temp/delete/insert approach (listed as "update_merlin83 (i/d/i)" above).</p> <pre><code>INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); DELETE FROM item USING temp_item WHERE item.key=temp_item.key; INSERT INTO item (key, a0, a1, a2) SELECT key, a0, a1, a2 FROM temp_item; </code></pre> <p>My gut feeling is that these tests are not very representative to the performance in the real-world scenario, but I think the differences are great enough to give an indication of the most promising approaches for further investigation. The perftest.py script contains all updates as well for those of you who want to check it out. It's fairly ugly though, so don't forget your goggles :)</p> <p><strong>EDIT</strong></p> <p>andres in #postgresql @ freenode pointed out that I should test with an insert-to-temp/update variant (listed as "update_merlin83 (i/u)" above).</p> <pre><code>INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); UPDATE item SET a0=temp_item.a0, a1=temp_item.a1, a2=temp_item.a2 FROM temp_item WHERE item.key=temp_item.key </code></pre> <p><strong>EDIT</strong></p> <p>Probably final edit: I changed my script to match our load scenario better, and it seems the numbers hold even when scaling things up a bit and adding some randomness. If anyone gets very different numbers from some other scenario I'd be interested in knowing about it.</p>
19
2009-06-07T17:28:56Z
962,699
<p>The usual way I do these things in pg is: load raw data matching target table into temp table (no constraints) using copy, merge(the fun part), profit.</p> <p>I wrote a merge_by_key function specifically for these situations:</p> <p><a href="http://mbk.projects.postgresql.org/" rel="nofollow">http://mbk.projects.postgresql.org/</a></p> <p>The docs aren't terribly friendly, but I'd suggest giving it a <em>good</em> look.</p>
4
2009-06-07T20:01:59Z
[ "python", "sql", "postgresql", "psycopg2" ]
How can I speed up update/replace operations in PostgreSQL?
962,361
<p>We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects).</p> <p>For sanity reasons we have created our own <a href="http://martinfowler.com/eaaCatalog/dataMapper.html">Data Mapper</a>-like layer that works reasonably well, but it has one big bottleneck, the update performance. Of course, I'm not expecting the update/replace scenario to be as speedy as the 'insert to an empty table' one, but it would be nice to get a bit closer.</p> <p>Note that this system is free from concurrent updates</p> <p>We always set all the fields of each rows on an update, which can be seen in the terminology where I use the word 'replace' in my tests. I've so far tried two approaches to our update problem:</p> <ol> <li><p>Create a <code>replace()</code> procedure that takes an array of rows to update:</p> <pre><code>CREATE OR REPLACE FUNCTION replace_item(data item[]) RETURNS VOID AS $$ BEGIN FOR i IN COALESCE(array_lower(data,1),0) .. COALESCE(array_upper(data,1),-1) LOOP UPDATE item SET a0=data[i].a0,a1=data[i].a1,a2=data[i].a2 WHERE key=data[i].key; END LOOP; END; $$ LANGUAGE plpgsql </code></pre></li> <li><p>Create an <code>insert_or_replace</code> rule so that everything but the occasional delete becomes multi-row inserts</p> <pre><code>CREATE RULE "insert_or_replace" AS ON INSERT TO "item" WHERE EXISTS(SELECT 1 FROM item WHERE key=NEW.key) DO INSTEAD (UPDATE item SET a0=NEW.a0,a1=NEW.a1,a2=NEW.a2 WHERE key=NEW.key); </code></pre></li> </ol> <p>These both speeds up the updates a fair bit, although the latter slows down inserts a bit: </p> <pre><code>Multi-row insert : 50000 items inserted in 1.32 seconds averaging 37807.84 items/s executemany() update : 50000 items updated in 26.67 seconds averaging 1874.57 items/s update_andres : 50000 items updated in 3.84 seconds averaging 13028.51 items/s update_merlin83 (i/d/i) : 50000 items updated in 1.29 seconds averaging 38780.46 items/s update_merlin83 (i/u) : 50000 items updated in 1.24 seconds averaging 40313.28 items/s replace_item() procedure : 50000 items replaced in 3.10 seconds averaging 16151.42 items/s Multi-row insert_or_replace: 50000 items inserted in 2.73 seconds averaging 18296.30 items/s Multi-row insert_or_replace: 50000 items replaced in 2.02 seconds averaging 24729.94 items/s </code></pre> <p>Random notes about the test run:</p> <ul> <li>All tests are run on the same computer as the database resides; connecting to localhost.</li> <li>Inserts and updates are applied to the database in batches of of 500 items, each sent in its own transaction (<strong>UPDATED</strong>).</li> <li>All update/replace tests used the same values as were already in the database.</li> <li>All data was escaped using the psycopg2 adapt() function.</li> <li>All tables are truncated and vacuumed before use (<strong>ADDED</strong>, in previous runs only truncation happened)</li> <li><p>The table looks like this:</p> <pre><code>CREATE TABLE item ( key MACADDR PRIMARY KEY, a0 VARCHAR, a1 VARCHAR, a2 VARCHAR ) </code></pre></li> </ul> <p>So, the real question is: How can I speed up update/replace operations a bit more? (I think these findings might be 'good enough', but I don't want to give up without tapping the SO crowd :)</p> <p>Also anyones hints towards a more elegant replace_item(), or evidence that my tests are completely broken would be most welcome.</p> <p>The test script is available <a href="http://fnord.se/perftest.py">here</a> if you'd like to attempt to reproduce. Remember to check it first though...it WorksForMe, but...</p> <p>You will need to edit the db.connect() line to suit your setup.</p> <p><strong>EDIT</strong></p> <p>Thanks to andres in #postgresql @ freenode I have another test with a single-query update; much like a multi-row insert (listed as update_andres above).</p> <pre><code>UPDATE item SET a0=i.a0, a1=i.a1, a2=i.a2 FROM (VALUES ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ... ) AS i(key, a0, a1, a2) WHERE item.key=i.key::macaddr </code></pre> <p><strong>EDIT</strong></p> <p>Thanks to merlin83 in #postgresql @ freenode and jug/jwp below I have another test with an insert-to-temp/delete/insert approach (listed as "update_merlin83 (i/d/i)" above).</p> <pre><code>INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); DELETE FROM item USING temp_item WHERE item.key=temp_item.key; INSERT INTO item (key, a0, a1, a2) SELECT key, a0, a1, a2 FROM temp_item; </code></pre> <p>My gut feeling is that these tests are not very representative to the performance in the real-world scenario, but I think the differences are great enough to give an indication of the most promising approaches for further investigation. The perftest.py script contains all updates as well for those of you who want to check it out. It's fairly ugly though, so don't forget your goggles :)</p> <p><strong>EDIT</strong></p> <p>andres in #postgresql @ freenode pointed out that I should test with an insert-to-temp/update variant (listed as "update_merlin83 (i/u)" above).</p> <pre><code>INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); UPDATE item SET a0=temp_item.a0, a1=temp_item.a1, a2=temp_item.a2 FROM temp_item WHERE item.key=temp_item.key </code></pre> <p><strong>EDIT</strong></p> <p>Probably final edit: I changed my script to match our load scenario better, and it seems the numbers hold even when scaling things up a bit and adding some randomness. If anyone gets very different numbers from some other scenario I'd be interested in knowing about it.</p>
19
2009-06-07T17:28:56Z
3,520,889
<p>For updates, you can lower your fillfactor for the tables and the indexes and that might help</p> <p><a href="http://www.postgresql.org/docs/current/static/sql-createtable.html" rel="nofollow">http://www.postgresql.org/docs/current/static/sql-createtable.html</a></p> <p><a href="http://www.postgresql.org/docs/current/static/sql-createindex.html" rel="nofollow">http://www.postgresql.org/docs/current/static/sql-createindex.html</a></p>
1
2010-08-19T10:34:02Z
[ "python", "sql", "postgresql", "psycopg2" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) causes me some trouble. I can ofc code it in my view, to something like this:</p> <pre><code>number_of_records = models.Painting.objects.count() random_index = int(random.random()*number_of_records)+1 random_paint = models.Painting.get(pk = random_index) </code></pre> <p>It doesn't look like something I'd like to have in my view tho - this is entirely part of database abstraction and should be in the model. Also, here I need to take care of removed records (then number of all records won't cover me all the possible key values) and probably lots of other things.</p> <p>Any other options how I can do it, preferably somehow inside the model abstraction?</p>
109
2009-06-07T19:25:15Z
962,662
<p>You could create a <a href="http://docs.djangoproject.com/en/dev/topics/db/managers/" rel="nofollow">manager</a> on your model to do this sort of thing. To first understand what a manager is, the <code>Painting.objects</code> method is a manager that contains <code>all()</code>, <code>filter()</code>, <code>get()</code>, etc. Creating your own manager allows you to pre-filter results and have all these same methods, as well as your own custom methods, work on the results.</p> <p><strong>EDIT</strong>: I modified my code to reflect the <code>order_by['?']</code> method. Note that the manager returns an unlimited number of random models. Because of this I've included a bit of usage code to show how to get just a single model.</p> <pre><code>from django.db import models class RandomManager(models.Manager): def get_query_set(self): return super(RandomManager, self).get_query_set().order_by('?') class Painting(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=50) objects = models.Manager() # The default manager. randoms = RandomManager() # The random-specific manager. </code></pre> <p><strong>Usage</strong></p> <pre><code>random_painting = Painting.randoms.all()[0] </code></pre> <p>Lastly, you can have many managers on your models, so feel free to create a <code>LeastViewsManager()</code> or <code>MostPopularManager()</code>.</p>
8
2009-06-07T19:49:53Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) causes me some trouble. I can ofc code it in my view, to something like this:</p> <pre><code>number_of_records = models.Painting.objects.count() random_index = int(random.random()*number_of_records)+1 random_paint = models.Painting.get(pk = random_index) </code></pre> <p>It doesn't look like something I'd like to have in my view tho - this is entirely part of database abstraction and should be in the model. Also, here I need to take care of removed records (then number of all records won't cover me all the possible key values) and probably lots of other things.</p> <p>Any other options how I can do it, preferably somehow inside the model abstraction?</p>
109
2009-06-07T19:25:15Z
962,672
<p>Simply use:</p> <pre><code>MyModel.objects.order_by('?').first() </code></pre> <p>It is documented in <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by-fields">QuerySet API</a>.</p>
174
2009-06-07T19:54:50Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) causes me some trouble. I can ofc code it in my view, to something like this:</p> <pre><code>number_of_records = models.Painting.objects.count() random_index = int(random.random()*number_of_records)+1 random_paint = models.Painting.get(pk = random_index) </code></pre> <p>It doesn't look like something I'd like to have in my view tho - this is entirely part of database abstraction and should be in the model. Also, here I need to take care of removed records (then number of all records won't cover me all the possible key values) and probably lots of other things.</p> <p>Any other options how I can do it, preferably somehow inside the model abstraction?</p>
109
2009-06-07T19:25:15Z
962,675
<p>You could simply do:</p> <pre><code>models.Painting.objects.all().order_by('?')[:1].get() </code></pre> <p>which is much more efficient.</p>
5
2009-06-07T19:55:38Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) causes me some trouble. I can ofc code it in my view, to something like this:</p> <pre><code>number_of_records = models.Painting.objects.count() random_index = int(random.random()*number_of_records)+1 random_paint = models.Painting.get(pk = random_index) </code></pre> <p>It doesn't look like something I'd like to have in my view tho - this is entirely part of database abstraction and should be in the model. Also, here I need to take care of removed records (then number of all records won't cover me all the possible key values) and probably lots of other things.</p> <p>Any other options how I can do it, preferably somehow inside the model abstraction?</p>
109
2009-06-07T19:25:15Z
971,671
<p>The solutions with order_by('?')[:N] are extremely slow even for medium-sized tables if you use MySQL (don't know about other databases).</p> <p><code>order_by('?')[:N]</code> will be translated to <code>SELECT ... FROM ... WHERE ... ORDER BY RAND() LIMIT N</code> query.</p> <p>It means that for every row in table the RAND() function will be executed, then the whole table will be sorted according to value of this function and then first N records will be returned. If your tables are small, this is fine. But in most cases this is a very slow query.</p> <p>I wrote simple function that works even if id's have holes (some rows where deleted):</p> <pre><code>def get_random_item(model, max_id=None): if max_id is None: max_id = model.objects.aggregate(Max('id')).values()[0] min_id = math.ceil(max_id*random.random()) return model.objects.filter(id__gte=min_id)[0] </code></pre> <p>It is faster than order_by('?') in almost all cases. </p>
23
2009-06-09T18:16:49Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) causes me some trouble. I can ofc code it in my view, to something like this:</p> <pre><code>number_of_records = models.Painting.objects.count() random_index = int(random.random()*number_of_records)+1 random_paint = models.Painting.get(pk = random_index) </code></pre> <p>It doesn't look like something I'd like to have in my view tho - this is entirely part of database abstraction and should be in the model. Also, here I need to take care of removed records (then number of all records won't cover me all the possible key values) and probably lots of other things.</p> <p>Any other options how I can do it, preferably somehow inside the model abstraction?</p>
109
2009-06-07T19:25:15Z
2,118,712
<p>Using <code>order_by('?')</code> will kill the db server on the second day in production. A better way is something like what is described in <a href="http://web.archive.org/web/20110802060451/http://bolddream.com/2010/01/22/getting-a-random-row-from-a-relational-database/">Getting a random row from a relational database</a>.</p> <pre><code>from django.db.models.aggregates import Count from random import randint class PaintingManager(models.Manager): def random(self): count = self.aggregate(count=Count('id'))['count'] random_index = randint(0, count - 1) return self.all()[random_index] </code></pre>
79
2010-01-22T16:27:08Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) causes me some trouble. I can ofc code it in my view, to something like this:</p> <pre><code>number_of_records = models.Painting.objects.count() random_index = int(random.random()*number_of_records)+1 random_paint = models.Painting.get(pk = random_index) </code></pre> <p>It doesn't look like something I'd like to have in my view tho - this is entirely part of database abstraction and should be in the model. Also, here I need to take care of removed records (then number of all records won't cover me all the possible key values) and probably lots of other things.</p> <p>Any other options how I can do it, preferably somehow inside the model abstraction?</p>
109
2009-06-07T19:25:15Z
10,530,328
<p>This is Highly recomended <s><a href="http://bolddream.com/2010/01/22/getting-a-random-row-from-a-relational-database/" rel="nofollow">Getting a random row from a relational database</a></s></p> <p>Because using django orm to do such a thing like that, will makes your db server angry specially if you have big data table :|</p> <p>And the solution is provide a Model Manager and write the SQL query by hand ;)</p> <p><strong>Update</strong>:</p> <p>Another solution which works on any database backend even non-rel ones without writing custom <code>ModelManager</code>. <a href="http://elpenia.wordpress.com/2010/05/11/getting-random-objects-from-a-queryset-in-django/" rel="nofollow">Getting Random objects from a Queryset in Django</a></p>
1
2012-05-10T08:38:57Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) causes me some trouble. I can ofc code it in my view, to something like this:</p> <pre><code>number_of_records = models.Painting.objects.count() random_index = int(random.random()*number_of_records)+1 random_paint = models.Painting.get(pk = random_index) </code></pre> <p>It doesn't look like something I'd like to have in my view tho - this is entirely part of database abstraction and should be in the model. Also, here I need to take care of removed records (then number of all records won't cover me all the possible key values) and probably lots of other things.</p> <p>Any other options how I can do it, preferably somehow inside the model abstraction?</p>
109
2009-06-07T19:25:15Z
10,836,811
<p>Just to note a (fairly common) special case, if there is a indexed auto-increment column in the table with no deletes, the optimum way to do a random select is a query like:</p> <pre><code>SELECT * FROM table WHERE id = RAND() LIMIT 1 </code></pre> <p>that assumes such a column named id for table. In django you can do this by:</p> <pre><code>Painting.objects.raw('SELECT * FROM appname_painting WHERE id = RAND() LIMIT 1') </code></pre> <p>in which you must replace appname with your application name.</p> <p>In General, with an id column, the order_by('?') can be done much faster with:</p> <pre><code>Paiting.objects.raw( 'SELECT * FROM auth_user WHERE id&gt;=RAND() * (SELECT MAX(id) FROM auth_user) LIMIT %d' % needed_count) </code></pre>
0
2012-05-31T15:39:13Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) causes me some trouble. I can ofc code it in my view, to something like this:</p> <pre><code>number_of_records = models.Painting.objects.count() random_index = int(random.random()*number_of_records)+1 random_paint = models.Painting.get(pk = random_index) </code></pre> <p>It doesn't look like something I'd like to have in my view tho - this is entirely part of database abstraction and should be in the model. Also, here I need to take care of removed records (then number of all records won't cover me all the possible key values) and probably lots of other things.</p> <p>Any other options how I can do it, preferably somehow inside the model abstraction?</p>
109
2009-06-07T19:25:15Z
30,741,675
<p>Just a simple idea how I do it:</p> <pre><code>def _get_random_service(self, professional): services = Service.objects.filter(professional=professional) i = randint(0, services.count()-1) return services[i] </code></pre>
0
2015-06-09T19:58:13Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) causes me some trouble. I can ofc code it in my view, to something like this:</p> <pre><code>number_of_records = models.Painting.objects.count() random_index = int(random.random()*number_of_records)+1 random_paint = models.Painting.get(pk = random_index) </code></pre> <p>It doesn't look like something I'd like to have in my view tho - this is entirely part of database abstraction and should be in the model. Also, here I need to take care of removed records (then number of all records won't cover me all the possible key values) and probably lots of other things.</p> <p>Any other options how I can do it, preferably somehow inside the model abstraction?</p>
109
2009-06-07T19:25:15Z
32,537,380
<p>The other answers are either potentially slow (using <code>order_by('?')</code>) or use more than one SQL query. Here's a sample solution with no ordering and just one query (assuming Postgres):</p> <pre class="lang-py prettyprint-override"><code>Model.objects.raw(''' select * from {0} limit 1 offset floor(random() * (select count(*) from {0})) '''.format(Model._meta.db_table))[0] </code></pre> <p>Be aware that this will raise an index error if the table is empty. Write yourself a model-agnostic helper function to check for that.</p>
0
2015-09-12T09:43:56Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) causes me some trouble. I can ofc code it in my view, to something like this:</p> <pre><code>number_of_records = models.Painting.objects.count() random_index = int(random.random()*number_of_records)+1 random_paint = models.Painting.get(pk = random_index) </code></pre> <p>It doesn't look like something I'd like to have in my view tho - this is entirely part of database abstraction and should be in the model. Also, here I need to take care of removed records (then number of all records won't cover me all the possible key values) and probably lots of other things.</p> <p>Any other options how I can do it, preferably somehow inside the model abstraction?</p>
109
2009-06-07T19:25:15Z
34,099,143
<p>You may want to use the <a href="http://stackoverflow.com/a/12583436/623735">same approach</a> that you'd use to sample any iterator, especially if you plan to sample multiple items to create a <em>sample set</em>. @MatijnPieters and @DzinX put a lot of thought into this:</p> <pre><code>def random_sampling(qs, N=1): """Sample any iterable (like a Django QuerySet) to retrieve N random elements Arguments: qs (iterable): Any iterable (like a Django QuerySet) N (int): Number of samples to retrieve at random from the iterable References: @DZinX: http://stackoverflow.com/a/12583436/623735 @MartinPieters: http://stackoverflow.com/a/12581484/623735 """ samples = [] iterator = iter(qs) # Get the first `N` elements and put them in your results list to preallocate memory try: for _ in xrange(N): samples.append(iterator.next()) except StopIteration: raise ValueError("N, the number of reuested samples, is larger than the length of the iterable.") random.shuffle(samples) # Randomize your list of N objects # Now replace each element by a truly random sample for i, v in enumerate(qs, N): r = random.randint(0, i) if r &lt; N: samples[r] = v # at a decreasing rate, replace random items return samples </code></pre>
0
2015-12-04T23:22:05Z
[ "python", "django", "django-models" ]
PyQt - QLabel inheriting
962,640
<p>i wanna inherit QLabel to add there click event processing. I'm trying this code:</p> <pre><code>class NewLabel(QtGui.QLabel): def __init__(self, parent): QtGui.QLabel.__init__(self, parent) def clickEvent(self, event): print 'Label clicked!' </code></pre> <p>But after clicking I have no line 'Label clicked!'</p> <p><strong>EDIT:</strong></p> <p>Okay, now I'm using not 'clickEvent' but 'mousePressEvent'. And I still have a question. How can i know what exactly label was clicked? For example, i have 2 edit box and 2 labels. Labels content are pixmaps. So there aren't any text in labels, so i can't discern difference between labels. How can i do that?</p> <p><strong>EDIT2:</strong> I made this code:</p> <pre><code>class NewLabel(QtGui.QLabel): def __init__(self, firstLabel): QtGui.QLabel.__init__(self, firstLabel) def mousePressEvent(self, event): print 'Clicked' #myLabel = self.sender() # None =) self.emit(QtCore.SIGNAL('clicked()'), "Label pressed") </code></pre> <p>In another class:</p> <pre><code>self.FirstLang = NewLabel(Form) QtCore.QObject.connect(self.FirstLang, QtCore.SIGNAL('clicked()'), self.labelPressed) </code></pre> <p>Slot in the same class:</p> <pre><code>def labelPressed(self): print 'in labelPressed' print self.sender() </code></pre> <p>But there isn't sender object in self. What i did wrong?</p>
2
2009-06-07T19:38:54Z
962,726
<p>There is no function <code>clickEvent</code> in QWidget/QLabel. You could connect that function to a Qt signal, or you could do:</p> <pre><code>class NewLabel(QtGui.QLabel): def __init__(self, parent=None): QtGui.QLabel.__init__(self, parent) self.setText('Lorem Ipsum') def mouseReleaseEvent(self, event): print 'Label clicked!' </code></pre>
1
2009-06-07T20:15:51Z
[ "python", "qt", "inheritance", "pyqt", "label" ]
PyQt - QLabel inheriting
962,640
<p>i wanna inherit QLabel to add there click event processing. I'm trying this code:</p> <pre><code>class NewLabel(QtGui.QLabel): def __init__(self, parent): QtGui.QLabel.__init__(self, parent) def clickEvent(self, event): print 'Label clicked!' </code></pre> <p>But after clicking I have no line 'Label clicked!'</p> <p><strong>EDIT:</strong></p> <p>Okay, now I'm using not 'clickEvent' but 'mousePressEvent'. And I still have a question. How can i know what exactly label was clicked? For example, i have 2 edit box and 2 labels. Labels content are pixmaps. So there aren't any text in labels, so i can't discern difference between labels. How can i do that?</p> <p><strong>EDIT2:</strong> I made this code:</p> <pre><code>class NewLabel(QtGui.QLabel): def __init__(self, firstLabel): QtGui.QLabel.__init__(self, firstLabel) def mousePressEvent(self, event): print 'Clicked' #myLabel = self.sender() # None =) self.emit(QtCore.SIGNAL('clicked()'), "Label pressed") </code></pre> <p>In another class:</p> <pre><code>self.FirstLang = NewLabel(Form) QtCore.QObject.connect(self.FirstLang, QtCore.SIGNAL('clicked()'), self.labelPressed) </code></pre> <p>Slot in the same class:</p> <pre><code>def labelPressed(self): print 'in labelPressed' print self.sender() </code></pre> <p>But there isn't sender object in self. What i did wrong?</p>
2
2009-06-07T19:38:54Z
962,816
<p>Answering your second question, I'll continue based on @gnud example:</p> <ul> <li>subclass QLabel, override mouseReleaseEvent and add a signal to the class, let's call it clicked.</li> <li>check which button was clicked in mouseReleaseEvent, if it's the left one emit the clicked signal.</li> <li>connect a slot to your labels clicked signal and use <a href="http://doc.trolltech.com/4.5/qobject.html#sender" rel="nofollow">sender()</a> inside to know which QLabel was clicked.</li> </ul>
1
2009-06-07T21:04:12Z
[ "python", "qt", "inheritance", "pyqt", "label" ]
PyQt - QLabel inheriting
962,640
<p>i wanna inherit QLabel to add there click event processing. I'm trying this code:</p> <pre><code>class NewLabel(QtGui.QLabel): def __init__(self, parent): QtGui.QLabel.__init__(self, parent) def clickEvent(self, event): print 'Label clicked!' </code></pre> <p>But after clicking I have no line 'Label clicked!'</p> <p><strong>EDIT:</strong></p> <p>Okay, now I'm using not 'clickEvent' but 'mousePressEvent'. And I still have a question. How can i know what exactly label was clicked? For example, i have 2 edit box and 2 labels. Labels content are pixmaps. So there aren't any text in labels, so i can't discern difference between labels. How can i do that?</p> <p><strong>EDIT2:</strong> I made this code:</p> <pre><code>class NewLabel(QtGui.QLabel): def __init__(self, firstLabel): QtGui.QLabel.__init__(self, firstLabel) def mousePressEvent(self, event): print 'Clicked' #myLabel = self.sender() # None =) self.emit(QtCore.SIGNAL('clicked()'), "Label pressed") </code></pre> <p>In another class:</p> <pre><code>self.FirstLang = NewLabel(Form) QtCore.QObject.connect(self.FirstLang, QtCore.SIGNAL('clicked()'), self.labelPressed) </code></pre> <p>Slot in the same class:</p> <pre><code>def labelPressed(self): print 'in labelPressed' print self.sender() </code></pre> <p>But there isn't sender object in self. What i did wrong?</p>
2
2009-06-07T19:38:54Z
9,038,610
<p>The answer from the <a href="http://diotavelli.net/PyQtWiki/Making%20non-clickable%20widgets%20clickable" rel="nofollow">PyQt Wiki</a> works very well but I would add that the <code>clickable</code> class should call <code>widget.mouseReleaseEvent</code> (right before <code>return True</code>), just in case the user has customized this event.</p>
1
2012-01-27T19:00:20Z
[ "python", "qt", "inheritance", "pyqt", "label" ]
How to call up attributes in python 3.1 -- easy
962,877
<p>Python 2.5 all you needed to do was type "dir(filename)" and that pulls up the attributes.</p> <p>What is the command in 3.1?</p>
-1
2009-06-07T21:31:05Z
962,912
<p>Just <code>dir(whateverobject)</code>. Example:</p> <pre><code>Python 3.1rc1 (r31rc1:73141, Jun 2 2009, 12:50:02) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; x=23 &gt;&gt;&gt; dir(x) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real'] </code></pre> <p>Please show us exactly what isn't working for you -- give us a chance to help!</p>
3
2009-06-07T21:52:16Z
[ "python" ]
Python: changing methods and attributes at runtime
962,962
<p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> <p>Oh, and please don't ask why.</p>
63
2009-06-07T22:39:01Z
962,966
<p>This example shows the differences between adding a method to a class and to an instance. </p> <pre><code>&gt;&gt;&gt; class Dog(): ... def __init__(self, name): ... self.name = name ... &gt;&gt;&gt; skip = Dog('Skip') &gt;&gt;&gt; spot = Dog('Spot') &gt;&gt;&gt; def talk(self): ... print 'Hi, my name is ' + self.name ... &gt;&gt;&gt; Dog.talk = talk # add method to class &gt;&gt;&gt; skip.talk() Hi, my name is Skip &gt;&gt;&gt; spot.talk() Hi, my name is Spot &gt;&gt;&gt; del Dog.talk # remove method from class &gt;&gt;&gt; skip.talk() # won't work anymore Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: Dog instance has no attribute 'talk' &gt;&gt;&gt; import types &gt;&gt;&gt; f = types.MethodType(talk, skip, Dog) &gt;&gt;&gt; skip.talk = f # add method to specific instance &gt;&gt;&gt; skip.talk() Hi, my name is Skip &gt;&gt;&gt; spot.talk() # won't work, since we only modified skip Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: Dog instance has no attribute 'talk' </code></pre>
107
2009-06-07T22:42:51Z
[ "python", "reflection", "runtime" ]
Python: changing methods and attributes at runtime
962,962
<p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> <p>Oh, and please don't ask why.</p>
63
2009-06-07T22:39:01Z
963,199
<p>A possibly interesting alternative to using <code>types.MethodType</code> in:</p> <pre><code>&gt;&gt;&gt; f = types.MethodType(talk, puppy, Dog) &gt;&gt;&gt; puppy.talk = f # add method to specific instance </code></pre> <p>would be to exploit the fact that functions are <a href="http://users.rcn.com/python/download/Descriptor.htm">descriptors</a>:</p> <pre><code>&gt;&gt;&gt; puppy.talk = talk.__get__(puppy, Dog) </code></pre>
26
2009-06-08T01:32:40Z
[ "python", "reflection", "runtime" ]
Python: changing methods and attributes at runtime
962,962
<p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> <p>Oh, and please don't ask why.</p>
63
2009-06-07T22:39:01Z
964,049
<blockquote> <p>I wish to create a class in Python that I can add and remove attributes and methods.</p> </blockquote> <pre><code>import types class SpecialClass(object): @classmethod def removeVariable(cls, name): return delattr(cls, name) @classmethod def addMethod(cls, func): return setattr(cls, func.__name__, types.MethodType(func, cls)) def hello(self, n): print n instance = SpecialClass() SpecialClass.addMethod(hello) &gt;&gt;&gt; SpecialClass.hello(5) 5 &gt;&gt;&gt; instance.hello(6) 6 &gt;&gt;&gt; SpecialClass.removeVariable("hello") &gt;&gt;&gt; instance.hello(7) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'SpecialClass' object has no attribute 'hello' &gt;&gt;&gt; SpecialClass.hello(8) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: type object 'SpecialClass' has no attribute 'hello' </code></pre>
39
2009-06-08T09:24:15Z
[ "python", "reflection", "runtime" ]
Python: changing methods and attributes at runtime
962,962
<p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> <p>Oh, and please don't ask why.</p>
63
2009-06-07T22:39:01Z
966,464
<blockquote> <p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> </blockquote> <p>You can add and remove attributes and methods to any class, and they'll be available to all instances of the class:</p> <pre><code>&gt;&gt;&gt; def method1(self): pass &gt;&gt;&gt; def method1(self): print "method1" &gt;&gt;&gt; def method2(self): print "method2" &gt;&gt;&gt; class C(): pass &gt;&gt;&gt; c = C() &gt;&gt;&gt; c.method() Traceback (most recent call last): File "&lt;pyshell#62&gt;", line 1, in &lt;module&gt; c.method() AttributeError: C instance has no attribute 'method' &gt;&gt;&gt; C.method = method1 &gt;&gt;&gt; c.method() method1 &gt;&gt;&gt; C.method = method2 &gt;&gt;&gt; c.method() method2 &gt;&gt;&gt; del C.method &gt;&gt;&gt; c.method() Traceback (most recent call last): File "&lt;pyshell#68&gt;", line 1, in &lt;module&gt; c.method() AttributeError: C instance has no attribute 'method' &gt;&gt;&gt; C.attribute = "foo" &gt;&gt;&gt; c.attribute 'foo' &gt;&gt;&gt; c.attribute = "bar" &gt;&gt;&gt; c.attribute 'bar' </code></pre>
5
2009-06-08T19:16:46Z
[ "python", "reflection", "runtime" ]
Python: changing methods and attributes at runtime
962,962
<p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> <p>Oh, and please don't ask why.</p>
63
2009-06-07T22:39:01Z
13,221,989
<p>another alternative, if you need to replace the class wholesale is to modify the <strong>class</strong> attribute:</p> <pre><code>&gt;&gt;&gt; class A(object): ... def foo(self): ... print 'A' ... &gt;&gt;&gt; class B(object): ... def foo(self): ... print 'Bar' ... &gt;&gt;&gt; a = A() &gt;&gt;&gt; a.foo() A &gt;&gt;&gt; a.__class__ = B &gt;&gt;&gt; a.foo() Bar </code></pre>
0
2012-11-04T19:23:36Z
[ "python", "reflection", "runtime" ]
Python: changing methods and attributes at runtime
962,962
<p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> <p>Oh, and please don't ask why.</p>
63
2009-06-07T22:39:01Z
14,436,426
<p>Simply: </p> <pre><code>f1 = lambda:0 #method for instances f2 = lambda _:0 #method for class class C: pass #class c1,c2 = C(),C() #instances print dir(c1),dir(c2) #add to the Instances c1.func = f1 c1.any = 1.23 print dir(c1),dir(c2) print c1.func(),c1.any del c1.func,c1.any #add to the Class C.func = f2 C.any = 1.23 print dir(c1),dir(c2) print c1.func(),c1.any print c2.func(),c2.any </code></pre> <p>which results in: </p> <pre><code>['__doc__', '__module__'] ['__doc__', '__module__'] ['__doc__', '__module__', 'any', 'func'] ['__doc__', '__module__'] 0 1.23 ['__doc__', '__module__', 'any', 'func'] ['__doc__', '__module__', 'any', 'func'] 0 1.23 0 1.23 </code></pre>
0
2013-01-21T10:15:26Z
[ "python", "reflection", "runtime" ]
Python: changing methods and attributes at runtime
962,962
<p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> <p>Oh, and please don't ask why.</p>
63
2009-06-07T22:39:01Z
15,956,467
<p>you can just assign directly to the class (either by accessing the original class name or via <code>__class__</code> ):</p> <pre><code>class a : pass ob=a() ob.__class__.blah=lambda self,k: (3, self,k) ob.blah(5) ob2=a() ob2.blah(7) </code></pre> <p>will print</p> <pre><code>(3, &lt;__main__.a instance at 0x7f18e3c345f0&gt;, 5) (3, &lt;__main__.a instance at 0x7f18e3c344d0&gt;, 7) </code></pre>
3
2013-04-11T18:46:17Z
[ "python", "reflection", "runtime" ]
Python: changing methods and attributes at runtime
962,962
<p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> <p>Oh, and please don't ask why.</p>
63
2009-06-07T22:39:01Z
25,836,670
<p>Does the class itself necessarily need to be modified? Or is the goal simply to replace what object.method() does at a particular point during runtime? </p> <p>I ask because I sidestep the problem of actually modifying the class to monkey patch specific method calls in my framework with <strong>getattribute</strong> and a Runtime Decorator on my Base inheritance object. </p> <p>Methods retrieved by a Base object in <strong>getattribute</strong> are wrapped in a Runtime_Decorator that parses the method calls keyword arguments for decorators/monkey patches to apply. </p> <p>This enables you to utilize the syntax object.method(monkey_patch="mypatch"), object.method(decorator="mydecorator"), and even object.method(decorators=my_decorator_list).</p> <p>This works for any individual method call (I leave out magic methods), does so without actually modifying any class/instance attributes, can utilize arbitrary, even foreign methods to patch, and will work transparently on sublcasses that inherit from Base (provided they don't override <strong>getattribute</strong> of course).</p> <pre><code>import trace def monkey_patched(self, *args, **kwargs): print self, "Tried to call a method, but it was monkey patched instead" return "and now for something completely different" class Base(object): def __init__(self): super(Base, self).__init__() def testmethod(self): print "%s test method" % self def __getattribute__(self, attribute): value = super(Base, self).__getattribute__(attribute) if "__" not in attribute and callable(value): value = Runtime_Decorator(value) return value class Runtime_Decorator(object): def __init__(self, function): self.function = function def __call__(self, *args, **kwargs): if kwargs.has_key("monkey_patch"): module_name, patch_name = self._resolve_string(kwargs.pop("monkey_patch")) module = self._get_module(module_name) monkey_patch = getattr(module, patch_name) return monkey_patch(self.function.im_self, *args, **kwargs) if kwargs.has_key('decorator'): decorator_type = str(kwargs['decorator']) module_name, decorator_name = self._resolve_string(decorator_type) decorator = self._get_decorator(decorator_name, module_name) wrapped_function = decorator(self.function) del kwargs['decorator'] return wrapped_function(*args, **kwargs) elif kwargs.has_key('decorators'): decorators = [] for item in kwargs['decorators']: module_name, decorator_name = self._resolve_string(item) decorator = self._get_decorator(decorator_name, module_name) decorators.append(decorator) wrapped_function = self.function for item in reversed(decorators): wrapped_function = item(wrapped_function) del kwargs['decorators'] return wrapped_function(*args, **kwargs) else: return self.function(*args, **kwargs) def _resolve_string(self, string): try: # attempt to split the string into a module and attribute module_name, decorator_name = string.split(".") except ValueError: # there was no ".", it's just a single attribute module_name = "__main__" decorator_name = string finally: return module_name, decorator_name def _get_module(self, module_name): try: # attempt to load the module if it exists already module = modules[module_name] except KeyError: # import it if it doesn't module = __import__(module_name) finally: return module def _get_decorator(self, decorator_name, module_name): module = self._get_module(module_name) try: # attempt to procure the decorator class decorator_wrap = getattr(module, decorator_name) except AttributeError: # decorator not found in module print("failed to locate decorators %s for function %s." %\ (kwargs["decorator"], self.function)) else: return decorator_wrap # instantiate the class with self.function class Tracer(object): def __init__(self, function): self.function = function def __call__(self, *args, **kwargs): tracer = trace.Trace(trace=1) tracer.runfunc(self.function, *args, **kwargs) b = Base() b.testmethod(monkey_patch="monkey_patched") b.testmethod(decorator="Tracer") #b.testmethod(monkey_patch="external_module.my_patch") </code></pre> <p>The downside to this approach is <strong>getattribute</strong> hooks <em>all</em> access to attributes, so the checking of and potential wrapping of methods occurs even for attributes that are not methods + won't be utilizing the feature for the particular call in question. And using <strong>getattribute</strong> at all is inherently somewhat complicated. </p> <p>The actual impact of this overhead in my experience/for my purposes has been negligible, and my machine runs a dual core Celeron. The previous implementation I used introspected methods upon object <strong>init</strong> and bound the Runtime_Decorator to methods then. Doing things that way eliminated the need to utilize <strong>getattribute</strong> and reduced the overhead mentioned previously... however, it also breaks pickle (maybe not dill) and is less dynamic then this approach.</p> <p>The only use cases I have actually come across "in the wild" with this technique were with timing and tracing decorators. However, the possibilities it opens up are extremely wide ranging.</p> <p>If you have a preexisting class that cannot be made to inherit from a different base (or utilize the technique it's own class definition or in it's base class'), then the whole thing simply does not apply to your issue at all unfortunately.</p> <p>I don't think setting/removing non-callable attributes on a class at runtime is necessarily so challenging? unless you want classes that inherit from the modified class to automatically reflect the changes in themselves as well... That'd be a whole 'nother can o' worms by the sound of it though.</p>
0
2014-09-14T18:35:11Z
[ "python", "reflection", "runtime" ]
How can I create a variable that is scoped to a single request in app engine?
963,080
<p>I'm creating a python app for google app engine and I've got a performance problem with some expensive operations that are repetitive within a single request. To help deal with this I'd like to create a sort of mini-cache that's scoped to a single request. This is as opposed to a session-wide or application-wide cache, neither of which would make sense for my particular problem.</p> <p>I thought I could just use a python global or module-level variable for this, but it turns out that those maintain their state between requests in non-obvious ways.</p> <p>I also don't think memcache makes sense because it's application wide.</p> <p>I haven't been able to find a good answer for this in google's docs. Maybe that's because it's either a dumb idea or totally obvious, but it seems like it'd be useful and I'm stumped.</p> <p>Anybody have any ideas?</p>
0
2009-06-08T00:08:03Z
963,107
<p>Module variables may (or may not) persist between requests (the same app instance may or may not stay alive between requests), but you can explicitly clear them (<code>del</code>, or set to <code>None</code>, say) at the start of your handling a request, or when you know you're done with one. At worst (if your code is peculiarly organized) you need to set some function to always execute at every request start, or at every request end.</p>
1
2009-06-08T00:30:44Z
[ "python", "google-app-engine" ]
How can I create a variable that is scoped to a single request in app engine?
963,080
<p>I'm creating a python app for google app engine and I've got a performance problem with some expensive operations that are repetitive within a single request. To help deal with this I'd like to create a sort of mini-cache that's scoped to a single request. This is as opposed to a session-wide or application-wide cache, neither of which would make sense for my particular problem.</p> <p>I thought I could just use a python global or module-level variable for this, but it turns out that those maintain their state between requests in non-obvious ways.</p> <p>I also don't think memcache makes sense because it's application wide.</p> <p>I haven't been able to find a good answer for this in google's docs. Maybe that's because it's either a dumb idea or totally obvious, but it seems like it'd be useful and I'm stumped.</p> <p>Anybody have any ideas?</p>
0
2009-06-08T00:08:03Z
963,706
<p>use local list to store data and do a model.put at end of your request processing. save multiple db trips</p>
0
2009-06-08T06:56:32Z
[ "python", "google-app-engine" ]
How can I create a variable that is scoped to a single request in app engine?
963,080
<p>I'm creating a python app for google app engine and I've got a performance problem with some expensive operations that are repetitive within a single request. To help deal with this I'd like to create a sort of mini-cache that's scoped to a single request. This is as opposed to a session-wide or application-wide cache, neither of which would make sense for my particular problem.</p> <p>I thought I could just use a python global or module-level variable for this, but it turns out that those maintain their state between requests in non-obvious ways.</p> <p>I also don't think memcache makes sense because it's application wide.</p> <p>I haven't been able to find a good answer for this in google's docs. Maybe that's because it's either a dumb idea or totally obvious, but it seems like it'd be useful and I'm stumped.</p> <p>Anybody have any ideas?</p>
0
2009-06-08T00:08:03Z
965,582
<p>What I usually do is just create a new attribute on the request object. However, I use django with AppEngine, so I'm not sure if there is anything different about the appengine webapp framework.</p> <pre><code>def view_handler(request): if hasattr(request, 'mycache'): request.mycache['counter'] += 1 else: request.mycache = {'counter':1,} return HttpResponse("counter="+str(request.mycache["counter"])) </code></pre>
2
2009-06-08T15:46:20Z
[ "python", "google-app-engine" ]
How can I create a variable that is scoped to a single request in app engine?
963,080
<p>I'm creating a python app for google app engine and I've got a performance problem with some expensive operations that are repetitive within a single request. To help deal with this I'd like to create a sort of mini-cache that's scoped to a single request. This is as opposed to a session-wide or application-wide cache, neither of which would make sense for my particular problem.</p> <p>I thought I could just use a python global or module-level variable for this, but it turns out that those maintain their state between requests in non-obvious ways.</p> <p>I also don't think memcache makes sense because it's application wide.</p> <p>I haven't been able to find a good answer for this in google's docs. Maybe that's because it's either a dumb idea or totally obvious, but it seems like it'd be useful and I'm stumped.</p> <p>Anybody have any ideas?</p>
0
2009-06-08T00:08:03Z
972,243
<p>If you're using the 'webapp' framework included with App Engine (or, actually, most other WSGI-baesd frameworks), a new RequestHandler is instantiated for each request. Thus, you can use class variables on your handler class to store per-request data.</p>
2
2009-06-09T20:10:03Z
[ "python", "google-app-engine" ]
Python display string multiple times
963,161
<p>I want to print a character or string like '-' n number of times.</p> <p>Can I do it without using a loop?.. Is there a function like</p> <pre><code>print('-',3) </code></pre> <p>..which would mean printing the <code>-</code> 3 times, like this:</p> <pre><code>--- </code></pre>
40
2009-06-08T01:11:57Z
963,166
<p>Python 2.x:</p> <pre><code>print '-' * 3 </code></pre> <p>Python 3.x:</p> <pre><code>print('-' * 3) </code></pre>
78
2009-06-08T01:13:45Z
[ "python" ]
Python display string multiple times
963,161
<p>I want to print a character or string like '-' n number of times.</p> <p>Can I do it without using a loop?.. Is there a function like</p> <pre><code>print('-',3) </code></pre> <p>..which would mean printing the <code>-</code> 3 times, like this:</p> <pre><code>--- </code></pre>
40
2009-06-08T01:11:57Z
28,652,751
<p>To print a string 3 times in Python 3.x, in this case the string is "hello"</p> <blockquote> <blockquote> <blockquote> <p>print("hello " * 3)</p> </blockquote> </blockquote> </blockquote>
0
2015-02-21T23:41:57Z
[ "python" ]
how to use session/cookie in twisted.web?
963,236
<p>I am implementing an http server with twisted.web. Here comes the problem: there is a login operation; after that, I want the http server to remember each client using acookie/session, until the user closes the browser.</p> <p>I've read the twisted.web document, but I can't figure out how to do this. I know the request object has a function named getSession(), then a session object will be returned. What next? How do I store the information during the several requests?</p> <p>I also searched the twisted mail list; there nothing very helpful, and I am still confused. If someone used this before, please explain this to me, or even put some code here, so I can understand it myself. Thank you very much! </p>
9
2009-06-08T02:07:35Z
992,462
<p>You can use "request.getSession()" to get a componentized object.</p> <p>You can read more about componentized in <a href="http://twistedmatrix.com/documents/current/api/twisted.python.components.Componentized.html" rel="nofollow">http://twistedmatrix.com/documents/current/api/twisted.python.components.Componentized.html</a> -- the basic way of using it is via defining an interface and an implementation, and pushing your on objects into the session.</p>
4
2009-06-14T08:50:06Z
[ "python", "twisted" ]
how to use session/cookie in twisted.web?
963,236
<p>I am implementing an http server with twisted.web. Here comes the problem: there is a login operation; after that, I want the http server to remember each client using acookie/session, until the user closes the browser.</p> <p>I've read the twisted.web document, but I can't figure out how to do this. I know the request object has a function named getSession(), then a session object will be returned. What next? How do I store the information during the several requests?</p> <p>I also searched the twisted mail list; there nothing very helpful, and I am still confused. If someone used this before, please explain this to me, or even put some code here, so I can understand it myself. Thank you very much! </p>
9
2009-06-08T02:07:35Z
1,300,087
<p>Calling getSession() will generate a session and add the cookie to the request:</p> <p><a href="http://twistedmatrix.com/trac/browser/tags/releases/twisted-8.1.0/twisted/web/server.py#L315" rel="nofollow">getSession() source code</a></p> <p>If the clients already has a session cookie then calling getSession() will read it and return a Session with the original Session content. So it is transparent to your code whether or not it is actually creating the Session cookie or just reading it.</p> <p>Session cookies have certain properties... if you want more control over the contents of the cookie then look at Request.addCookie() which getSession() calls behind the scenese.</p>
4
2009-08-19T13:50:46Z
[ "python", "twisted" ]
how to use session/cookie in twisted.web?
963,236
<p>I am implementing an http server with twisted.web. Here comes the problem: there is a login operation; after that, I want the http server to remember each client using acookie/session, until the user closes the browser.</p> <p>I've read the twisted.web document, but I can't figure out how to do this. I know the request object has a function named getSession(), then a session object will be returned. What next? How do I store the information during the several requests?</p> <p>I also searched the twisted mail list; there nothing very helpful, and I am still confused. If someone used this before, please explain this to me, or even put some code here, so I can understand it myself. Thank you very much! </p>
9
2009-06-08T02:07:35Z
10,748,955
<p>See this related question <a href="http://stackoverflow.com/questions/4936994/store-an-instance-of-a-connection-twisted-web">Store an instance of a connection - twisted.web</a>. The answer there links to this blog post <a href="http://jcalderone.livejournal.com/53680.html" rel="nofollow">http://jcalderone.livejournal.com/53680.html</a>, which shows an example of storing a counter for the number of visits for the session (thanks to jcalderone for the example):</p> <pre><code># in a .rpy file launched with `twistd -n web --path .` cache() from zope.interface import Interface, Attribute, implements from twisted.python.components import registerAdapter from twisted.web.server import Session from twisted.web.resource import Resource class ICounter(Interface): value = Attribute("An int value which counts up once per page view.") class Counter(object): implements(ICounter) def __init__(self, session): self.value = 0 registerAdapter(Counter, Session, ICounter) class CounterResource(Resource): def render_GET(self, request): session = request.getSession() counter = ICounter(session) counter.value += 1 return "Visit #%d for you!" % (counter.value,) resource = CounterResource() </code></pre> <p>Don't worry if this seems confusing - there are two things that you need to understand before the behaviour here makes sense:</p> <ol> <li><a href="http://twistedmatrix.com/documents/current/core/howto/components.html" rel="nofollow">Twisted (Zope) Interfaces &amp; Adapters</a></li> <li><a href="http://twistedmatrix.com/documents/current/api/twisted.python.components.Componentized.html" rel="nofollow">Componentized</a></li> </ol> <p>The counter value is stored in an Adapter class, the Interface class documents what that class provides. The reason that you can store persistent data in the Adapter is because Session (returned by getSession()) is a subclass of Componentized.</p>
2
2012-05-25T05:32:45Z
[ "python", "twisted" ]
HTML tags within JSON (in Python)
963,448
<p>I understand its not a desirable circumstance, however if I NEEDED to have some kind of HTML within JSON tags, e.g.:</p> <pre><code>{ "node": { "list":"&lt;ul&gt;&lt;li class="lists"&gt;Hello World&lt;/li&gt;&lt;ul&gt;" } } </code></pre> <p>is this possible to do in Python without requiring to to be escaped beforehand? </p> <p>It will be a string initially so I was thinking about writing a regular expression to attempt to match and escape these prior to processing, but I just want to make sure there isn't an easier way.</p>
2
2009-06-08T04:48:15Z
963,476
<p>You can have arbitrary strings there, including ones which happen to contain HTML tags (the only issue with your example is the inner <code>"</code> which would confuse any parser).</p>
0
2009-06-08T05:00:50Z
[ "python", "json", "escaping", "markup" ]
HTML tags within JSON (in Python)
963,448
<p>I understand its not a desirable circumstance, however if I NEEDED to have some kind of HTML within JSON tags, e.g.:</p> <pre><code>{ "node": { "list":"&lt;ul&gt;&lt;li class="lists"&gt;Hello World&lt;/li&gt;&lt;ul&gt;" } } </code></pre> <p>is this possible to do in Python without requiring to to be escaped beforehand? </p> <p>It will be a string initially so I was thinking about writing a regular expression to attempt to match and escape these prior to processing, but I just want to make sure there isn't an easier way.</p>
2
2009-06-08T04:48:15Z
963,482
<p>Well, depending on how varied your HTML is, you can use single quotes in HTML fine, so you could do:</p> <pre><code>{ "node": { "list": "&lt;ul&gt;&lt;li class='lists'&gt;Hello World&lt;/li&gt;&lt;ul&gt;" } } </code></pre> <p>However, with <code>simplejson</code>, which is built into Python 2.6 as the <a href="http://docs.python.org/library/json.html" rel="nofollow">json module</a>, it does any escaping you need automatically:</p> <pre><code>&gt;&gt;&gt; import simplejson &gt;&gt;&gt; simplejson.dumps({'node': {'list': '&lt;ul&gt;&lt;li class="lists"&gt;Hello World&lt;/li&gt;&lt;ul&gt;'}}) '{"node": {"list": "&lt;ul&gt;&lt;li class=\\"lists\\"&gt;Hello World&lt;/li&gt;&lt;ul&gt;"}}' </code></pre>
4
2009-06-08T05:02:45Z
[ "python", "json", "escaping", "markup" ]
Tab view in CSS with tables
963,506
<p>I need a tab view in CSS with each tab showing a dynamic table. The complete table is dynamically constructed in loop and only after that should the tabs should hide and show each of the table corresponding to each tab. Any suggestions? The content of the tab is within list item and in loop only. The development is in Django/Python on appspot.</p> <p>The following code does not work for jquery also, is there a problem somewhere?</p> <pre><code>&lt;pre&gt;&lt;code&gt; &lt;div id="tabs"&gt; &lt;ul&gt; {% for poolname in poolnamelist %} &lt;li&gt;&lt;a href="#mypool{{ forloop.counter }}"&gt; &lt;span&gt;{{ poolname|escape }}&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% for poolsequence in sequences %} &lt;div id="mypool{{ forloop.counter }}"&gt; &lt;table&gt; {% for sequence in poolsequence %} &lt;form action="/mypool" method="post"&gt; &lt;tr&gt;&lt;td&gt;{{ sequence.seqdate }}&lt;/td&gt; &lt;td&gt;&lt;input type="submit" value="ChangeDriver"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/form&gt; {% endfor %} &lt;/table&gt; &lt;/div&gt; {% endfor %} &lt;/div&gt; &lt;/code&gt;&lt;/pre&gt; </code></pre>
0
2009-06-08T05:20:43Z
963,558
<p>Just of the top of my head, check out what some of the Javascript toolkits have to offer. Things like jQuery with a few plugins or Dojo might have something like that in its Dijit library.</p>
0
2009-06-08T05:44:06Z
[ "python", "html", "css", "tabs", "css-tables" ]
Tab view in CSS with tables
963,506
<p>I need a tab view in CSS with each tab showing a dynamic table. The complete table is dynamically constructed in loop and only after that should the tabs should hide and show each of the table corresponding to each tab. Any suggestions? The content of the tab is within list item and in loop only. The development is in Django/Python on appspot.</p> <p>The following code does not work for jquery also, is there a problem somewhere?</p> <pre><code>&lt;pre&gt;&lt;code&gt; &lt;div id="tabs"&gt; &lt;ul&gt; {% for poolname in poolnamelist %} &lt;li&gt;&lt;a href="#mypool{{ forloop.counter }}"&gt; &lt;span&gt;{{ poolname|escape }}&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% for poolsequence in sequences %} &lt;div id="mypool{{ forloop.counter }}"&gt; &lt;table&gt; {% for sequence in poolsequence %} &lt;form action="/mypool" method="post"&gt; &lt;tr&gt;&lt;td&gt;{{ sequence.seqdate }}&lt;/td&gt; &lt;td&gt;&lt;input type="submit" value="ChangeDriver"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/form&gt; {% endfor %} &lt;/table&gt; &lt;/div&gt; {% endfor %} &lt;/div&gt; &lt;/code&gt;&lt;/pre&gt; </code></pre>
0
2009-06-08T05:20:43Z
963,566
<p>Check out <a href="http://docs.jquery.com/UI/Tabs" rel="nofollow">jQuery UI Tabs</a>; this will do what you're looking for. It's not possible to do this using pure CSS.</p>
1
2009-06-08T05:48:33Z
[ "python", "html", "css", "tabs", "css-tables" ]
How can I instantiate a comment element programatically using lxml?
963,621
<p>I'm using lxml to programatically build HTML and I need to include a custom comment in the output. Whilst there is code in lxml to cope with comments (they can be instantiated when parsing existing HTML code) I cannot find a way to instantiate one programatically.</p> <p>Can anyone help?</p>
2
2009-06-08T06:15:45Z
963,680
<p>You can use the <a href="http://lxml.de/api/lxml.etree._Comment-class.html" rel="nofollow"><code>lxml.etree.Comment()</code></a> factory function. It will return a comment element that you can use like any other element.</p>
4
2009-06-08T06:44:34Z
[ "python", "html", "xml", "lxml" ]
Zipping dynamic files in App Engine (Python)
963,800
<p>Is there anyway I can zip dynamically generated content, such as a freshly rendered html template, into a zip file using zipfile?</p> <p>There seem to be some examples around for zipping static content, but none for zipping dynamic ones. Or, is it not possible at all?</p> <p>One more question: Is it possible to create a zip file with a bunch of sub-folders inside it?</p> <p>Thanks.</p>
6
2009-06-08T07:38:02Z
963,842
<p>You can add whatever you want to a zip file using <a href="http://docs.python.org/library/zipfile#zipfile.ZipFile.writestr"><code>ZipFile.writestr()</code></a>:</p> <pre><code>my_data = "&lt;html&gt;&lt;body&gt;&lt;p&gt;Hello, world!&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;" z.writestr("hello.html", my_data) </code></pre> <p>You can also use sub-folders using <code>/</code> (or <code>os.sep</code>) as a separator:</p> <pre><code>z.writestr("site/foo/hello/index.html", my_data) </code></pre>
7
2009-06-08T08:01:28Z
[ "python", "google-app-engine", "zipfile" ]
Zipping dynamic files in App Engine (Python)
963,800
<p>Is there anyway I can zip dynamically generated content, such as a freshly rendered html template, into a zip file using zipfile?</p> <p>There seem to be some examples around for zipping static content, but none for zipping dynamic ones. Or, is it not possible at all?</p> <p>One more question: Is it possible to create a zip file with a bunch of sub-folders inside it?</p> <p>Thanks.</p>
6
2009-06-08T07:38:02Z
964,084
<p>In addition to Schnouki's excellent answer, you can also pass ZipFile a file-like object, such as one created by <a href="http://docs.python.org/library/stringio.html" rel="nofollow">StringIO.StringIO</a>.</p>
3
2009-06-08T09:38:06Z
[ "python", "google-app-engine", "zipfile" ]
Zipping dynamic files in App Engine (Python)
963,800
<p>Is there anyway I can zip dynamically generated content, such as a freshly rendered html template, into a zip file using zipfile?</p> <p>There seem to be some examples around for zipping static content, but none for zipping dynamic ones. Or, is it not possible at all?</p> <p>One more question: Is it possible to create a zip file with a bunch of sub-folders inside it?</p> <p>Thanks.</p>
6
2009-06-08T07:38:02Z
964,418
<p>The working code: (for app engine:)</p> <pre><code>output = StringIO.StringIO() z = zipfile.ZipFile(output,'w') my_data = "&lt;html&gt;&lt;body&gt;&lt;p&gt;Hello, world!&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;" z.writestr("hello.html", my_data) z.close() self.response.headers["Content-Type"] = "multipart/x-zip" self.response.headers['Content-Disposition'] = "attachment; filename=test.zip" self.response.out.write(output.getvalue()) </code></pre> <p>Thanks again to Schnouki and Ryan.</p>
14
2009-06-08T11:16:36Z
[ "python", "google-app-engine", "zipfile" ]
Can't seem to get list() working
963,932
<p>I am trying to convert a set object to list...for example "p=list('abc')" is not working. any ideas or is it inherent in appengine</p>
0
2009-06-08T08:47:33Z
964,005
<p>A set object to list is converted like so:</p> <pre><code>my_list = list(my_set) </code></pre> <p>I don't understand your example though. Converting a string to a list results in a list of characters:</p> <pre><code>&gt;&gt;&gt; list('abc') ['a', 'b', 'c'] </code></pre>
1
2009-06-08T09:11:22Z
[ "python", "django", "google-app-engine", "list" ]
Can't seem to get list() working
963,932
<p>I am trying to convert a set object to list...for example "p=list('abc')" is not working. any ideas or is it inherent in appengine</p>
0
2009-06-08T08:47:33Z
964,194
<p>if the list() command is not working for you, you could work around it like this:</p> <pre><code>my_list = [] for item in my_set: my_list.append(item) </code></pre> <p>hth</p>
0
2009-06-08T10:11:45Z
[ "python", "django", "google-app-engine", "list" ]
Can't seem to get list() working
963,932
<p>I am trying to convert a set object to list...for example "p=list('abc')" is not working. any ideas or is it inherent in appengine</p>
0
2009-06-08T08:47:33Z
965,860
<p>There is no specific change "inherent" in appengine with respect to common aspects like lists. It is as just the same, plain python.</p>
0
2009-06-08T16:48:48Z
[ "python", "django", "google-app-engine", "list" ]
How to write Strategy Pattern in Python differently than example in Wikipedia?
963,965
<p>In the 2009 Wikipedia entry for the Strategy Pattern, there's a example <a href="http://web.archive.org/web/20090626214649/http://en.wikipedia.org/wiki/Strategy_Pattern#PHP" rel="nofollow">written in PHP</a>.</p> <p>Most other code samples do something like:</p> <pre><code>a = Context.new(StrategyA.new) a.execute #=&gt; Doing the task the normal way b = Context.new(StrategyB.new) b.execute #=&gt; Doing the task alternatively c = Context.new(StrategyC.new) c.execute #=&gt; Doing the task even more alternative </code></pre> <p>In the Python code a different technique is used with a Submit button. I wonder what the Python code will look like if it also did it the way the other code samples do.</p> <p><strong>Update:</strong> Can it be shorter using first-class functions in Python?</p>
27
2009-06-08T08:58:40Z
964,033
<p>The example in Python is not so different of the others. To mock the PHP script:</p> <pre><code>class StrategyExample: def __init__(self, func=None): if func: self.execute = func def execute(self): print("Original execution") def executeReplacement1(): print("Strategy 1") def executeReplacement2(): print("Strategy 2") if __name__ == "__main__": strat0 = StrategyExample() strat1 = StrategyExample(executeReplacement1) strat2 = StrategyExample(executeReplacement2) strat0.execute() strat1.execute() strat2.execute() </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>Original execution Strategy 1 Strategy 2 </code></pre> <p>The main differences are:</p> <ul> <li>You don't need to write any other class or implement any interface.</li> <li>Instead you can pass a function reference that will be bound to the method you want.</li> <li>The functions can still be used separately, and the original object can have a default behavior if you want to (the <code>if func == None</code> pattern can be used for that).</li> <li>Indeed, it's clean short and elegant as usual with Python. But you lose information; with no explicit interface, the programmer is assumed as an adult to know what they are doing.</li> </ul> <p>Note that there are 3 ways to dynamically add a method in Python:</p> <ul> <li><p>The way I've shown you. But the method will be static, it won't get the "self" argument passed.</p></li> <li><p>Using the class name:</p> <p><code>StrategyExample.execute = func</code></p></li> </ul> <p>Here, all the instance will get <code>func</code> as the <code>execute</code> method, and will get <code>self</code> passed as an argument.</p> <ul> <li><p>Binding to an instance only (using the <code>types</code> module):</p> <p><code>strat0.execute = types.MethodType(executeReplacement1, strat0)</code></p> <p>or with Python 2, the class of the instance being changed is also required:</p> <p><code>strat0.execute = types.MethodType(executeReplacement1, strat0, StrategyExample)</code></p></li> </ul> <p>This will bind the new method to <code>strat0</code>, and only <code>strat0</code>, like with the first example. But <code>start0.execute()</code> will get <code>self</code> passed as an argument.</p> <p>If you need to use a reference to the current instance in the function, then you would combine the first and the last method. If you do not:</p> <pre><code>class StrategyExample: def __init__(self, func=None): self.name = "Strategy Example 0" if func: self.execute = func def execute(self): print(self.name) def executeReplacement1(): print(self.name + " from execute 1") def executeReplacement2(): print(self.name + " from execute 2") if __name__ == "__main__": strat0 = StrategyExample() strat1 = StrategyExample(executeReplacement1) strat1.name = "Strategy Example 1" strat2 = StrategyExample(executeReplacement2) strat2.name = "Strategy Example 2" strat0.execute() strat1.execute() strat2.execute() </code></pre> <p>You will get:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "test.py", line 28, in &lt;module&gt; strat1.execute() File "test.py", line 13, in executeReplacement1 print self.name + " from execute 1" NameError: global name 'self' is not defined </code></pre> <p>So the proper code would be:</p> <pre><code>import sys import types if sys.version_info[0] &gt; 2: # Python 3+ create_bound_method = types.MethodType else: def create_bound_method(func, obj): return types.MethodType(func, obj, obj.__class__) class StrategyExample: def __init__(self, func=None): self.name = "Strategy Example 0" if func: self.execute = create_bound_method(func, self) def execute(self): print(self.name) def executeReplacement1(self): print(self.name + " from execute 1") def executeReplacement2(self): print(self.name + " from execute 2") if __name__ == "__main__": strat0 = StrategyExample() strat1 = StrategyExample(executeReplacement1) strat1.name = "Strategy Example 1" strat2 = StrategyExample(executeReplacement2) strat2.name = "Strategy Example 2" strat0.execute() strat1.execute() strat2.execute() </code></pre> <p>This will output the expected result:</p> <pre class="lang-none prettyprint-override"><code>Strategy Example 0 Strategy Example 1 from execute 1 Strategy Example 2 from execute 2 </code></pre> <p>Of course, in the case the functions cannot be used stand alone anymore, but can still be bound to any other instance of any object, without any interface limitation.</p>
40
2009-06-08T09:18:07Z
[ "python", "design-patterns" ]
How to write Strategy Pattern in Python differently than example in Wikipedia?
963,965
<p>In the 2009 Wikipedia entry for the Strategy Pattern, there's a example <a href="http://web.archive.org/web/20090626214649/http://en.wikipedia.org/wiki/Strategy_Pattern#PHP" rel="nofollow">written in PHP</a>.</p> <p>Most other code samples do something like:</p> <pre><code>a = Context.new(StrategyA.new) a.execute #=&gt; Doing the task the normal way b = Context.new(StrategyB.new) b.execute #=&gt; Doing the task alternatively c = Context.new(StrategyC.new) c.execute #=&gt; Doing the task even more alternative </code></pre> <p>In the Python code a different technique is used with a Submit button. I wonder what the Python code will look like if it also did it the way the other code samples do.</p> <p><strong>Update:</strong> Can it be shorter using first-class functions in Python?</p>
27
2009-06-08T08:58:40Z
964,325
<p>For clarity, I would still use a pseudo-interface:</p> <pre><code>class CommunicationStrategy(object): def execute(self, a, b): raise NotImplementedError('execute') class ConcreteCommunicationStrategyDuck(CommunicationStrategy): def execute(self, a, b): print "Quack Quack" class ConcreteCommunicationStrategyCow(CommunicationStrategy): def execute(self, a, b): print "Mooo" class ConcreteCommunicationStrategyFrog(CommunicationStrategy): def execute(self, a, b): print "Ribbit! Ribbit!" </code></pre>
9
2009-06-08T10:53:38Z
[ "python", "design-patterns" ]
How to write Strategy Pattern in Python differently than example in Wikipedia?
963,965
<p>In the 2009 Wikipedia entry for the Strategy Pattern, there's a example <a href="http://web.archive.org/web/20090626214649/http://en.wikipedia.org/wiki/Strategy_Pattern#PHP" rel="nofollow">written in PHP</a>.</p> <p>Most other code samples do something like:</p> <pre><code>a = Context.new(StrategyA.new) a.execute #=&gt; Doing the task the normal way b = Context.new(StrategyB.new) b.execute #=&gt; Doing the task alternatively c = Context.new(StrategyC.new) c.execute #=&gt; Doing the task even more alternative </code></pre> <p>In the Python code a different technique is used with a Submit button. I wonder what the Python code will look like if it also did it the way the other code samples do.</p> <p><strong>Update:</strong> Can it be shorter using first-class functions in Python?</p>
27
2009-06-08T08:58:40Z
964,345
<p>You're right, the wikipedia example isn't helpful. It conflates two things.</p> <ol> <li><p><strong>Strategy</strong>.</p></li> <li><p>Features of Python that simplify the implementation of <strong>Strategy</strong>. The "there's no need to implement this pattern explicitly" statement is incorrect. You often need to implement <strong>Strategy</strong>, but Python simplifies this by allowing you to use a function without the overhead of a class wrapper around a function.</p></li> </ol> <p>First, <strong>Strategy</strong>.</p> <pre><code>class AUsefulThing( object ): def __init__( self, aStrategicAlternative ): self.howToDoX = aStrategicAlternative def doX( self, someArg ): self. howToDoX.theAPImethod( someArg, self ) class StrategicAlternative( object ): pass class AlternativeOne( StrategicAlternative ): def theAPIMethod( self, someArg, theUsefulThing ): pass # an implementation class AlternativeTwo( StrategicAlternative ): def theAPImethod( self, someArg, theUsefulThing ): pass # another implementation </code></pre> <p>Now you can do things like this.</p> <pre><code>t = AUsefulThing( AlternativeOne() ) t.doX( arg ) </code></pre> <p>And it will use the strategy object we created.</p> <p>Second, Python alternatives.</p> <pre><code>class AUsefulThing( object ): def __init__( self, aStrategyFunction ): self.howToDoX = aStrategyFunction def doX( self, someArg ): self.howToDoX( someArg, self ) def strategyFunctionOne( someArg, theUsefulThing ): pass # an implementation def strategyFunctionTwo( someArg, theUsefulThing ): pass # another implementation </code></pre> <p>We can do this.</p> <pre><code>t= AUsefulThing( strategyFunctionOne ) t.doX( anArg ) </code></pre> <p>This will also use a strategy function we provided.</p>
26
2009-06-08T10:59:30Z
[ "python", "design-patterns" ]
How to write Strategy Pattern in Python differently than example in Wikipedia?
963,965
<p>In the 2009 Wikipedia entry for the Strategy Pattern, there's a example <a href="http://web.archive.org/web/20090626214649/http://en.wikipedia.org/wiki/Strategy_Pattern#PHP" rel="nofollow">written in PHP</a>.</p> <p>Most other code samples do something like:</p> <pre><code>a = Context.new(StrategyA.new) a.execute #=&gt; Doing the task the normal way b = Context.new(StrategyB.new) b.execute #=&gt; Doing the task alternatively c = Context.new(StrategyC.new) c.execute #=&gt; Doing the task even more alternative </code></pre> <p>In the Python code a different technique is used with a Submit button. I wonder what the Python code will look like if it also did it the way the other code samples do.</p> <p><strong>Update:</strong> Can it be shorter using first-class functions in Python?</p>
27
2009-06-08T08:58:40Z
8,919,545
<p>Answering an old question for the Googlers who searched "python strategy pattern" and landed here...</p> <p>This pattern is practically non-existent in languages that support first class functions. You may want to consider taking advantage of this feature in Python:</p> <pre><code>def strategy_add(a, b): return a + b def strategy_minus(a, b): return a - b solver = strategy_add print solver(1, 2) solver = strategy_minus print solver(2, 1) </code></pre> <p>This approach is very clean and simple.</p> <p>Also, be sure to check out Joe Gregorio's PyCon 2009 talk about Python and design patterns (or lack thereof): <a href="http://pyvideo.org/video/146/pycon-2009--the--lack-of--design-patterns-in-pyth" rel="nofollow">http://pyvideo.org/video/146/pycon-2009--the--lack-of--design-patterns-in-pyth</a></p>
30
2012-01-19T00:30:47Z
[ "python", "design-patterns" ]
How to write Strategy Pattern in Python differently than example in Wikipedia?
963,965
<p>In the 2009 Wikipedia entry for the Strategy Pattern, there's a example <a href="http://web.archive.org/web/20090626214649/http://en.wikipedia.org/wiki/Strategy_Pattern#PHP" rel="nofollow">written in PHP</a>.</p> <p>Most other code samples do something like:</p> <pre><code>a = Context.new(StrategyA.new) a.execute #=&gt; Doing the task the normal way b = Context.new(StrategyB.new) b.execute #=&gt; Doing the task alternatively c = Context.new(StrategyC.new) c.execute #=&gt; Doing the task even more alternative </code></pre> <p>In the Python code a different technique is used with a Submit button. I wonder what the Python code will look like if it also did it the way the other code samples do.</p> <p><strong>Update:</strong> Can it be shorter using first-class functions in Python?</p>
27
2009-06-08T08:58:40Z
36,996,245
<p>I've tried to convert the 'Duck' example from the 1st chapter (covering Strategy Pattern) of <a href="http://rads.stackoverflow.com/amzn/click/0596007124" rel="nofollow">Head First Design Pattern</a> in Python:</p> <pre><code>class FlyWithRocket(): def __init__(self): pass def fly(self): print 'FLying with rocket' class FlyWithWings(): def __init__(self): pass def fly(self): print 'FLying with wings' class CantFly(): def __init__(self): pass def fly(self): print 'I Cant fly' class SuperDuck: def __init__(self): pass def setFlyingBehaviour(self, fly_obj): self.fly_obj = fly_obj def perform_fly(self): self.fly_obj.fly() if __name__ == '__main__': duck = SuperDuck() fly_behaviour = FlyWithRocket() #fly_behaviour = FlyWithWings() duck.setFlyingBehaviour(fly_behaviour) duck.perform_fly() </code></pre>
0
2016-05-03T05:26:53Z
[ "python", "design-patterns" ]
How should I debug Trac plugins?
964,123
<p>I'm about to start a fair amount of work extending Trac to fit our business requirements. So far I've used pythonWin and now Netbeans 6.5 as the development environments - neither of these seem to provide any way of debugging the plugin I am working on.</p> <p><em>I'm totally new to Python</em> so probably have not set up the development environment how it could be congfigured to get it debugging. </p> <p>Am I missing something obvious? It seems a bit archaic to have to resort to printing debug messages to the Trac log, which is how I'm debugging at the moment.</p>
4
2009-06-08T09:49:05Z
964,191
<p>Usually, we unit test first.</p> <p>Then, we write log messages to diagnose problems.</p> <p>We generally don't depend heavily on debugging because it's often hard to do in situations where Python scripts are embedded in a larger product.</p>
0
2009-06-08T10:11:12Z
[ "python", "trac", "netbeans6.5" ]
How should I debug Trac plugins?
964,123
<p>I'm about to start a fair amount of work extending Trac to fit our business requirements. So far I've used pythonWin and now Netbeans 6.5 as the development environments - neither of these seem to provide any way of debugging the plugin I am working on.</p> <p><em>I'm totally new to Python</em> so probably have not set up the development environment how it could be congfigured to get it debugging. </p> <p>Am I missing something obvious? It seems a bit archaic to have to resort to printing debug messages to the Trac log, which is how I'm debugging at the moment.</p>
4
2009-06-08T09:49:05Z
964,546
<p>I've found that <a href="http://winpdb.org/about/" rel="nofollow">Winpdb</a> is a decent python debugger. </p> <p>But as S.Lott points out, debuggers may not be very useful to you when your project is embedded within a larger one. </p>
0
2009-06-08T11:56:45Z
[ "python", "trac", "netbeans6.5" ]
How should I debug Trac plugins?
964,123
<p>I'm about to start a fair amount of work extending Trac to fit our business requirements. So far I've used pythonWin and now Netbeans 6.5 as the development environments - neither of these seem to provide any way of debugging the plugin I am working on.</p> <p><em>I'm totally new to Python</em> so probably have not set up the development environment how it could be congfigured to get it debugging. </p> <p>Am I missing something obvious? It seems a bit archaic to have to resort to printing debug messages to the Trac log, which is how I'm debugging at the moment.</p>
4
2009-06-08T09:49:05Z
964,583
<p>Trac contains good examples of Python code, using it as a guideline will help avoid bugs. Just be sure to test your code, and do it often since you are new to Python... You'll find you don't need a debugger.</p> <p>For unit testing, check out <a href="http://wiki.python.org/moin/PyUnit" rel="nofollow">PyUnit</a>.</p>
0
2009-06-08T12:05:02Z
[ "python", "trac", "netbeans6.5" ]
How should I debug Trac plugins?
964,123
<p>I'm about to start a fair amount of work extending Trac to fit our business requirements. So far I've used pythonWin and now Netbeans 6.5 as the development environments - neither of these seem to provide any way of debugging the plugin I am working on.</p> <p><em>I'm totally new to Python</em> so probably have not set up the development environment how it could be congfigured to get it debugging. </p> <p>Am I missing something obvious? It seems a bit archaic to have to resort to printing debug messages to the Trac log, which is how I'm debugging at the moment.</p>
4
2009-06-08T09:49:05Z
964,957
<p>You can create a wrapper wsgi script and run it in a debugger. For example:</p> <pre><code>import os import trac.web.main os.environ['TRAC_ENV'] = '/path/to/your/trac/env' application = trac.web.main.dispatch_request from flup.server.fcgi import WSGIServer server = WSGIServer(application, bindAddress=("127.0.0.1", 9000), ) server.run() </code></pre> <p>You would run this script in the debugger, and you can use lighttpd as a frontend for the web application with a trivial config like this one:</p> <pre><code>server.document-root = "/path/to/your/trac/env" server.port = 1234 server.modules = ( "mod_fastcgi" ) server.pid-file = "/path/to/your/trac/env/httpd.pid" server.errorlog = "/path/to/your/trac/env/error.log" fastcgi.server = ( "/" =&gt; (( "host" =&gt; "127.0.0.1", "port" =&gt; 9000, "docroot" =&gt; "/", "check-local" =&gt; "disable", )) ) </code></pre> <p>Just run the fcgi wsgi wrapper in the debugger, set the breakpoints in your plugin, and open the web page.</p>
2
2009-06-08T13:33:59Z
[ "python", "trac", "netbeans6.5" ]
How should I debug Trac plugins?
964,123
<p>I'm about to start a fair amount of work extending Trac to fit our business requirements. So far I've used pythonWin and now Netbeans 6.5 as the development environments - neither of these seem to provide any way of debugging the plugin I am working on.</p> <p><em>I'm totally new to Python</em> so probably have not set up the development environment how it could be congfigured to get it debugging. </p> <p>Am I missing something obvious? It seems a bit archaic to have to resort to printing debug messages to the Trac log, which is how I'm debugging at the moment.</p>
4
2009-06-08T09:49:05Z
17,024,225
<p>I found it most useful to add those fancy Trac messageboxes at runtime as debugging help or tracing, just like this:</p> <pre><code>from trac.web.chrome import add_notice ... def any_function_somewhere(self, req, ...anyother args...): ... var = ...some value... add_notice(req, "my variable value I am tracing %s" % var) </code></pre> <p>Sometimes it's more comfortable than reading logging afterwards. Though it only works if the function you're running has that <code>req</code> arg.</p>
0
2013-06-10T12:46:40Z
[ "python", "trac", "netbeans6.5" ]
python formating float numbers
964,372
<p>my input is 3.23 , but when i use float on it , it becomes 3.2 , </p> <p>when my input is 3.00 , when i do float on it , it becomes 3.0 </p> <p>when i convert to float from string , i still want it to be 3.00 and not 3.0 is it possible? i want to know the code to make it possible , and when i am doing a problem in which the decimal point till 2 digits matter, 3.23 is better than 3.2 , for more precision</p>
-5
2009-06-08T11:05:02Z
964,412
<p>if you want decimal precision use the python <a href="http://docs.python.org/library/decimal.html" rel="nofollow"><code>decimal</code></a> module:</p> <pre><code>from decimal import Decimal x = Decimal('3.00') print x </code></pre> <p>That prints:</p> <pre><code>Decimal('3.00') </code></pre>
1
2009-06-08T11:15:37Z
[ "python", "floating" ]
python formating float numbers
964,372
<p>my input is 3.23 , but when i use float on it , it becomes 3.2 , </p> <p>when my input is 3.00 , when i do float on it , it becomes 3.0 </p> <p>when i convert to float from string , i still want it to be 3.00 and not 3.0 is it possible? i want to know the code to make it possible , and when i am doing a problem in which the decimal point till 2 digits matter, 3.23 is better than 3.2 , for more precision</p>
-5
2009-06-08T11:05:02Z
964,417
<p>If you want to print a floating-point number to a desired precision you can use output formatting codes like the following:</p> <p>Assuming x = 3.125</p> <pre><code>print "%.1f" % (x) # prints 3.1 print "%.2f" % (x) # prints 3.12 print "%.3f" % (x) # prints 3.125 print "%.4f" % (x) # prints 3.1250 </code></pre> <p>This will work in python 2.6 (I think they changed the print function in version 3).</p> <p>You should also realize that floating-point numbers can only be stored with a certain accuracy, so sometimes you will not get the exact same number back. For example 0.1 may be stored as something like 0.9999999987.</p>
0
2009-06-08T11:16:32Z
[ "python", "floating" ]
python formating float numbers
964,372
<p>my input is 3.23 , but when i use float on it , it becomes 3.2 , </p> <p>when my input is 3.00 , when i do float on it , it becomes 3.0 </p> <p>when i convert to float from string , i still want it to be 3.00 and not 3.0 is it possible? i want to know the code to make it possible , and when i am doing a problem in which the decimal point till 2 digits matter, 3.23 is better than 3.2 , for more precision</p>
-5
2009-06-08T11:05:02Z
964,419
<p>I suppose that what you want is to convert a float to a string with the number of decimals that you want. You can achieve that using %.3f (here 3 is the number of decimals that you want to print. For example:</p> <pre><code>&gt;&gt;&gt; print "Value: %.2f" % 3.0000 </code></pre> <p>Value: 3.00</p>
1
2009-06-08T11:16:43Z
[ "python", "floating" ]
python formating float numbers
964,372
<p>my input is 3.23 , but when i use float on it , it becomes 3.2 , </p> <p>when my input is 3.00 , when i do float on it , it becomes 3.0 </p> <p>when i convert to float from string , i still want it to be 3.00 and not 3.0 is it possible? i want to know the code to make it possible , and when i am doing a problem in which the decimal point till 2 digits matter, 3.23 is better than 3.2 , for more precision</p>
-5
2009-06-08T11:05:02Z
13,901,648
<p>Since this thread is first on the words "string formating decimal python", I think it's good to provide a more recent answer :</p> <pre><code>&gt;&gt;&gt; P=34.3234564 &gt;&gt;&gt; string="{:.2f}".format(P) &gt;&gt;&gt; string '34.32' </code></pre>
3
2012-12-16T13:17:49Z
[ "python", "floating" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
964,473
<p>You can do this with the <a href="http://docs.python.org/library/htmlparser.html" rel="nofollow">HTMLParser</a> module (complicated) or use regular expressions:</p> <pre><code>import re content = "asdf &lt;script&gt; bla &lt;/script&gt; end" x=re.search("&lt;script&gt;.*?&lt;/script&gt;", content, re.DOTALL) span = x.span() # gives (5, 27) stripped_content = content[:span[0]] + content[span[1]:] </code></pre> <p>EDIT: re.DOTALL, thanks to tgray</p>
0
2009-06-08T11:35:43Z
[ "javascript", "python" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
964,478
<p>I don't know Python good enough to tell you a solution. But if you want to use that to sanitize the user input you have to be very, very careful. Removing stuff between and just doesn't catch everything. Maybe you can have a look at existing solutions (I assume Django includes something like this).</p>
-1
2009-06-08T11:37:14Z
[ "javascript", "python" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
964,485
<p>You can use <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> with this (and other) methods:</p> <pre><code>soup = BeautifulSoup(source.lower()) to_extract = soup.findAll('script') for item in to_extract: item.extract() </code></pre> <p>This actually removes the nodes from the HTML. If you wanted to leave the empty <code>&lt;script&gt;&lt;/script&gt;</code> tags you'll have to work with the <code>item</code> attributes rather than just extracting it from the soup.</p>
25
2009-06-08T11:38:55Z
[ "javascript", "python" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
964,487
<p>If you're removing everything between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> why not just remove the entire node? </p> <p>Are you expecting a resig-style src and body?</p>
0
2009-06-08T11:39:43Z
[ "javascript", "python" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
964,518
<pre><code>example_text = "This is some text &lt;script&gt; blah blah blah &lt;/script&gt; this is some more text." import re myre = re.compile("(^.*)&lt;script&gt;(.*)&lt;/script&gt;(.*$)") result = myre.match(example_text) result.groups() &lt;52&gt; ('This is some text ', ' blah blah blah ', ' this is some more text.') # Text between &lt;script&gt; .. &lt;/script&gt; result.group(2) &lt;56&gt; 'blah blah blah' # Text outside of &lt;script&gt; .. &lt;/script&gt; result.group(1)+result.group(3) &lt;57&gt; 'This is some text this is some more text.' </code></pre>
-1
2009-06-08T11:48:16Z
[ "javascript", "python" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
964,699
<p>If you don't want to import any modules:</p> <pre><code>string = "&lt;script&gt; this is some js. begone! &lt;/script&gt;" string = string.split(' ') for i, s in enumerate(string): if s == '&lt;script&gt;' or s == '&lt;/script&gt;' : del string[i] print ' '.join(string) </code></pre>
-1
2009-06-08T12:34:37Z
[ "javascript", "python" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
964,727
<p>According to answers posted by Pev and wr, why not to upgrade a regular expression, e.g.:</p> <pre><code>pattern = r"(?is)&lt;script[^&gt;]*&gt;(.*?)&lt;/script&gt;" text = """&lt;script&gt;foo bar baz bar foo &lt;/script&gt;""" re.sub(pattern, '', text) </code></pre> <p>(?is) - added to ignore case and allow new lines in text. This version should also support script tags with attributes.</p> <p>EDIT: I can't add any comments yet, so I'm just editing my answer. I totally agree with the comment below, regexps are totally wrong for such tasks and b. soup ot lxml are a lot better. But question asked gave just a simple example and regexps should be enough for such simple task. Using Beautiful Soup for a simple text removing could just be too much (overload? I don't how to express what I mean, excuse my english).</p> <p>BTW I made a mistake, the code should look like this:</p> <pre><code>pattern = r"(?is)(&lt;script[^&gt;]*&gt;)(.*?)(&lt;/script&gt;)" text = """&lt;script&gt;foo bar baz bar foo &lt;/script&gt;""" re.sub(pattern, '\1\3', text) </code></pre>
0
2009-06-08T12:41:20Z
[ "javascript", "python" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
965,236
<p>Are you trying to prevent <a href="http://en.wikipedia.org/wiki/Cross-site%5Fscripting" rel="nofollow">XSS</a>? Just eliminating the <code>&lt;script&gt;</code> tags will not solve all possible attacks! Here's a great list of the many ways (some of them very creative) that you could be vulnerable <a href="http://ha.ckers.org/xss.html" rel="nofollow">http://ha.ckers.org/xss.html</a>. After reading this page you should understand why just elimintating the <code>&lt;script&gt;</code> tags using a regular expression is not robust enough. The python library <a href="http://codespeak.net/lxml/lxmlhtml.html#cleaning-up-html" rel="nofollow">lxml</a> has a function that will robustly clean your HTML to make it safe to display.</p> <p><strong>If</strong> you are sure that you just want to eliminate the <code>&lt;script&gt;</code> tags this code in lxml should work:</p> <pre><code>from lxml.html import parse root = parse(filename_or_url).getroot() for element in root.iter("script"): element.drop_tree() </code></pre> <p><strong>Note:</strong> I downvoted all the solutions using regular expresions. See here why you shouldn't parse HTML using regular expressions: <a href="http://stackoverflow.com/questions/590747/using-regular-expressions-to-parse-html-why-not">http://stackoverflow.com/questions/590747/using-regular-expressions-to-parse-html-why-not</a></p> <p><strong>Note 2:</strong> Another SO question showing HTML that is impossible to parse with regular expressions: <a href="http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-rege">http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-rege</a></p>
5
2009-06-08T14:45:21Z
[ "javascript", "python" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
965,840
<p><a href="http://diveintopython3.org/xml.html" rel="nofollow">Element Tree</a> is the best simplest and sweetest package to do this. Yes, there are other ways to do it too; but don't use any 'coz they suck! (via Mark Pilgrim)</p>
0
2009-06-08T16:45:19Z
[ "javascript", "python" ]
Patching classes in Python
964,532
<p>Suppose I have a Python class that I want to add an extra property to.</p> <p>Is there any difference between </p> <pre><code>import path.MyClass MyClass.foo = bar </code></pre> <p>and using something like :</p> <pre><code>import path.MyClass setattr(MyClass, 'foo', bar) </code></pre> <p>?</p> <p>If not, why do people seem to do the second rather than the first? (Eg. here <a href="http://concisionandconcinnity.blogspot.com/2008/10/chaining-monkey-patches-in-python.html" rel="nofollow">http://concisionandconcinnity.blogspot.com/2008/10/chaining-monkey-patches-in-python.html</a> )</p>
6
2009-06-08T11:53:38Z
964,551
<p>The statements are equivalent, but setattr might be used because it's the most dynamic choice of the two (with setattr you can use a variable for the attribute name.)</p> <p>See: <a href="http://docs.python.org/library/functions.html#setattr">http://docs.python.org/library/functions.html#setattr</a></p>
11
2009-06-08T11:57:28Z
[ "python", "class", "monkeypatching" ]
Django : Adding a property to the User class. Changing it at runtime and UserManager.create_user
964,569
<p>For various complicated reasons[1] I need to add extra properties to the Django User class.</p> <p>I can't use either Profile nor the "inheritance" way of doing this. (As in <a href="http://stackoverflow.com/questions/44109/extending-the-user-model-with-custom-fields-in-django">http://stackoverflow.com/questions/44109/extending-the-user-model-with-custom-fields-in-django</a> )</p> <p>So what I've been doing is including the User class in my local_settings file. And adding the property to it there.</p> <p>This, perhaps surprisingly, seems to work in many cases. But not when I create a new User from UserManager.create_user(). So I need to patch an alternative to the UserManager.create_user() method. Looking at the source for this (in contrib.auth.models.py) I find that the class it uses to create the User is kept in a property called UserManager.model rather than referenced directly.</p> <p>The line is this : </p> <p>user = self.model(None, username, '', '', email.strip().lower(), 'placeholder', False, True, False, now, now)</p> <p>The problem is that this self.model (which I assume contains a reference to the User class) doesn't seem to be my patched version.</p> <p>So, does anyone know where this self.model is set-up in the case of UserManager? And whether I'm correct in assuming that at that point the code hasn't gone through local_settings so my patch to the User class isn't there? And if there's a better place to patch the class?</p> <p>cheers</p> <p>phil</p> <p>[1] To satisfy the cur ious. I need to make the User class use a different and existing table in the database, which has extra fields and constraints.</p> <p>Update : For future reference, it looks like Proxy Models are the way that Django's going to support what I need : <a href="http://code.djangoproject.com/ticket/10356" rel="nofollow">http://code.djangoproject.com/ticket/10356</a></p>
2
2009-06-08T12:01:52Z
964,619
<p>The usual way of the having site-specific user fields is to specify a user profile table in your settings.py. You can then retrieve the specific settings via a the u.user_profile() method. It's very well documented in the docs.</p>
2
2009-06-08T12:13:04Z
[ "python", "django", "django-authentication", "patching" ]
Django : Adding a property to the User class. Changing it at runtime and UserManager.create_user
964,569
<p>For various complicated reasons[1] I need to add extra properties to the Django User class.</p> <p>I can't use either Profile nor the "inheritance" way of doing this. (As in <a href="http://stackoverflow.com/questions/44109/extending-the-user-model-with-custom-fields-in-django">http://stackoverflow.com/questions/44109/extending-the-user-model-with-custom-fields-in-django</a> )</p> <p>So what I've been doing is including the User class in my local_settings file. And adding the property to it there.</p> <p>This, perhaps surprisingly, seems to work in many cases. But not when I create a new User from UserManager.create_user(). So I need to patch an alternative to the UserManager.create_user() method. Looking at the source for this (in contrib.auth.models.py) I find that the class it uses to create the User is kept in a property called UserManager.model rather than referenced directly.</p> <p>The line is this : </p> <p>user = self.model(None, username, '', '', email.strip().lower(), 'placeholder', False, True, False, now, now)</p> <p>The problem is that this self.model (which I assume contains a reference to the User class) doesn't seem to be my patched version.</p> <p>So, does anyone know where this self.model is set-up in the case of UserManager? And whether I'm correct in assuming that at that point the code hasn't gone through local_settings so my patch to the User class isn't there? And if there's a better place to patch the class?</p> <p>cheers</p> <p>phil</p> <p>[1] To satisfy the cur ious. I need to make the User class use a different and existing table in the database, which has extra fields and constraints.</p> <p>Update : For future reference, it looks like Proxy Models are the way that Django's going to support what I need : <a href="http://code.djangoproject.com/ticket/10356" rel="nofollow">http://code.djangoproject.com/ticket/10356</a></p>
2
2009-06-08T12:01:52Z
965,245
<p>You probably just need to make sure that you do the replacement/addition/monkey patch as early as you can (before the auth application is actually installed). The trouble though is that the model classes do some meta-class stuff that'd probably explain why the UserManager has the wrong class - as it will generate the original class, set the UserManager up with that class, then you'll do your stuff and things won't be the same.</p> <p>So in short be brutal when you replace the class. If you can extend the original class, then replace the original with the extended version:</p> <pre> <code> import django.contrib.auth.models from django.contrib.auth.models import User as OriginalUser class User(OriginalUser): pass # add your extra fields etc # then patch the module with your new version django.contrib.auth.models.User = User </code> </pre> <p>Or if that doesn't work duplicate the User class in your new class and then patch it in.</p> <p>It's all a bit dirty, but it may do what you want.</p>
2
2009-06-08T14:47:17Z
[ "python", "django", "django-authentication", "patching" ]
Django : Adding a property to the User class. Changing it at runtime and UserManager.create_user
964,569
<p>For various complicated reasons[1] I need to add extra properties to the Django User class.</p> <p>I can't use either Profile nor the "inheritance" way of doing this. (As in <a href="http://stackoverflow.com/questions/44109/extending-the-user-model-with-custom-fields-in-django">http://stackoverflow.com/questions/44109/extending-the-user-model-with-custom-fields-in-django</a> )</p> <p>So what I've been doing is including the User class in my local_settings file. And adding the property to it there.</p> <p>This, perhaps surprisingly, seems to work in many cases. But not when I create a new User from UserManager.create_user(). So I need to patch an alternative to the UserManager.create_user() method. Looking at the source for this (in contrib.auth.models.py) I find that the class it uses to create the User is kept in a property called UserManager.model rather than referenced directly.</p> <p>The line is this : </p> <p>user = self.model(None, username, '', '', email.strip().lower(), 'placeholder', False, True, False, now, now)</p> <p>The problem is that this self.model (which I assume contains a reference to the User class) doesn't seem to be my patched version.</p> <p>So, does anyone know where this self.model is set-up in the case of UserManager? And whether I'm correct in assuming that at that point the code hasn't gone through local_settings so my patch to the User class isn't there? And if there's a better place to patch the class?</p> <p>cheers</p> <p>phil</p> <p>[1] To satisfy the cur ious. I need to make the User class use a different and existing table in the database, which has extra fields and constraints.</p> <p>Update : For future reference, it looks like Proxy Models are the way that Django's going to support what I need : <a href="http://code.djangoproject.com/ticket/10356" rel="nofollow">http://code.djangoproject.com/ticket/10356</a></p>
2
2009-06-08T12:01:52Z
966,806
<p>If Django 1.1 beta isn't too bleeding edge for you, try proxy models.</p>
2
2009-06-08T20:23:34Z
[ "python", "django", "django-authentication", "patching" ]
Find a HAL object based on /dev node path
964,801
<p>I'm using <code>python-dbus</code> to interface with HAL, and I need to find a device's UDI based on it's path in the <code>/dev</code> hierarchy.</p> <p>So given a path such as <code>/dev/sdb</code>, I want to get a value back like <code>/org/freedesktop/Hal/devices/usb_device_10</code>.</p>
2
2009-06-08T13:02:18Z
964,992
<p>I would spawn a <code>hal-find-by-property</code> call from Python:</p> <pre><code>import subprocess def get_UDI(path): cmd = 'hal-find-by-property --key block.device --string %s' % path proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) output = proc.communicate() # stdout return output[0].strip() print get_UDI('/dev/sdb') # /org/freedesktop/Hal/devices/xxxxxx </code></pre>
1
2009-06-08T13:44:30Z
[ "python", "dbus", "hal" ]
Find a HAL object based on /dev node path
964,801
<p>I'm using <code>python-dbus</code> to interface with HAL, and I need to find a device's UDI based on it's path in the <code>/dev</code> hierarchy.</p> <p>So given a path such as <code>/dev/sdb</code>, I want to get a value back like <code>/org/freedesktop/Hal/devices/usb_device_10</code>.</p>
2
2009-06-08T13:02:18Z
965,110
<p>Pure python solution:</p> <pre><code>import dbus bus = dbus.SystemBus() obj = bus.get_object("org.freedesktop.Hal", "/org/freedesktop/Hal/Manager") iface = dbus.Interface(obj, "org.freedesktop.Hal.Manager") print iface.FindDeviceStringMatch("block.device", "/dev/sda") </code></pre>
3
2009-06-08T14:15:25Z
[ "python", "dbus", "hal" ]
Python: Reading part of a text file
964,993
<p>HI all</p> <p>I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: </p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; </code></pre> <p>I need the <code>form</code>, <code>lemma</code> and <code>postag</code> information. e.g. for above I need <code>hibernis</code>, <code>hibernus1</code> and <code>n-p---nb-</code>.</p> <p>How do I tell python to read until it reaches form, to read forward until it reaches the quote mark <code>"</code> and then read the information between the quote marks <code>"hibernis"</code>? Really struggling with this. </p> <p>My attempts so far have been to remove the punctuation, split the sentence and then pull the info I need from a list. Having trouble getting python to iterate over whole file though, I can only get this working for 1 line. My code is below:</p> <pre><code>f=open('blank.txt','r') quotes=f.read() noquotes=quotes.replace('"','') f.close() rf=open('blank.txt','w') rf.write(noquotes) rf.close() f=open('blank.txt','r') finished = False postag=[] while not finished: line=f.readline() words=line.split() postag.append(words[4]) postag.append(words[6]) postag.append(words[8]) finished=True </code></pre> <p>Would appreciate any feedback/criticisms</p> <p>thanks</p>
4
2009-06-08T13:44:32Z
965,005
<p>I'd suggest using the regular expression module: <a href="http://docs.python.org/library/re.html" rel="nofollow">re</a></p> <p>Something along these lines perhaps?</p> <pre><code>#!/usr/bin/python import re if __name__ == '__main__': data = open('x').read() RE = re.compile('.*form="(.*)" lemma="(.*)" postag="(.*?)"', re.M) matches = RE.findall(data) for m in matches: print m </code></pre> <p>This does assume that the <code>&lt;word ...&gt;</code> lines are each on a single line and that each part is in that exact order, and that you don't need to deal with full xml parsing.</p>
2
2009-06-08T13:48:01Z
[ "python" ]
Python: Reading part of a text file
964,993
<p>HI all</p> <p>I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: </p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; </code></pre> <p>I need the <code>form</code>, <code>lemma</code> and <code>postag</code> information. e.g. for above I need <code>hibernis</code>, <code>hibernus1</code> and <code>n-p---nb-</code>.</p> <p>How do I tell python to read until it reaches form, to read forward until it reaches the quote mark <code>"</code> and then read the information between the quote marks <code>"hibernis"</code>? Really struggling with this. </p> <p>My attempts so far have been to remove the punctuation, split the sentence and then pull the info I need from a list. Having trouble getting python to iterate over whole file though, I can only get this working for 1 line. My code is below:</p> <pre><code>f=open('blank.txt','r') quotes=f.read() noquotes=quotes.replace('"','') f.close() rf=open('blank.txt','w') rf.write(noquotes) rf.close() f=open('blank.txt','r') finished = False postag=[] while not finished: line=f.readline() words=line.split() postag.append(words[4]) postag.append(words[6]) postag.append(words[8]) finished=True </code></pre> <p>Would appreciate any feedback/criticisms</p> <p>thanks</p>
4
2009-06-08T13:44:32Z
965,029
<p>Is your file proper XML? If so, try a SAX parser:</p> <pre><code>import xml.sax class Handler (xml.sax.ContentHandler): def startElement (self, tag, attrs): if tag == 'word': print 'form=', attrs['form'] print 'lemma=',attrs['lemma'] print 'postag=',attrs['postag'] ch = Handler () f = open ('myfile') xml.sax.parse (f, ch) </code></pre> <p>(this is rough .. it may not be entirely correct).</p>
1
2009-06-08T13:54:49Z
[ "python" ]
Python: Reading part of a text file
964,993
<p>HI all</p> <p>I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: </p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; </code></pre> <p>I need the <code>form</code>, <code>lemma</code> and <code>postag</code> information. e.g. for above I need <code>hibernis</code>, <code>hibernus1</code> and <code>n-p---nb-</code>.</p> <p>How do I tell python to read until it reaches form, to read forward until it reaches the quote mark <code>"</code> and then read the information between the quote marks <code>"hibernis"</code>? Really struggling with this. </p> <p>My attempts so far have been to remove the punctuation, split the sentence and then pull the info I need from a list. Having trouble getting python to iterate over whole file though, I can only get this working for 1 line. My code is below:</p> <pre><code>f=open('blank.txt','r') quotes=f.read() noquotes=quotes.replace('"','') f.close() rf=open('blank.txt','w') rf.write(noquotes) rf.close() f=open('blank.txt','r') finished = False postag=[] while not finished: line=f.readline() words=line.split() postag.append(words[4]) postag.append(words[6]) postag.append(words[8]) finished=True </code></pre> <p>Would appreciate any feedback/criticisms</p> <p>thanks</p>
4
2009-06-08T13:44:32Z
965,036
<p>In addition to the usual RegEx answer, since this appears to be a form of XML, you might try something like BeautifulSoup ( <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">http://www.crummy.com/software/BeautifulSoup/</a> )</p> <p>It's very easy to use, and find tags/attributes in things like HTML/XML, even if they're not "well formed". Might be worth a look. </p>
1
2009-06-08T13:55:51Z
[ "python" ]
Python: Reading part of a text file
964,993
<p>HI all</p> <p>I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: </p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; </code></pre> <p>I need the <code>form</code>, <code>lemma</code> and <code>postag</code> information. e.g. for above I need <code>hibernis</code>, <code>hibernus1</code> and <code>n-p---nb-</code>.</p> <p>How do I tell python to read until it reaches form, to read forward until it reaches the quote mark <code>"</code> and then read the information between the quote marks <code>"hibernis"</code>? Really struggling with this. </p> <p>My attempts so far have been to remove the punctuation, split the sentence and then pull the info I need from a list. Having trouble getting python to iterate over whole file though, I can only get this working for 1 line. My code is below:</p> <pre><code>f=open('blank.txt','r') quotes=f.read() noquotes=quotes.replace('"','') f.close() rf=open('blank.txt','w') rf.write(noquotes) rf.close() f=open('blank.txt','r') finished = False postag=[] while not finished: line=f.readline() words=line.split() postag.append(words[4]) postag.append(words[6]) postag.append(words[8]) finished=True </code></pre> <p>Would appreciate any feedback/criticisms</p> <p>thanks</p>
4
2009-06-08T13:44:32Z
965,040
<p>Parsing xml by hand is usually the wrong thing. For one thing, your code will break if there's an escaped quote in any of the attributes. Getting the attributes from an xml parser is probably cleaner and less error-prone.</p> <p>An approach like this can also run into problems parsing the entire file if you have lines that don't match the format. You can deal with this either by creating a parseline method (something like</p> <pre><code>def parse (line): try: return parsed values here except: </code></pre> <p>You can also simplify this with filter and map functions:</p> <pre><code>lines = filter( lambda line: parseable(line), f.readlines()) values = map (parse, lines) </code></pre>
0
2009-06-08T13:56:49Z
[ "python" ]
Python: Reading part of a text file
964,993
<p>HI all</p> <p>I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: </p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; </code></pre> <p>I need the <code>form</code>, <code>lemma</code> and <code>postag</code> information. e.g. for above I need <code>hibernis</code>, <code>hibernus1</code> and <code>n-p---nb-</code>.</p> <p>How do I tell python to read until it reaches form, to read forward until it reaches the quote mark <code>"</code> and then read the information between the quote marks <code>"hibernis"</code>? Really struggling with this. </p> <p>My attempts so far have been to remove the punctuation, split the sentence and then pull the info I need from a list. Having trouble getting python to iterate over whole file though, I can only get this working for 1 line. My code is below:</p> <pre><code>f=open('blank.txt','r') quotes=f.read() noquotes=quotes.replace('"','') f.close() rf=open('blank.txt','w') rf.write(noquotes) rf.close() f=open('blank.txt','r') finished = False postag=[] while not finished: line=f.readline() words=line.split() postag.append(words[4]) postag.append(words[6]) postag.append(words[8]) finished=True </code></pre> <p>Would appreciate any feedback/criticisms</p> <p>thanks</p>
4
2009-06-08T13:44:32Z
965,041
<p>Just to highlight your problem:</p> <pre><code>finished = False counter = 0 while not finished: counter += 1 finished=True print counter </code></pre>
0
2009-06-08T13:56:59Z
[ "python" ]
Python: Reading part of a text file
964,993
<p>HI all</p> <p>I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: </p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; </code></pre> <p>I need the <code>form</code>, <code>lemma</code> and <code>postag</code> information. e.g. for above I need <code>hibernis</code>, <code>hibernus1</code> and <code>n-p---nb-</code>.</p> <p>How do I tell python to read until it reaches form, to read forward until it reaches the quote mark <code>"</code> and then read the information between the quote marks <code>"hibernis"</code>? Really struggling with this. </p> <p>My attempts so far have been to remove the punctuation, split the sentence and then pull the info I need from a list. Having trouble getting python to iterate over whole file though, I can only get this working for 1 line. My code is below:</p> <pre><code>f=open('blank.txt','r') quotes=f.read() noquotes=quotes.replace('"','') f.close() rf=open('blank.txt','w') rf.write(noquotes) rf.close() f=open('blank.txt','r') finished = False postag=[] while not finished: line=f.readline() words=line.split() postag.append(words[4]) postag.append(words[6]) postag.append(words[8]) finished=True </code></pre> <p>Would appreciate any feedback/criticisms</p> <p>thanks</p>
4
2009-06-08T13:44:32Z
965,047
<p>With regular expressions, this is the gist (you can do the file.readline() part):</p> <pre><code>import re line = '&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt;' r = re.compile( 'form="([^"]*)".*lemma="([^"]*)".*postag="([^"]*)"' ) match = r.search( line ) print match.groups() &gt;&gt;&gt; ('hibernis', 'hibernus1', 'n-p---nb-') &gt;&gt;&gt; </code></pre>
0
2009-06-08T13:58:29Z
[ "python" ]
Python: Reading part of a text file
964,993
<p>HI all</p> <p>I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: </p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; </code></pre> <p>I need the <code>form</code>, <code>lemma</code> and <code>postag</code> information. e.g. for above I need <code>hibernis</code>, <code>hibernus1</code> and <code>n-p---nb-</code>.</p> <p>How do I tell python to read until it reaches form, to read forward until it reaches the quote mark <code>"</code> and then read the information between the quote marks <code>"hibernis"</code>? Really struggling with this. </p> <p>My attempts so far have been to remove the punctuation, split the sentence and then pull the info I need from a list. Having trouble getting python to iterate over whole file though, I can only get this working for 1 line. My code is below:</p> <pre><code>f=open('blank.txt','r') quotes=f.read() noquotes=quotes.replace('"','') f.close() rf=open('blank.txt','w') rf.write(noquotes) rf.close() f=open('blank.txt','r') finished = False postag=[] while not finished: line=f.readline() words=line.split() postag.append(words[4]) postag.append(words[6]) postag.append(words[8]) finished=True </code></pre> <p>Would appreciate any feedback/criticisms</p> <p>thanks</p>
4
2009-06-08T13:44:32Z
965,048
<p>First, don't spend a lot of time rewriting your file. It's generally a waste of time. The processing to clean up and parse the tags is so fast, that you'll be perfectly happy working from the source file all the time.</p> <pre><code>source= open( "blank.txt", "r" ) for line in source: # line has a tag-line structure # &lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; # Assumption -- no spaces in the quoted strings. parts = line.split() # parts is [ '&lt;word', 'id="8"', 'form="hibernis"', ... ] assert parts[0] == "&lt;word" nameValueList = [ part.partition('=') for part in parts[1:] ] # nameValueList is [ ('id','=','"8"'), ('form','=','"hibernis"'), ... ] attrs = dict( (n,eval(v)) for n, _, v in nameValueList ) # attrs is { 'id':'8', 'form':'hibernis', ... } print attrs['form'], attrs['lemma'], attrs['posttag'] </code></pre>
0
2009-06-08T13:58:32Z
[ "python" ]