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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Iterate over a string 2 (or n) characters at a time in Python | 1,162,592 | <p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p>
<p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite.</p>
<pre><code># Might not be exact, but you get the idea, use the step
# parameter of range() and slicing to grab 2 chars at a time
s = "+c-R+D-e"
for op, code in (s[i:i+2] for i in range(0, len(s), 2)):
print op, code
</code></pre>
<p>Are there some better/cleaner ways to do this?</p>
| 21 | 2009-07-22T01:24:53Z | 1,162,636 | <p>Dunno about cleaner, but there's another alternative:</p>
<pre><code>for (op, code) in zip(s[0::2], s[1::2]):
print op, code
</code></pre>
<p>A no-copy version:</p>
<pre><code>from itertools import izip, islice
for (op, code) in izip(islice(s, 0, None, 2), islice(s, 1, None, 2)):
print op, code
</code></pre>
| 32 | 2009-07-22T01:39:53Z | [
"python",
"iteration"
] |
Iterate over a string 2 (or n) characters at a time in Python | 1,162,592 | <p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p>
<p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite.</p>
<pre><code># Might not be exact, but you get the idea, use the step
# parameter of range() and slicing to grab 2 chars at a time
s = "+c-R+D-e"
for op, code in (s[i:i+2] for i in range(0, len(s), 2)):
print op, code
</code></pre>
<p>Are there some better/cleaner ways to do this?</p>
| 21 | 2009-07-22T01:24:53Z | 1,162,799 | <p>The other answers work well for n = 2, but for the general case you could try this:</p>
<pre><code>def slicen(s, n, truncate=False):
nslices = len(s) / n
if not truncate and (len(s) % n):
nslices += 1
return (s[i*n:n*(i+1)] for i in range(nslices))
>>> s = '+c-R+D-e'
>>> for op, code in slicen(s, 2):
... print op, code
...
+ c
- R
+ D
- e
>>> for a, b, c in slicen(s, 3):
... print a, b, c
...
+ c -
R + D
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: need more than 2 values to unpack
>>> for a, b, c in slicen(s,3,True):
... print a, b, c
...
+ c -
R + D
</code></pre>
| 2 | 2009-07-22T02:40:51Z | [
"python",
"iteration"
] |
Iterate over a string 2 (or n) characters at a time in Python | 1,162,592 | <p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p>
<p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite.</p>
<pre><code># Might not be exact, but you get the idea, use the step
# parameter of range() and slicing to grab 2 chars at a time
s = "+c-R+D-e"
for op, code in (s[i:i+2] for i in range(0, len(s), 2)):
print op, code
</code></pre>
<p>Are there some better/cleaner ways to do this?</p>
| 21 | 2009-07-22T01:24:53Z | 1,162,864 | <p>Great opportunity for a generator. For larger lists, this will be much more efficient than zipping every other elemnent. Note that this version also handles strings with dangling <code>op</code>s</p>
<pre><code>def opcodes(s):
while True:
try:
op = s[0]
code = s[1]
s = s[2:]
except IndexError:
return
yield op,code
for op,code in opcodes("+c-R+D-e"):
print op,code
</code></pre>
<p>edit: minor rewrite to avoid ValueError exceptions.</p>
| 2 | 2009-07-22T02:59:36Z | [
"python",
"iteration"
] |
Iterate over a string 2 (or n) characters at a time in Python | 1,162,592 | <p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p>
<p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite.</p>
<pre><code># Might not be exact, but you get the idea, use the step
# parameter of range() and slicing to grab 2 chars at a time
s = "+c-R+D-e"
for op, code in (s[i:i+2] for i in range(0, len(s), 2)):
print op, code
</code></pre>
<p>Are there some better/cleaner ways to do this?</p>
| 21 | 2009-07-22T01:24:53Z | 1,162,959 | <p><a href="http://stackoverflow.com/users/43089/triptych">Triptych</a> inspired this more general solution:</p>
<pre><code>def slicen(s, n, truncate=False):
assert n > 0
while len(s) >= n:
yield s[:n]
s = s[n:]
if len(s) and not truncate:
yield s
for op, code in slicen("+c-R+D-e", 2):
print op,code
</code></pre>
| 4 | 2009-07-22T03:43:59Z | [
"python",
"iteration"
] |
Iterate over a string 2 (or n) characters at a time in Python | 1,162,592 | <p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p>
<p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite.</p>
<pre><code># Might not be exact, but you get the idea, use the step
# parameter of range() and slicing to grab 2 chars at a time
s = "+c-R+D-e"
for op, code in (s[i:i+2] for i in range(0, len(s), 2)):
print op, code
</code></pre>
<p>Are there some better/cleaner ways to do this?</p>
| 21 | 2009-07-22T01:24:53Z | 1,163,166 | <p>Maybe not the most efficient, but if you like regexes...</p>
<pre><code>import re
s = "+c-R+D-e"
for op, code in re.findall('(.)(.)', s):
print op, code
</code></pre>
| 0 | 2009-07-22T05:10:23Z | [
"python",
"iteration"
] |
Iterate over a string 2 (or n) characters at a time in Python | 1,162,592 | <p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p>
<p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite.</p>
<pre><code># Might not be exact, but you get the idea, use the step
# parameter of range() and slicing to grab 2 chars at a time
s = "+c-R+D-e"
for op, code in (s[i:i+2] for i in range(0, len(s), 2)):
print op, code
</code></pre>
<p>Are there some better/cleaner ways to do this?</p>
| 21 | 2009-07-22T01:24:53Z | 19,699,417 | <p>This approach support an arbitrary number of elements per result, evaluates lazily, and the input iterable can be a generator (no indexing is attempted): </p>
<pre><code>import itertools
def groups_of_n(n, iterable):
c = itertools.count()
for _, gen in itertools.groupby(iterable, lambda x: c.next() / n):
yield gen
</code></pre>
<p>Any left-over elements are returned in a shorter list.</p>
<p>Example usage:</p>
<pre><code>for g in groups_of_n(4, xrange(21)):
print list(g)
[0, 1, 2, 3]
[4, 5, 6, 7]
[8, 9, 10, 11]
[12, 13, 14, 15]
[16, 17, 18, 19]
[20]
</code></pre>
| 2 | 2013-10-31T06:00:27Z | [
"python",
"iteration"
] |
Iterate over a string 2 (or n) characters at a time in Python | 1,162,592 | <p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p>
<p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite.</p>
<pre><code># Might not be exact, but you get the idea, use the step
# parameter of range() and slicing to grab 2 chars at a time
s = "+c-R+D-e"
for op, code in (s[i:i+2] for i in range(0, len(s), 2)):
print op, code
</code></pre>
<p>Are there some better/cleaner ways to do this?</p>
| 21 | 2009-07-22T01:24:53Z | 22,798,438 | <p>I ran into a similar problem. Ended doing something like this:</p>
<pre><code>ops = iter("+c-R+D-e")
for op in ops
code = ops.next()
print op, code
</code></pre>
<p>I felt it was the most readable.</p>
| 0 | 2014-04-01T22:53:01Z | [
"python",
"iteration"
] |
Iterate over a string 2 (or n) characters at a time in Python | 1,162,592 | <p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p>
<p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite.</p>
<pre><code># Might not be exact, but you get the idea, use the step
# parameter of range() and slicing to grab 2 chars at a time
s = "+c-R+D-e"
for op, code in (s[i:i+2] for i in range(0, len(s), 2)):
print op, code
</code></pre>
<p>Are there some better/cleaner ways to do this?</p>
| 21 | 2009-07-22T01:24:53Z | 23,211,888 | <p>Here's my answer, a little bit cleaner to my eyes:</p>
<pre class="lang-py prettyprint-override"><code>for i in range(0, len(string) - 1):
if i % 2 == 0:
print string[i:i+2]
</code></pre>
| 0 | 2014-04-22T06:21:50Z | [
"python",
"iteration"
] |
GQL Query on date equality in Python | 1,162,644 | <p>Ok, you guys were quick and helpful last time so I'm going back to the well ;)</p>
<p>Disclaimer: I'm new to python and very new to App Engine. What I'm trying to do is a simple modification of the example from the AppEngine tutorial.</p>
<p>I've got my date value being stored in my Memory class:</p>
<pre><code>class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty(auto_now_add=True)
</code></pre>
<p>and now I want to be able to lookup records for a certain date. I wasn't sure exactly how to do it so I tried a few things including:</p>
<pre><code>memories = db.GqlQuery("SELECT * from Memory where date = '2007-07-20')
and
memories = Memory.all()
memories.filter("date=", datetime.strptime(self.request.get('date'), '%Y-%m-%d').date())
and
memories = Memory.all()
memories.filter("date=", self.request.get('date'))
</code></pre>
<p>But every time I run it, I get an ImportError. Frankly, I'm not even sure how to parse these error message I get when the app fails but I'd just be happy to be able to look up the Memory records for a certain date.</p>
<p>EDIT: FULL SOURCE BELOW</p>
<pre><code>import cgi
import time
from datetime import datetime
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty()
class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
memories = db.GqlQuery('SELECT * from Memory ORDER BY date DESC LIMIT 10')
for memory in memories:
self.response.out.write('<b>%s</b> wrote: ' % memory.author.nickname())
self.response.out.write('<em>%s</em>' % memory.date)
self.response.out.write('<blockquote>%s</blockquote>' % cgi.escape(memory.content))
self.response.out.write("""
<div style="float: left;">
<form action="/post" method="post">
<fieldset>
<legend>Record</legend>
<div><label>Memory:</label><input type="text" name="content" /></textarea></div>
<div><label>Date:</label><input type="text" name="date" /></div>
<div><input type="submit" value="Record memory" /></div>
</fieldset>
</form>
</div>
<div style="float: left;">
<form action="/lookup" method="post">
<fieldset>
<legend>Lookup</legend>
<div><label>Date:</label><input type="text" name="date" /></div>
<div><input type="submit" value="Lookup memory" /></div>
</fieldset>
</form>
</div>""")
self.response.out.write('</body></html>')
class PostMemory(webapp.RequestHandler):
def post(self):
memory = Memory()
if users.get_current_user():
memory.author = users.get_current_user()
memory.content = self.request.get('content')
memory.date = datetime.strptime(self.request.get('date'), '%Y-%m-%d').date()
memory.put()
self.redirect('/')
class LookupMemory(webapp.RequestHandler):
def post(self):
memories = db.GqlQuery("SELECT * FROM Memory WHERE date = '2009-07-21'")
for memory in memories:
self.response.out.write('<b>%s</b> wrote: ' % memory.author.nickname())
self.response.out.write('<em>%s</em>' % memory.date)
self.response.out.write('<blockquote>%s</blockquote>' % cgi.escape(memory.content))
application = webapp.WSGIApplication([('/', MainPage), ('/post', PostMemory), ('/lookup', LookupMemory)], debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
</code></pre>
| 0 | 2009-07-22T01:41:31Z | 1,162,879 | <pre><code>memories.filter("date=DATE(2007, 7, 20)")
</code></pre>
<p>Refer to <a href="http://code.google.com/appengine/docs/python/datastore/gqlreference.html" rel="nofollow">GQL Reference</a>.</p>
| 1 | 2009-07-22T03:06:46Z | [
"python",
"google-app-engine"
] |
GQL Query on date equality in Python | 1,162,644 | <p>Ok, you guys were quick and helpful last time so I'm going back to the well ;)</p>
<p>Disclaimer: I'm new to python and very new to App Engine. What I'm trying to do is a simple modification of the example from the AppEngine tutorial.</p>
<p>I've got my date value being stored in my Memory class:</p>
<pre><code>class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty(auto_now_add=True)
</code></pre>
<p>and now I want to be able to lookup records for a certain date. I wasn't sure exactly how to do it so I tried a few things including:</p>
<pre><code>memories = db.GqlQuery("SELECT * from Memory where date = '2007-07-20')
and
memories = Memory.all()
memories.filter("date=", datetime.strptime(self.request.get('date'), '%Y-%m-%d').date())
and
memories = Memory.all()
memories.filter("date=", self.request.get('date'))
</code></pre>
<p>But every time I run it, I get an ImportError. Frankly, I'm not even sure how to parse these error message I get when the app fails but I'd just be happy to be able to look up the Memory records for a certain date.</p>
<p>EDIT: FULL SOURCE BELOW</p>
<pre><code>import cgi
import time
from datetime import datetime
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty()
class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
memories = db.GqlQuery('SELECT * from Memory ORDER BY date DESC LIMIT 10')
for memory in memories:
self.response.out.write('<b>%s</b> wrote: ' % memory.author.nickname())
self.response.out.write('<em>%s</em>' % memory.date)
self.response.out.write('<blockquote>%s</blockquote>' % cgi.escape(memory.content))
self.response.out.write("""
<div style="float: left;">
<form action="/post" method="post">
<fieldset>
<legend>Record</legend>
<div><label>Memory:</label><input type="text" name="content" /></textarea></div>
<div><label>Date:</label><input type="text" name="date" /></div>
<div><input type="submit" value="Record memory" /></div>
</fieldset>
</form>
</div>
<div style="float: left;">
<form action="/lookup" method="post">
<fieldset>
<legend>Lookup</legend>
<div><label>Date:</label><input type="text" name="date" /></div>
<div><input type="submit" value="Lookup memory" /></div>
</fieldset>
</form>
</div>""")
self.response.out.write('</body></html>')
class PostMemory(webapp.RequestHandler):
def post(self):
memory = Memory()
if users.get_current_user():
memory.author = users.get_current_user()
memory.content = self.request.get('content')
memory.date = datetime.strptime(self.request.get('date'), '%Y-%m-%d').date()
memory.put()
self.redirect('/')
class LookupMemory(webapp.RequestHandler):
def post(self):
memories = db.GqlQuery("SELECT * FROM Memory WHERE date = '2009-07-21'")
for memory in memories:
self.response.out.write('<b>%s</b> wrote: ' % memory.author.nickname())
self.response.out.write('<em>%s</em>' % memory.date)
self.response.out.write('<blockquote>%s</blockquote>' % cgi.escape(memory.content))
application = webapp.WSGIApplication([('/', MainPage), ('/post', PostMemory), ('/lookup', LookupMemory)], debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
</code></pre>
| 0 | 2009-07-22T01:41:31Z | 1,163,586 | <pre><code>class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty(auto_now_add=True)
</code></pre>
<p>I think that you are either getting import errors for memory or your are getting an import error for datetime</p>
<p>if Memory is in another .py file, e.g otherpyfile.py, you will need to do <code>from otherpyfile import Memory</code> and then use it that way</p>
<p>if its a datetime issue then you will need to <code>import datetime</code>. Your first answer had a mismatch of quotes so sorted that. I sorted your middle one so that if you import datetime </p>
<pre><code>memories = db.GqlQuery("SELECT * from Memory where date = '2007-07-20'")
memories = Memory.all().filter("date=", datetime.datetime.strptime(self.request.get('date'), '%Y-%m-%d').date())
memories = Memory.all().filter("date=", self.request.get('date'))
</code></pre>
<p>The appengine error screen isn't always helpful so have a look at the logs that are being thrown in the command prompt. If you see that error it might be worth dumping the short stacktrace it does so I can try help you further.</p>
| 0 | 2009-07-22T07:18:48Z | [
"python",
"google-app-engine"
] |
GQL Query on date equality in Python | 1,162,644 | <p>Ok, you guys were quick and helpful last time so I'm going back to the well ;)</p>
<p>Disclaimer: I'm new to python and very new to App Engine. What I'm trying to do is a simple modification of the example from the AppEngine tutorial.</p>
<p>I've got my date value being stored in my Memory class:</p>
<pre><code>class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty(auto_now_add=True)
</code></pre>
<p>and now I want to be able to lookup records for a certain date. I wasn't sure exactly how to do it so I tried a few things including:</p>
<pre><code>memories = db.GqlQuery("SELECT * from Memory where date = '2007-07-20')
and
memories = Memory.all()
memories.filter("date=", datetime.strptime(self.request.get('date'), '%Y-%m-%d').date())
and
memories = Memory.all()
memories.filter("date=", self.request.get('date'))
</code></pre>
<p>But every time I run it, I get an ImportError. Frankly, I'm not even sure how to parse these error message I get when the app fails but I'd just be happy to be able to look up the Memory records for a certain date.</p>
<p>EDIT: FULL SOURCE BELOW</p>
<pre><code>import cgi
import time
from datetime import datetime
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty()
class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
memories = db.GqlQuery('SELECT * from Memory ORDER BY date DESC LIMIT 10')
for memory in memories:
self.response.out.write('<b>%s</b> wrote: ' % memory.author.nickname())
self.response.out.write('<em>%s</em>' % memory.date)
self.response.out.write('<blockquote>%s</blockquote>' % cgi.escape(memory.content))
self.response.out.write("""
<div style="float: left;">
<form action="/post" method="post">
<fieldset>
<legend>Record</legend>
<div><label>Memory:</label><input type="text" name="content" /></textarea></div>
<div><label>Date:</label><input type="text" name="date" /></div>
<div><input type="submit" value="Record memory" /></div>
</fieldset>
</form>
</div>
<div style="float: left;">
<form action="/lookup" method="post">
<fieldset>
<legend>Lookup</legend>
<div><label>Date:</label><input type="text" name="date" /></div>
<div><input type="submit" value="Lookup memory" /></div>
</fieldset>
</form>
</div>""")
self.response.out.write('</body></html>')
class PostMemory(webapp.RequestHandler):
def post(self):
memory = Memory()
if users.get_current_user():
memory.author = users.get_current_user()
memory.content = self.request.get('content')
memory.date = datetime.strptime(self.request.get('date'), '%Y-%m-%d').date()
memory.put()
self.redirect('/')
class LookupMemory(webapp.RequestHandler):
def post(self):
memories = db.GqlQuery("SELECT * FROM Memory WHERE date = '2009-07-21'")
for memory in memories:
self.response.out.write('<b>%s</b> wrote: ' % memory.author.nickname())
self.response.out.write('<em>%s</em>' % memory.date)
self.response.out.write('<blockquote>%s</blockquote>' % cgi.escape(memory.content))
application = webapp.WSGIApplication([('/', MainPage), ('/post', PostMemory), ('/lookup', LookupMemory)], debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
</code></pre>
| 0 | 2009-07-22T01:41:31Z | 1,165,432 | <p>You're trying to use GQL syntax with non-GQL Query objects. Your options are:</p>
<ol>
<li>Use the Query object and pass in a datetime.date object: <code>q = Memory.all().filter("date =", datetime.date.today())</code></li>
<li>Use a GqlQuery and use the DATE syntax: <code>q = db.GqlQuery("SELECT * FROM Memory WHERE date = DATE(2007, 07, 20)")</code></li>
<li>Use a GqlQuery and pass in a datetime.date object: <code>q = db.GqlQuery("SELECT * FROM Memory WHERE date = :1", datetime.date.today())</code></li>
</ol>
| 2 | 2009-07-22T13:53:42Z | [
"python",
"google-app-engine"
] |
How would you model this database relationship? | 1,162,877 | <p>I'm modeling a database relationship in django, and I'd like to have other opinions. The relationship is kind of a two-to-many relationship. For example, a patient can have two physicians: an attending and a primary. A physician obviously has many patients.</p>
<p>The application does need to know which one is which; further, there are cases where an attending physician of one patient can be the primary of another. Lastly, both attending and primary are often the same. </p>
<p>At first, I was thinking two foreign keys from the patient table into the physician table. However, I think django disallows this. Additionally, on second thought, this is really a many(two)-to-many relationship.</p>
<p>Therefore, how can I model this relationship with django while maintaining the physician type as it pertains to a patient? Perhaps I will need to store the physician type on the many-to-many association table?</p>
<p>Thanks,
Pete</p>
| 2 | 2009-07-22T03:05:08Z | 1,162,884 | <p>I agree with your conclusion. I would store the physician type in the many-to-many linking table.</p>
| 0 | 2009-07-22T03:08:40Z | [
"python",
"database",
"django",
"database-design"
] |
How would you model this database relationship? | 1,162,877 | <p>I'm modeling a database relationship in django, and I'd like to have other opinions. The relationship is kind of a two-to-many relationship. For example, a patient can have two physicians: an attending and a primary. A physician obviously has many patients.</p>
<p>The application does need to know which one is which; further, there are cases where an attending physician of one patient can be the primary of another. Lastly, both attending and primary are often the same. </p>
<p>At first, I was thinking two foreign keys from the patient table into the physician table. However, I think django disallows this. Additionally, on second thought, this is really a many(two)-to-many relationship.</p>
<p>Therefore, how can I model this relationship with django while maintaining the physician type as it pertains to a patient? Perhaps I will need to store the physician type on the many-to-many association table?</p>
<p>Thanks,
Pete</p>
| 2 | 2009-07-22T03:05:08Z | 1,162,892 | <p>Consider using a many-to-many join table. Use application logic to prevent more than two physicians per patient.</p>
<pre><code>Physician
Physician_ID
...
Patient
Patient_ID
...
Physician_Patient
Physician_ID int not null
Patient_ID int not null
Type ENUM ('Primary', 'Attending')
PRIMARY KEY (Physician_ID, Patient_ID)
KEY (Patient_ID)
</code></pre>
| 1 | 2009-07-22T03:11:13Z | [
"python",
"database",
"django",
"database-design"
] |
How would you model this database relationship? | 1,162,877 | <p>I'm modeling a database relationship in django, and I'd like to have other opinions. The relationship is kind of a two-to-many relationship. For example, a patient can have two physicians: an attending and a primary. A physician obviously has many patients.</p>
<p>The application does need to know which one is which; further, there are cases where an attending physician of one patient can be the primary of another. Lastly, both attending and primary are often the same. </p>
<p>At first, I was thinking two foreign keys from the patient table into the physician table. However, I think django disallows this. Additionally, on second thought, this is really a many(two)-to-many relationship.</p>
<p>Therefore, how can I model this relationship with django while maintaining the physician type as it pertains to a patient? Perhaps I will need to store the physician type on the many-to-many association table?</p>
<p>Thanks,
Pete</p>
| 2 | 2009-07-22T03:05:08Z | 1,162,901 | <p>How about something like this:</p>
<pre><code>class Patient(models.Model):
primary_physician = models.ForeignKey('Physician', related_name='primary_patients')
attending_physicial = models.ForeignKey('Physician', related_name='attending_patients')
</code></pre>
<p>This allows you to have two foreign keys to the same model; the <code>Physician</code> model will also have fields called <code>primary_patients</code> and <code>attending_patients</code>.</p>
| 10 | 2009-07-22T03:14:48Z | [
"python",
"database",
"django",
"database-design"
] |
Cost of scaling Rails vs cost of scaling PHP vs Python frameworks | 1,163,012 | <p>I guess this question has been asked a lot around. I know <strong>Rails can scale</strong> because I have worked on it and it's awesome. And there is not much doubt about that as far as PHP frameworks are concerned.</p>
<p>I don't want to know which frameworks are better.</p>
<p>How much is difference in cost of scaling Rails vs other frameworks (PHP, Python) assuming a large app with 1 million visits per month?</p>
<p>This is something I get asked a lot. I can explain to people that "Rails does scale pretty well" but in the long run, what are the economics?</p>
<p>If somebody can provide some metrics, that'd be great.</p>
| 7 | 2009-07-22T04:07:29Z | 1,163,208 | <p>One major factor in this is that isn't affected by choice of framework is database access. No matter what approach you take, you likely put data in a relational database. Then the question is how efficiently you can get the data out of the database. This primarily depends on the RDBMS (Oracle vs. Postgres vs. MySQL), and not on the framework - except that some data mapping library may make inefficient use of SQL.</p>
<p>For the pure "number of visits" parameter, the question really is how fast your HTML templating system works. So the question is: how many pages can you render per second? I would make this the primary metrics to determine how good a system would scale.</p>
<p>Of course, different pages may have different costs; for some, you can use caching, but not for others. So in measuring scalability, split your 1 million visits into cheap and expensive pages, and measure them separately. Together, they should give a good estimate of the load your system can take (or the number of systems you need to satisfy demand).</p>
<p>There is also the issue of memory usage. If you have the data in SQL, this shouldn't matter - but with caching, you may also need to consider scalability wrt. main memory usage.</p>
| 5 | 2009-07-22T05:27:53Z | [
"php",
"python",
"ruby-on-rails",
"scaling"
] |
Cost of scaling Rails vs cost of scaling PHP vs Python frameworks | 1,163,012 | <p>I guess this question has been asked a lot around. I know <strong>Rails can scale</strong> because I have worked on it and it's awesome. And there is not much doubt about that as far as PHP frameworks are concerned.</p>
<p>I don't want to know which frameworks are better.</p>
<p>How much is difference in cost of scaling Rails vs other frameworks (PHP, Python) assuming a large app with 1 million visits per month?</p>
<p>This is something I get asked a lot. I can explain to people that "Rails does scale pretty well" but in the long run, what are the economics?</p>
<p>If somebody can provide some metrics, that'd be great.</p>
| 7 | 2009-07-22T04:07:29Z | 1,163,341 | <p>IMHO I don't think the cost of scaling is going to be any different between those three because none of them have "scalability batteries" included. I just don't see any huge architectural differences between those three choices that would cause a significant difference in scaling.</p>
<p>In other words, your application architecture is going to dominate how the application scales regardless of which of the three languages.</p>
<p>If you need memory caching you're going to at least use memcached (or something similar which will interface with all three languages). Maybe you help your scalability using nginx to serve directly from memcache, but that's obviously not going to change the performance of php/perl/python/ruby.</p>
<p>If you use MySQL or Postgresql you're still going to have to design your database correctly for scaling regardless of your app language, and any tool you use to start clustering / mirroring is going to be outside of your app.</p>
<p>I think in terms of memory usage Python (with mod_wsgi daemon mode) and Ruby (enterprise ruby with passenger/mod_rack) have pretty decent footprints at least comparable to PHP under fcgi and probably better than PHP under mod_php (i.e. apache MPM prefork + php in all the apache processes sucks a lot of memory).</p>
<p>Where this question might be interesting is trying to compare those 3 languages vs. something like Erlang where you (supposedly) have cheap built-in scalability automatically in all Erlang processes, but even then you'll have a RDBMS database bottleneck unless your app nicely fits into one of the Erlang database ways of doing things, e.g. couchdb.</p>
| 4 | 2009-07-22T06:16:17Z | [
"php",
"python",
"ruby-on-rails",
"scaling"
] |
Cost of scaling Rails vs cost of scaling PHP vs Python frameworks | 1,163,012 | <p>I guess this question has been asked a lot around. I know <strong>Rails can scale</strong> because I have worked on it and it's awesome. And there is not much doubt about that as far as PHP frameworks are concerned.</p>
<p>I don't want to know which frameworks are better.</p>
<p>How much is difference in cost of scaling Rails vs other frameworks (PHP, Python) assuming a large app with 1 million visits per month?</p>
<p>This is something I get asked a lot. I can explain to people that "Rails does scale pretty well" but in the long run, what are the economics?</p>
<p>If somebody can provide some metrics, that'd be great.</p>
| 7 | 2009-07-22T04:07:29Z | 18,622,672 | <p>Unfortunately, I do not know any cost comparison of Rails, PHP and Django. But I do know a cost comparison of some Java Web Frameworks: Spring(9k$), Wicket(59k$) , GWT(6k$) and JSF(49k$). </p>
<p>You have the original conference here: </p>
<p><a href="http://www.devoxx.com/display/DV11/WWW++World+Wide+Wait++A+Performance+Comparison+of+Java+Web+Frameworks" rel="nofollow">http://www.devoxx.com/display/DV11/WWW++World+Wide+Wait++A+Performance+Comparison+of+Java+Web+Frameworks</a> </p>
<p>There you have a post about it(shorter):</p>
<p><a href="http://blog.websitesframeworks.com/2013/03/web-frameworks-benchmarks-192/" rel="nofollow">http://blog.websitesframeworks.com/2013/03/web-frameworks-benchmarks-192/</a></p>
<p>If you want to try to infere about this cost. You could cross this data with the bencharmk proposed by Techempower:</p>
<p><a href="http://www.techempower.com/benchmarks/" rel="nofollow">http://www.techempower.com/benchmarks/</a></p>
<p>So, if you know Spring is pretty cheap compare to Wicket and Django/Rails have worse marks in benchmarks than Wicket and Spring, it probably means they will represent a higher cost. </p>
<p>Hope it helps. </p>
| 1 | 2013-09-04T19:55:08Z | [
"php",
"python",
"ruby-on-rails",
"scaling"
] |
Authenticated commenting in Django 1.1? | 1,163,113 | <p>(Now that Django 1.1 is in release candidate status, it could be a good time to ask this.)</p>
<p>I've been searing everywhere for ways to extend Django's comments app to support authenticated comments. After reading through the comments model a few times, I found that a <code>ForeignKey</code> to <code>User</code> already exists.</p>
<p>From <code>django.contrib.comments.models</code>:</p>
<pre><code>class Comment(BaseCommentAbstractModel):
"""
A user comment about some object.
"""
# Who posted this comment? If ``user`` is set then it was an authenticated
# user; otherwise at least user_name should have been set and the comment
# was posted by a non-authenticated user.
user = models.ForeignKey(User, verbose_name=_('user'),
blank=True, null=True, related_name="%(class)s_comments")
user_name = models.CharField(_("user's name"), max_length=50, blank=True)
user_email = models.EmailField(_("user's email address"), blank=True)
user_url = models.URLField(_("user's URL"), blank=True)
</code></pre>
<p><strong>I can't seem to get my head around setting <code>user</code>.</strong> If I use comments as is, even if I'm authenticated, it still seems to require the other fields. I'm guessing I should override the form and do it there? On top of that, if I use <code>user</code>, I should ignore the fact that <code>user_name</code>, <code>user_email</code> and <code>user_url</code> will be empty and just pull that information from a related profile model, correct?</p>
<p>While the answers could be quite trivial in the end, I'm just surprised that it hasn't been written or even talked about.</p>
| 6 | 2009-07-22T04:45:45Z | 1,163,165 | <p>Use a Profile model for extra account data besides user name and password. You can call user.get_profile() if you include this line in Profile:</p>
<pre><code>user = models.ForeignKey(User, unique=True)
</code></pre>
<p>and this line in settings.py:</p>
<pre><code>AUTH_PROFILE_MODULE = 'yourapp.Profile'
</code></pre>
| 1 | 2009-07-22T05:10:07Z | [
"python",
"django",
"comments"
] |
Authenticated commenting in Django 1.1? | 1,163,113 | <p>(Now that Django 1.1 is in release candidate status, it could be a good time to ask this.)</p>
<p>I've been searing everywhere for ways to extend Django's comments app to support authenticated comments. After reading through the comments model a few times, I found that a <code>ForeignKey</code> to <code>User</code> already exists.</p>
<p>From <code>django.contrib.comments.models</code>:</p>
<pre><code>class Comment(BaseCommentAbstractModel):
"""
A user comment about some object.
"""
# Who posted this comment? If ``user`` is set then it was an authenticated
# user; otherwise at least user_name should have been set and the comment
# was posted by a non-authenticated user.
user = models.ForeignKey(User, verbose_name=_('user'),
blank=True, null=True, related_name="%(class)s_comments")
user_name = models.CharField(_("user's name"), max_length=50, blank=True)
user_email = models.EmailField(_("user's email address"), blank=True)
user_url = models.URLField(_("user's URL"), blank=True)
</code></pre>
<p><strong>I can't seem to get my head around setting <code>user</code>.</strong> If I use comments as is, even if I'm authenticated, it still seems to require the other fields. I'm guessing I should override the form and do it there? On top of that, if I use <code>user</code>, I should ignore the fact that <code>user_name</code>, <code>user_email</code> and <code>user_url</code> will be empty and just pull that information from a related profile model, correct?</p>
<p>While the answers could be quite trivial in the end, I'm just surprised that it hasn't been written or even talked about.</p>
| 6 | 2009-07-22T04:45:45Z | 1,163,803 | <p>According to the comment, it's either-or: the other fields are meant to be used when <code>user</code> <em>isn't</em> set. Have you checked that the relevant columns are definitely NOT NULL? They're marked as <code>blank=True</code> which normally means <code>required=False</code> at the field level. If you have actually tried it, what errors are you getting?</p>
| 0 | 2009-07-22T08:19:35Z | [
"python",
"django",
"comments"
] |
Authenticated commenting in Django 1.1? | 1,163,113 | <p>(Now that Django 1.1 is in release candidate status, it could be a good time to ask this.)</p>
<p>I've been searing everywhere for ways to extend Django's comments app to support authenticated comments. After reading through the comments model a few times, I found that a <code>ForeignKey</code> to <code>User</code> already exists.</p>
<p>From <code>django.contrib.comments.models</code>:</p>
<pre><code>class Comment(BaseCommentAbstractModel):
"""
A user comment about some object.
"""
# Who posted this comment? If ``user`` is set then it was an authenticated
# user; otherwise at least user_name should have been set and the comment
# was posted by a non-authenticated user.
user = models.ForeignKey(User, verbose_name=_('user'),
blank=True, null=True, related_name="%(class)s_comments")
user_name = models.CharField(_("user's name"), max_length=50, blank=True)
user_email = models.EmailField(_("user's email address"), blank=True)
user_url = models.URLField(_("user's URL"), blank=True)
</code></pre>
<p><strong>I can't seem to get my head around setting <code>user</code>.</strong> If I use comments as is, even if I'm authenticated, it still seems to require the other fields. I'm guessing I should override the form and do it there? On top of that, if I use <code>user</code>, I should ignore the fact that <code>user_name</code>, <code>user_email</code> and <code>user_url</code> will be empty and just pull that information from a related profile model, correct?</p>
<p>While the answers could be quite trivial in the end, I'm just surprised that it hasn't been written or even talked about.</p>
| 6 | 2009-07-22T04:45:45Z | 1,164,400 | <p>First off, the comments app already supports both authenticated and anonymous users, so I assume you want to accept comments from authenticated users only?</p>
<p>Thejaswi Puthraya had a <a href="http://thejaswi.info/blog/2008/11/19/part-1-django-comments-authenticated-users/" rel="nofollow">series</a> of <a href="http://thejaswi.info/blog/2008/11/20/part-2-django-comments-authenticated-users/" rel="nofollow">articles</a> on his blog addressing this. Basically, he pre-populates the <code>name</code> and <code>email</code> fields in the comment form and replaces them with hidden fields, then defines a wrapper view around <code>post_comment</code> to ensure the user posting the comment is the same as the logged-in user, among other things. Seemed pretty straightforward, though maybe a tad tedious.</p>
<p>His blog seems to be down presently...hopefully it's only temporary.</p>
| 1 | 2009-07-22T10:37:25Z | [
"python",
"django",
"comments"
] |
Authenticated commenting in Django 1.1? | 1,163,113 | <p>(Now that Django 1.1 is in release candidate status, it could be a good time to ask this.)</p>
<p>I've been searing everywhere for ways to extend Django's comments app to support authenticated comments. After reading through the comments model a few times, I found that a <code>ForeignKey</code> to <code>User</code> already exists.</p>
<p>From <code>django.contrib.comments.models</code>:</p>
<pre><code>class Comment(BaseCommentAbstractModel):
"""
A user comment about some object.
"""
# Who posted this comment? If ``user`` is set then it was an authenticated
# user; otherwise at least user_name should have been set and the comment
# was posted by a non-authenticated user.
user = models.ForeignKey(User, verbose_name=_('user'),
blank=True, null=True, related_name="%(class)s_comments")
user_name = models.CharField(_("user's name"), max_length=50, blank=True)
user_email = models.EmailField(_("user's email address"), blank=True)
user_url = models.URLField(_("user's URL"), blank=True)
</code></pre>
<p><strong>I can't seem to get my head around setting <code>user</code>.</strong> If I use comments as is, even if I'm authenticated, it still seems to require the other fields. I'm guessing I should override the form and do it there? On top of that, if I use <code>user</code>, I should ignore the fact that <code>user_name</code>, <code>user_email</code> and <code>user_url</code> will be empty and just pull that information from a related profile model, correct?</p>
<p>While the answers could be quite trivial in the end, I'm just surprised that it hasn't been written or even talked about.</p>
| 6 | 2009-07-22T04:45:45Z | 1,193,040 | <p>I recommend that when you come up with a question about Django internals, you take a look at the source.</p>
<p>If we look at the <a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/comments/views/comments.py#L32" rel="nofollow">start of post_comment view</a> we see that the POST querydict is copied and the user's email and name are inserted. They are still required (as seen in the <a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/comments/views/comments.py#L32" rel="nofollow">form's source</a>), so these details must either entered in the form or the user must provide them.</p>
<p>To answer your question to Superjoe, the view attaches the user to the comment before it is saved (as seen <a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/comments/views/comments.py#L94" rel="nofollow">near the end of the post_comment view</a>).</p>
| 3 | 2009-07-28T09:45:07Z | [
"python",
"django",
"comments"
] |
Authenticated commenting in Django 1.1? | 1,163,113 | <p>(Now that Django 1.1 is in release candidate status, it could be a good time to ask this.)</p>
<p>I've been searing everywhere for ways to extend Django's comments app to support authenticated comments. After reading through the comments model a few times, I found that a <code>ForeignKey</code> to <code>User</code> already exists.</p>
<p>From <code>django.contrib.comments.models</code>:</p>
<pre><code>class Comment(BaseCommentAbstractModel):
"""
A user comment about some object.
"""
# Who posted this comment? If ``user`` is set then it was an authenticated
# user; otherwise at least user_name should have been set and the comment
# was posted by a non-authenticated user.
user = models.ForeignKey(User, verbose_name=_('user'),
blank=True, null=True, related_name="%(class)s_comments")
user_name = models.CharField(_("user's name"), max_length=50, blank=True)
user_email = models.EmailField(_("user's email address"), blank=True)
user_url = models.URLField(_("user's URL"), blank=True)
</code></pre>
<p><strong>I can't seem to get my head around setting <code>user</code>.</strong> If I use comments as is, even if I'm authenticated, it still seems to require the other fields. I'm guessing I should override the form and do it there? On top of that, if I use <code>user</code>, I should ignore the fact that <code>user_name</code>, <code>user_email</code> and <code>user_url</code> will be empty and just pull that information from a related profile model, correct?</p>
<p>While the answers could be quite trivial in the end, I'm just surprised that it hasn't been written or even talked about.</p>
| 6 | 2009-07-22T04:45:45Z | 1,229,332 | <p>Theju wrote an authenticated comments app â <a href="http://thejaswi.info/tech/blog/2009/08/04/reusable-app-authenticated-comments/" rel="nofollow">http://thejaswi.info/tech/blog/2009/08/04/reusable-app-authenticated-comments/</a></p>
| 1 | 2009-08-04T19:05:58Z | [
"python",
"django",
"comments"
] |
Authenticated commenting in Django 1.1? | 1,163,113 | <p>(Now that Django 1.1 is in release candidate status, it could be a good time to ask this.)</p>
<p>I've been searing everywhere for ways to extend Django's comments app to support authenticated comments. After reading through the comments model a few times, I found that a <code>ForeignKey</code> to <code>User</code> already exists.</p>
<p>From <code>django.contrib.comments.models</code>:</p>
<pre><code>class Comment(BaseCommentAbstractModel):
"""
A user comment about some object.
"""
# Who posted this comment? If ``user`` is set then it was an authenticated
# user; otherwise at least user_name should have been set and the comment
# was posted by a non-authenticated user.
user = models.ForeignKey(User, verbose_name=_('user'),
blank=True, null=True, related_name="%(class)s_comments")
user_name = models.CharField(_("user's name"), max_length=50, blank=True)
user_email = models.EmailField(_("user's email address"), blank=True)
user_url = models.URLField(_("user's URL"), blank=True)
</code></pre>
<p><strong>I can't seem to get my head around setting <code>user</code>.</strong> If I use comments as is, even if I'm authenticated, it still seems to require the other fields. I'm guessing I should override the form and do it there? On top of that, if I use <code>user</code>, I should ignore the fact that <code>user_name</code>, <code>user_email</code> and <code>user_url</code> will be empty and just pull that information from a related profile model, correct?</p>
<p>While the answers could be quite trivial in the end, I'm just surprised that it hasn't been written or even talked about.</p>
| 6 | 2009-07-22T04:45:45Z | 2,268,367 | <p>WordPress and other systems make this a no-brainer. If you're logged in, the comment form should just "do the right thing" and remove the name/email/url fields. Isn't this exactly the kind of heavy lifting a framework is supposed to do for you? </p>
<p>Rather than dancing around with subclassing models for something that should be trivially easy, I find it simpler to build the form manually in the template and provide the hidden field values it needs. This works perfectly for sites that only accept comments from authenticated users:</p>
<pre><code>{% if user.is_authenticated %}
{% get_comment_form for [object] as form %}
<form action="{% comment_form_target %}" method="POST">
{% csrf_token %}
{{ form.comment }}
{{ form.honeypot }}
{{ form.content_type }}
{{ form.object_pk }}
{{ form.timestamp }}
{{ form.security_hash }}
<input type="hidden" name="next" value="{% url [the_view] [object].id %}" />
<input type="submit" value="Add comment" id="id_submit" />
</form>
{% else %}
<p>Please <a href="{% url auth_login %}">log in</a> to leave a comment.</p>
{% endif %}
</code></pre>
<p>Note that this will leave the honeypot field visible; you'll want to hide it in your CSS:</p>
<pre><code>#id_honeypot {
visibility:hidden;
}
</code></pre>
<p>If you want to enable comments either for anonymous or authenticated users, replace the auth_login line above with a standard call to a comment form.</p>
| 4 | 2010-02-15T19:24:38Z | [
"python",
"django",
"comments"
] |
How to detect the country and city of a user accessing your site? | 1,163,136 | <p>How can you detect the country of origin of the users accessing your site? </p>
<p>I'm using Google Analytics on my site and can see that I have users coming from different regions of the world.</p>
<p>But within my application I would like to provide some additional customization based on the country and perhaps the city.</p>
<p>Is it possible to detect this infomation from the browser? This is a Python web application.</p>
| 5 | 2009-07-22T05:01:11Z | 1,163,159 | <p>Get the visitor's IP and check it with a <a href="http://en.wikipedia.org/wiki/Geolocation" rel="nofollow">geolocation</a> web service (or purchase a geolocation database if you're keen to host that determination in-house).</p>
| 8 | 2009-07-22T05:07:50Z | [
"python",
"web-applications"
] |
How to detect the country and city of a user accessing your site? | 1,163,136 | <p>How can you detect the country of origin of the users accessing your site? </p>
<p>I'm using Google Analytics on my site and can see that I have users coming from different regions of the world.</p>
<p>But within my application I would like to provide some additional customization based on the country and perhaps the city.</p>
<p>Is it possible to detect this infomation from the browser? This is a Python web application.</p>
| 5 | 2009-07-22T05:01:11Z | 1,163,695 | <p>Grab and gunzip <a href="http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz">http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz</a>, install the GeoIP-Python package (python-geoip package if you're in Debian or Ubuntu, otherwise install <a href="http://geolite.maxmind.com/download/geoip/api/python/GeoIP-Python-1.2.4.tar.gz">http://geolite.maxmind.com/download/geoip/api/python/GeoIP-Python-1.2.4.tar.gz</a>), and do:</p>
<pre><code>import GeoIP
gi = GeoIP.open("GeoLiteCity.dat", GeoIP.GEOIP_INDEX_CACHE | GeoIP.GEOIP_CHECK_CACHE)
print gi.record_by_name("74.125.67.100") # a www.google.com IP
</code></pre>
<p><code>{'city': 'Mountain View', 'region_name': 'California', 'region': 'CA', 'area_code': 650, 'time_zone': 'America/Los_Angeles', 'longitude': -122.05740356445312, 'country_code3': 'USA', 'latitude': 37.419200897216797, 'postal_code': '94043', 'dma_code': 807, 'country_code': 'US', 'country_name': 'United States'}</code></p>
<p>The database is free (<a href="http://geolite.maxmind.com/download/geoip/database/LICENSE.txt">http://geolite.maxmind.com/download/geoip/database/LICENSE.txt</a>). They do sell it, too; I think that just gets you more frequent updates.</p>
| 12 | 2009-07-22T07:49:14Z | [
"python",
"web-applications"
] |
How to detect the country and city of a user accessing your site? | 1,163,136 | <p>How can you detect the country of origin of the users accessing your site? </p>
<p>I'm using Google Analytics on my site and can see that I have users coming from different regions of the world.</p>
<p>But within my application I would like to provide some additional customization based on the country and perhaps the city.</p>
<p>Is it possible to detect this infomation from the browser? This is a Python web application.</p>
| 5 | 2009-07-22T05:01:11Z | 40,068,720 | <p>Max mind costs money.
For a free yet country code only solution you can try:
<a href="https://pypi.python.org/pypi/geoip2nation/" rel="nofollow">https://pypi.python.org/pypi/geoip2nation/</a></p>
<p>pip install geoip2nation</p>
<pre><code>from geoip import geoip
r = geoip.GeoIp()
r.load_memory()
r.resolve("12.12.12.12").country_code
#This prints : 'US'
print r.resolve("123.44.57.4")
#This prints : {'country': 'Korea (South)', 'host_name': '', 'country_code': 'KR'}
r.resolve2("12.12.12.12")
#This prints : 'US'
</code></pre>
| 0 | 2016-10-16T09:15:35Z | [
"python",
"web-applications"
] |
Non-recursive means of printing a list in Python | 1,163,429 | <p>Is there a way to perform the following in a non-recursive fashion:</p>
<pre><code>my_list = [
"level 1-1",
"level 1-2",
"level 1-3",
[
"level 2-1",
"level 2-2",
"level 2-3",
[
"level 3-1",
"level 3-2"
]
],
"level 1-4",
"level 1-5"
]
def print_list(the_list, indent_level=0):
for item in the_list:
if isinstance(item, list):
print_list(item, indent_level + 1)
else:
print "\t" * indent_level, item
print_list(my_list)
</code></pre>
| 2 | 2009-07-22T06:42:56Z | 1,163,532 | <pre><code>def print_list(the_list, indent_level=0):
stack = [iter(the_list)]
while stack:
try:
item = stack[-1].next()
except StopIteration:
stack.pop()
indent_level -= 1
continue
if isinstance(item, list):
indent_level += 1
stack.append(iter(item))
else:
print "\t" * indent_level, item
</code></pre>
| 2 | 2009-07-22T07:05:19Z | [
"python",
"recursion"
] |
Non-recursive means of printing a list in Python | 1,163,429 | <p>Is there a way to perform the following in a non-recursive fashion:</p>
<pre><code>my_list = [
"level 1-1",
"level 1-2",
"level 1-3",
[
"level 2-1",
"level 2-2",
"level 2-3",
[
"level 3-1",
"level 3-2"
]
],
"level 1-4",
"level 1-5"
]
def print_list(the_list, indent_level=0):
for item in the_list:
if isinstance(item, list):
print_list(item, indent_level + 1)
else:
print "\t" * indent_level, item
print_list(my_list)
</code></pre>
| 2 | 2009-07-22T06:42:56Z | 1,163,533 | <p>Note that this depens on the input not containing tuples.</p>
<pre><code>l1 = my_list
done = False
# Repeatedly turn the list elements into tuples of the form
# (indent, item) until there are no more lists.
while not done:
done = True
l2 = []
for item in l1:
if isinstance(item,tuple):
indent = item[0]
item = item[1]
else:
indent = 0
if isinstance(item,list):
l2.extend( zip( (indent + 1,) * len(item), item) )
done = False
else:
l2.append((indent,item))
l1 = l2
for indent, item in l1:
print "\t" * indent, item
</code></pre>
| 0 | 2009-07-22T07:05:31Z | [
"python",
"recursion"
] |
Non-recursive means of printing a list in Python | 1,163,429 | <p>Is there a way to perform the following in a non-recursive fashion:</p>
<pre><code>my_list = [
"level 1-1",
"level 1-2",
"level 1-3",
[
"level 2-1",
"level 2-2",
"level 2-3",
[
"level 3-1",
"level 3-2"
]
],
"level 1-4",
"level 1-5"
]
def print_list(the_list, indent_level=0):
for item in the_list:
if isinstance(item, list):
print_list(item, indent_level + 1)
else:
print "\t" * indent_level, item
print_list(my_list)
</code></pre>
| 2 | 2009-07-22T06:42:56Z | 1,163,542 | <pre><code>stack = [(my_list, -1)]
while stack:
item, level = stack.pop()
if isinstance(item, list):
for i in reversed(item):
stack.append((i, level+1))
else:
print "\t" * level, item
</code></pre>
| 4 | 2009-07-22T07:07:21Z | [
"python",
"recursion"
] |
Non-recursive means of printing a list in Python | 1,163,429 | <p>Is there a way to perform the following in a non-recursive fashion:</p>
<pre><code>my_list = [
"level 1-1",
"level 1-2",
"level 1-3",
[
"level 2-1",
"level 2-2",
"level 2-3",
[
"level 3-1",
"level 3-2"
]
],
"level 1-4",
"level 1-5"
]
def print_list(the_list, indent_level=0):
for item in the_list:
if isinstance(item, list):
print_list(item, indent_level + 1)
else:
print "\t" * indent_level, item
print_list(my_list)
</code></pre>
| 2 | 2009-07-22T06:42:56Z | 1,164,531 | <p>Everyone has given solutions which are</p>
<ul>
<li>production ready</li>
<li>use stack, so has same problem as recursion</li>
<li>or go thru list multiple time</li>
</ul>
<p>Here is a solution lateral solution :)</p>
<ul>
<li>not production ready but fun</li>
<li>no stack or anything like that, no lists in sight</li>
</ul>
<p>--</p>
<pre><code>def my_print(the_list):
level = -1
out = []
levelUp="levelup"
levelDown="leveldown"
s = repr(the_list).replace("', '","\n").replace(
"', ['", "\n%s\n"%levelUp).replace("['", "\n%s\n"%levelUp).replace(
"']", "\n%s\n"%levelDown).replace("], '", "\n%s\n"%levelDown)
for line in s.splitlines():
if not line: continue
if line == levelUp:
level+=1
elif line == levelDown:
level-=1
else:
print "\t"*level,line
my_print(my_list)
</code></pre>
<p>It assumes the your list text will not have some special substrings.</p>
| 0 | 2009-07-22T11:02:32Z | [
"python",
"recursion"
] |
Non-recursive means of printing a list in Python | 1,163,429 | <p>Is there a way to perform the following in a non-recursive fashion:</p>
<pre><code>my_list = [
"level 1-1",
"level 1-2",
"level 1-3",
[
"level 2-1",
"level 2-2",
"level 2-3",
[
"level 3-1",
"level 3-2"
]
],
"level 1-4",
"level 1-5"
]
def print_list(the_list, indent_level=0):
for item in the_list:
if isinstance(item, list):
print_list(item, indent_level + 1)
else:
print "\t" * indent_level, item
print_list(my_list)
</code></pre>
| 2 | 2009-07-22T06:42:56Z | 1,164,783 | <p>Here's a variation of Martin Löwis' version that uses <code>for/else</code> instead of manually catching <code>StopIteration</code>, and <code>len(stack)</code> instead of keeping track of the indent level.</p>
<pre><code>def print_list(the_list):
stack = [iter(the_list)]
while stack:
for item in stack[-1]:
if isinstance(item, (list, tuple)):
stack.append(iter(item))
break
else:
print '\t' * (len(stack)-1), item
else:
stack.pop()
</code></pre>
| 2 | 2009-07-22T11:58:11Z | [
"python",
"recursion"
] |
Reading integers from binary file in Python | 1,163,459 | <p>I'm trying to read a <a href="http://en.wikipedia.org/wiki/BMP_file_format">BMP</a> file in Python. I know the first two bytes
indicate the BMP firm. The next 4 bytes are the file size. When I excecute:</p>
<pre><code>fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size = int(fin.read(4))
</code></pre>
<p>I get </p>
<blockquote>
<p>ValueError: invalid literal for int() with base 10: 'F#\x13'</p>
</blockquote>
<p>What I want to do is reading those four bytes as an integer... It seems Python is reading them as characters and returning a string, which cannot be converted to an integer. How can I do this correctly? </p>
| 40 | 2009-07-22T06:48:39Z | 1,163,508 | <p>The <code>read</code> method returns a sequence of bytes as a string. To convert from a string byte-sequence to binary data, use the built-in <code>struct</code> module: <a href="http://docs.python.org/library/struct.html">http://docs.python.org/library/struct.html</a>. </p>
<pre><code>import struct
print(struct.unpack('i', fin.read(4)))
</code></pre>
<p>Note that <code>unpack</code> always returns a tuple, so <code>struct.unpack('i', fin.read(4))[0]</code> gives the integer value that you are after.</p>
<p>You should probably use the format string <code>'<i'</code> (< is a modifier that indicates little-endian byte-order and standard size and alignment - the default is to use the platform's byte ordering, size and alignment). According to the BMP format spec, the bytes should be written in Intel/little-endian byte order.</p>
| 68 | 2009-07-22T06:59:55Z | [
"python",
"file",
"binary",
"integer"
] |
Reading integers from binary file in Python | 1,163,459 | <p>I'm trying to read a <a href="http://en.wikipedia.org/wiki/BMP_file_format">BMP</a> file in Python. I know the first two bytes
indicate the BMP firm. The next 4 bytes are the file size. When I excecute:</p>
<pre><code>fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size = int(fin.read(4))
</code></pre>
<p>I get </p>
<blockquote>
<p>ValueError: invalid literal for int() with base 10: 'F#\x13'</p>
</blockquote>
<p>What I want to do is reading those four bytes as an integer... It seems Python is reading them as characters and returning a string, which cannot be converted to an integer. How can I do this correctly? </p>
| 40 | 2009-07-22T06:48:39Z | 1,163,525 | <p>As you are reading the binary file, you need to unpack it into a integer, so use struct module for that</p>
<pre><code>import struct
fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size, = struct.unpack("i",fin.read(4))
</code></pre>
| 4 | 2009-07-22T07:03:57Z | [
"python",
"file",
"binary",
"integer"
] |
Reading integers from binary file in Python | 1,163,459 | <p>I'm trying to read a <a href="http://en.wikipedia.org/wiki/BMP_file_format">BMP</a> file in Python. I know the first two bytes
indicate the BMP firm. The next 4 bytes are the file size. When I excecute:</p>
<pre><code>fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size = int(fin.read(4))
</code></pre>
<p>I get </p>
<blockquote>
<p>ValueError: invalid literal for int() with base 10: 'F#\x13'</p>
</blockquote>
<p>What I want to do is reading those four bytes as an integer... It seems Python is reading them as characters and returning a string, which cannot be converted to an integer. How can I do this correctly? </p>
| 40 | 2009-07-22T06:48:39Z | 1,163,554 | <p>Except <code>struct</code> you can also use <code>array</code> module</p>
<pre><code>import array
values = array.array('l') # array of long integers
values.read(fin, 1) # read 1 integer
file_size = values[0]
</code></pre>
| 6 | 2009-07-22T07:10:16Z | [
"python",
"file",
"binary",
"integer"
] |
Reading integers from binary file in Python | 1,163,459 | <p>I'm trying to read a <a href="http://en.wikipedia.org/wiki/BMP_file_format">BMP</a> file in Python. I know the first two bytes
indicate the BMP firm. The next 4 bytes are the file size. When I excecute:</p>
<pre><code>fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size = int(fin.read(4))
</code></pre>
<p>I get </p>
<blockquote>
<p>ValueError: invalid literal for int() with base 10: 'F#\x13'</p>
</blockquote>
<p>What I want to do is reading those four bytes as an integer... It seems Python is reading them as characters and returning a string, which cannot be converted to an integer. How can I do this correctly? </p>
| 40 | 2009-07-22T06:48:39Z | 11,713,266 | <p>An alternative method which does not make use of 'struct.unpack()' would be to use <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a>:</p>
<pre><code>import numpy as np
f = open("file.bin", "r")
a = np.fromfile(f, dtype=np.uint32)
</code></pre>
<p>'dtype' represents the datatype and can be int#, uint#, float#, complex# or a user defined type. See <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html"><code>numpy.fromfile</code></a>.</p>
<p>Personally prefer using NumPy to work with array/matrix data as it is a lot faster than using Python lists.</p>
| 22 | 2012-07-29T21:51:48Z | [
"python",
"file",
"binary",
"integer"
] |
Python plugin in netbeans manually | 1,163,531 | <p>Can install python plugin in netbeans 6.7 manually (without Tools/Plugin) ?
if yes (with .nbi package ) which url can use ?</p>
| 1 | 2009-07-22T07:04:38Z | 1,776,811 | <p>find one Netbeans that downloaded python plug-in and go to Netbeans folder and copy python folder. In computer that need to install python plug-in copy that folder in Netbeans root folder and go to Tools/Plugin and activate python . </p>
| 0 | 2009-11-21T21:15:06Z | [
"python",
"netbeans",
"netbeans6.7",
"netbeans-plugins"
] |
fast-ish python/jython IPC? | 1,163,574 | <p>All I want to do is make some RPC calls over sockets. I have a server that does backendish stuff running jython 2.5. I need to make some calls from a frontend server running Django on CPython. I've been beating my head against a wall getting any form of IPC going.</p>
<p>The list of things I've tried:</p>
<ul>
<li><a href="http://incubator.apache.org/thrift/">Apache Thrift</a> doesn't have any actual releases, just snapshots. I'd like to use something stable.</li>
<li><a href="http://json-rpc.org/">JSON-RPC</a> is interesting, and it should be able to run over sockets, but in practice most of the <a href="http://json-rpc.org/wiki/implementations">implementations</a> only seem to work over HTTP. HTTP overhead is exactly what I'm trying to avoid.</li>
<li><a href="http://code.google.com/p/protobuf/">Protocol Buffers</a> is really only a serialization protocol. From what I gather protobuf provides interface generation for RPC, but it's only the interface. Actually writing all the connection code is up to the user. If I'm going to be stuck using sockets, I'll just use JSON for serialization. It's simpler and <a href="http://www.eishay.com/2009/03/thrift-vs-protocol-buffers-in-python.html">faster</a>.</li>
<li><a href="http://pyro.sourceforge.net/">Pyro</a> doesn't work properly with Jython as a server. Some sort of socket timeout issue. I've sent a message to the mailing list.</li>
<li><a href="http://code.google.com/p/pysage/">pysage</a> Yay for message passing! Only it requires python 2.6 or the processing module (which has compiled extensions). Jython is version 2.5 and doesn't allow compiled extensions. Shit.</li>
<li><a href="http://candygram.sourceforge.net/">Candygram</a> is an interesting alternative to pysage, but as far as I can tell it's unmaintained. I haven't even tried it out with Jython. Any experiences with it?</li>
<li><a href="http://twistedmatrix.com/projects/core/documentation/howto/pb-intro.html">Twisted Perspective Broker</a> Twisted doesn't work on Jython.</li>
</ul>
<p>I know that it'd be a snap doing this with XML-RPC, which makes me even more cranky. I want to avoid the overhead of HTTP, but at the same time I really don't want to get down and dirty with sockets to implement my own protocol. I'll do it wrong if I do.</p>
<p>Any ideas? I'm probably going to cry for about 20 minutes and then just use XML-RPC.</p>
| 14 | 2009-07-22T07:14:36Z | 1,163,737 | <p>Have you considered <a href="http://hessian.caucho.com/" rel="nofollow">Hessian</a>? From the blurb:</p>
<blockquote>
<p>The Hessian binary web service
protocol makes web services usable
without requiring a large framework,
and without learning yet another
alphabet soup of protocols. Because it
is a binary protocol, it is
well-suited to sending binary data
without any need to extend the
protocol with attachments.</p>
</blockquote>
<p>It has Python client and Java server (and more besides).</p>
<p><strong>Update:</strong> If you're dead against HTTP, why not just use <code>SocketServer</code> and <code>pickle</code>? Not much of a protocol needed, hard to get wrong. Send / receive pickled strings with length prefixes.</p>
| 6 | 2009-07-22T08:00:13Z | [
"python",
"ipc",
"jython",
"twisted",
"rpc"
] |
fast-ish python/jython IPC? | 1,163,574 | <p>All I want to do is make some RPC calls over sockets. I have a server that does backendish stuff running jython 2.5. I need to make some calls from a frontend server running Django on CPython. I've been beating my head against a wall getting any form of IPC going.</p>
<p>The list of things I've tried:</p>
<ul>
<li><a href="http://incubator.apache.org/thrift/">Apache Thrift</a> doesn't have any actual releases, just snapshots. I'd like to use something stable.</li>
<li><a href="http://json-rpc.org/">JSON-RPC</a> is interesting, and it should be able to run over sockets, but in practice most of the <a href="http://json-rpc.org/wiki/implementations">implementations</a> only seem to work over HTTP. HTTP overhead is exactly what I'm trying to avoid.</li>
<li><a href="http://code.google.com/p/protobuf/">Protocol Buffers</a> is really only a serialization protocol. From what I gather protobuf provides interface generation for RPC, but it's only the interface. Actually writing all the connection code is up to the user. If I'm going to be stuck using sockets, I'll just use JSON for serialization. It's simpler and <a href="http://www.eishay.com/2009/03/thrift-vs-protocol-buffers-in-python.html">faster</a>.</li>
<li><a href="http://pyro.sourceforge.net/">Pyro</a> doesn't work properly with Jython as a server. Some sort of socket timeout issue. I've sent a message to the mailing list.</li>
<li><a href="http://code.google.com/p/pysage/">pysage</a> Yay for message passing! Only it requires python 2.6 or the processing module (which has compiled extensions). Jython is version 2.5 and doesn't allow compiled extensions. Shit.</li>
<li><a href="http://candygram.sourceforge.net/">Candygram</a> is an interesting alternative to pysage, but as far as I can tell it's unmaintained. I haven't even tried it out with Jython. Any experiences with it?</li>
<li><a href="http://twistedmatrix.com/projects/core/documentation/howto/pb-intro.html">Twisted Perspective Broker</a> Twisted doesn't work on Jython.</li>
</ul>
<p>I know that it'd be a snap doing this with XML-RPC, which makes me even more cranky. I want to avoid the overhead of HTTP, but at the same time I really don't want to get down and dirty with sockets to implement my own protocol. I'll do it wrong if I do.</p>
<p>Any ideas? I'm probably going to cry for about 20 minutes and then just use XML-RPC.</p>
| 14 | 2009-07-22T07:14:36Z | 1,163,852 | <p>Have you thought about using CORBA? It's fast, portable and object oriented...</p>
<p>I have only used it on the Java side (I think you could use a pure java broker with no problems from Jython), and with IIOP you should be able to interoperate with the CPython client.</p>
| 0 | 2009-07-22T08:27:26Z | [
"python",
"ipc",
"jython",
"twisted",
"rpc"
] |
fast-ish python/jython IPC? | 1,163,574 | <p>All I want to do is make some RPC calls over sockets. I have a server that does backendish stuff running jython 2.5. I need to make some calls from a frontend server running Django on CPython. I've been beating my head against a wall getting any form of IPC going.</p>
<p>The list of things I've tried:</p>
<ul>
<li><a href="http://incubator.apache.org/thrift/">Apache Thrift</a> doesn't have any actual releases, just snapshots. I'd like to use something stable.</li>
<li><a href="http://json-rpc.org/">JSON-RPC</a> is interesting, and it should be able to run over sockets, but in practice most of the <a href="http://json-rpc.org/wiki/implementations">implementations</a> only seem to work over HTTP. HTTP overhead is exactly what I'm trying to avoid.</li>
<li><a href="http://code.google.com/p/protobuf/">Protocol Buffers</a> is really only a serialization protocol. From what I gather protobuf provides interface generation for RPC, but it's only the interface. Actually writing all the connection code is up to the user. If I'm going to be stuck using sockets, I'll just use JSON for serialization. It's simpler and <a href="http://www.eishay.com/2009/03/thrift-vs-protocol-buffers-in-python.html">faster</a>.</li>
<li><a href="http://pyro.sourceforge.net/">Pyro</a> doesn't work properly with Jython as a server. Some sort of socket timeout issue. I've sent a message to the mailing list.</li>
<li><a href="http://code.google.com/p/pysage/">pysage</a> Yay for message passing! Only it requires python 2.6 or the processing module (which has compiled extensions). Jython is version 2.5 and doesn't allow compiled extensions. Shit.</li>
<li><a href="http://candygram.sourceforge.net/">Candygram</a> is an interesting alternative to pysage, but as far as I can tell it's unmaintained. I haven't even tried it out with Jython. Any experiences with it?</li>
<li><a href="http://twistedmatrix.com/projects/core/documentation/howto/pb-intro.html">Twisted Perspective Broker</a> Twisted doesn't work on Jython.</li>
</ul>
<p>I know that it'd be a snap doing this with XML-RPC, which makes me even more cranky. I want to avoid the overhead of HTTP, but at the same time I really don't want to get down and dirty with sockets to implement my own protocol. I'll do it wrong if I do.</p>
<p>Any ideas? I'm probably going to cry for about 20 minutes and then just use XML-RPC.</p>
| 14 | 2009-07-22T07:14:36Z | 1,163,968 | <p>How about using sockets, but with the help of <code>asyncore</code> and <code>asynchat</code>?</p>
<p>Some links:</p>
<ul>
<li><a href="http://effbot.org/librarybook/asynchat.htm">An example</a></li>
<li><a href="http://docs.python.org/library/asyncore.html">http://docs.python.org/library/asyncore.html</a></li>
<li><a href="http://docs.python.org/library/asynchat.html">http://docs.python.org/library/asynchat.html</a></li>
</ul>
| 5 | 2009-07-22T08:56:45Z | [
"python",
"ipc",
"jython",
"twisted",
"rpc"
] |
fast-ish python/jython IPC? | 1,163,574 | <p>All I want to do is make some RPC calls over sockets. I have a server that does backendish stuff running jython 2.5. I need to make some calls from a frontend server running Django on CPython. I've been beating my head against a wall getting any form of IPC going.</p>
<p>The list of things I've tried:</p>
<ul>
<li><a href="http://incubator.apache.org/thrift/">Apache Thrift</a> doesn't have any actual releases, just snapshots. I'd like to use something stable.</li>
<li><a href="http://json-rpc.org/">JSON-RPC</a> is interesting, and it should be able to run over sockets, but in practice most of the <a href="http://json-rpc.org/wiki/implementations">implementations</a> only seem to work over HTTP. HTTP overhead is exactly what I'm trying to avoid.</li>
<li><a href="http://code.google.com/p/protobuf/">Protocol Buffers</a> is really only a serialization protocol. From what I gather protobuf provides interface generation for RPC, but it's only the interface. Actually writing all the connection code is up to the user. If I'm going to be stuck using sockets, I'll just use JSON for serialization. It's simpler and <a href="http://www.eishay.com/2009/03/thrift-vs-protocol-buffers-in-python.html">faster</a>.</li>
<li><a href="http://pyro.sourceforge.net/">Pyro</a> doesn't work properly with Jython as a server. Some sort of socket timeout issue. I've sent a message to the mailing list.</li>
<li><a href="http://code.google.com/p/pysage/">pysage</a> Yay for message passing! Only it requires python 2.6 or the processing module (which has compiled extensions). Jython is version 2.5 and doesn't allow compiled extensions. Shit.</li>
<li><a href="http://candygram.sourceforge.net/">Candygram</a> is an interesting alternative to pysage, but as far as I can tell it's unmaintained. I haven't even tried it out with Jython. Any experiences with it?</li>
<li><a href="http://twistedmatrix.com/projects/core/documentation/howto/pb-intro.html">Twisted Perspective Broker</a> Twisted doesn't work on Jython.</li>
</ul>
<p>I know that it'd be a snap doing this with XML-RPC, which makes me even more cranky. I want to avoid the overhead of HTTP, but at the same time I really don't want to get down and dirty with sockets to implement my own protocol. I'll do it wrong if I do.</p>
<p>Any ideas? I'm probably going to cry for about 20 minutes and then just use XML-RPC.</p>
| 14 | 2009-07-22T07:14:36Z | 1,164,219 | <p>Two that look the most interesting to me:</p>
<ul>
<li><p><a href="http://gearman.org/" rel="nofollow">Gearman</a> and <a href="http://github.com/samuel/python-gearman/tree/master" rel="nofollow">Python bindings</a>. It's quite a bit faster now that it's been re-written in C (originally perl). It's used in production (although I can't point to any examples of the python bindings being used in production). It has very interesting (to me) interfaces into MySQL and Postgresql. Finally, <a href="http://twitter.com/jacobian/status/2761378698" rel="nofollow">todays tweet</a> from Django's Jacob Kaplan-Moss.</p></li>
<li><p><a href="http://www.rabbitmq.com/" rel="nofollow">RabbitMQ</a> although because it's just a message queue you'll still have to serialize your own messages unless you also use <a href="http://pypi.python.org/pypi/celery/" rel="nofollow">celery</a>.</p></li>
</ul>
| 2 | 2009-07-22T09:57:04Z | [
"python",
"ipc",
"jython",
"twisted",
"rpc"
] |
fast-ish python/jython IPC? | 1,163,574 | <p>All I want to do is make some RPC calls over sockets. I have a server that does backendish stuff running jython 2.5. I need to make some calls from a frontend server running Django on CPython. I've been beating my head against a wall getting any form of IPC going.</p>
<p>The list of things I've tried:</p>
<ul>
<li><a href="http://incubator.apache.org/thrift/">Apache Thrift</a> doesn't have any actual releases, just snapshots. I'd like to use something stable.</li>
<li><a href="http://json-rpc.org/">JSON-RPC</a> is interesting, and it should be able to run over sockets, but in practice most of the <a href="http://json-rpc.org/wiki/implementations">implementations</a> only seem to work over HTTP. HTTP overhead is exactly what I'm trying to avoid.</li>
<li><a href="http://code.google.com/p/protobuf/">Protocol Buffers</a> is really only a serialization protocol. From what I gather protobuf provides interface generation for RPC, but it's only the interface. Actually writing all the connection code is up to the user. If I'm going to be stuck using sockets, I'll just use JSON for serialization. It's simpler and <a href="http://www.eishay.com/2009/03/thrift-vs-protocol-buffers-in-python.html">faster</a>.</li>
<li><a href="http://pyro.sourceforge.net/">Pyro</a> doesn't work properly with Jython as a server. Some sort of socket timeout issue. I've sent a message to the mailing list.</li>
<li><a href="http://code.google.com/p/pysage/">pysage</a> Yay for message passing! Only it requires python 2.6 or the processing module (which has compiled extensions). Jython is version 2.5 and doesn't allow compiled extensions. Shit.</li>
<li><a href="http://candygram.sourceforge.net/">Candygram</a> is an interesting alternative to pysage, but as far as I can tell it's unmaintained. I haven't even tried it out with Jython. Any experiences with it?</li>
<li><a href="http://twistedmatrix.com/projects/core/documentation/howto/pb-intro.html">Twisted Perspective Broker</a> Twisted doesn't work on Jython.</li>
</ul>
<p>I know that it'd be a snap doing this with XML-RPC, which makes me even more cranky. I want to avoid the overhead of HTTP, but at the same time I really don't want to get down and dirty with sockets to implement my own protocol. I'll do it wrong if I do.</p>
<p>Any ideas? I'm probably going to cry for about 20 minutes and then just use XML-RPC.</p>
| 14 | 2009-07-22T07:14:36Z | 1,165,579 | <p>My favorite..
<a href="http://www.zeroc.com" rel="nofollow">zeroc's ice</a></p>
| 2 | 2009-07-22T14:14:53Z | [
"python",
"ipc",
"jython",
"twisted",
"rpc"
] |
python mysql connection problem | 1,164,033 | <p>This code works fine:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect("localhost", "root", "","bullsorbit")
cursor = db.cursor()
cursor.execute("Select * from table where conditions'")
numrows = int(cursor.rowcount)
print 'Total number of Pages : %d ' % numrows
</code></pre>
<p>but if I give my IP address </p>
<pre><code>db = MySQLdb.connect("192.168.*.*", "root", "","bullsorbit")
</code></pre>
<p>it will give this error</p>
<pre><code>super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'ip address' (111)")
</code></pre>
| 1 | 2009-07-22T09:12:14Z | 1,164,071 | <p>with localhost you connect via loopback-interface.</p>
<p>with ip-addr you connect - as you connect from extern.</p>
<p>if your server allows only the local (loopback) connection
your ip-addr connection fails. (security!)</p>
<p>look at your mysql config, maybe only local-connections are allowed.</p>
<p>is the skip-networking switch off (in the mysql-conf) ?</p>
<pre><code>#skip-networking
</code></pre>
| 3 | 2009-07-22T09:18:48Z | [
"python",
"mysql"
] |
python mysql connection problem | 1,164,033 | <p>This code works fine:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect("localhost", "root", "","bullsorbit")
cursor = db.cursor()
cursor.execute("Select * from table where conditions'")
numrows = int(cursor.rowcount)
print 'Total number of Pages : %d ' % numrows
</code></pre>
<p>but if I give my IP address </p>
<pre><code>db = MySQLdb.connect("192.168.*.*", "root", "","bullsorbit")
</code></pre>
<p>it will give this error</p>
<pre><code>super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'ip address' (111)")
</code></pre>
| 1 | 2009-07-22T09:12:14Z | 1,164,077 | <p>Instead of:</p>
<p><code>db = MySQLdb.connect("192.168..", "root", "","bullsorbit")</code></p>
<p>try:</p>
<p><code>db = MySQLdb.connect(user="root", host="192.168..", db="bullsorbit")</code></p>
<p>Password will default to empty string and try the usual identity methods. Host will also default to localhost on default port.</p>
| 0 | 2009-07-22T09:19:52Z | [
"python",
"mysql"
] |
python mysql connection problem | 1,164,033 | <p>This code works fine:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect("localhost", "root", "","bullsorbit")
cursor = db.cursor()
cursor.execute("Select * from table where conditions'")
numrows = int(cursor.rowcount)
print 'Total number of Pages : %d ' % numrows
</code></pre>
<p>but if I give my IP address </p>
<pre><code>db = MySQLdb.connect("192.168.*.*", "root", "","bullsorbit")
</code></pre>
<p>it will give this error</p>
<pre><code>super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'ip address' (111)")
</code></pre>
| 1 | 2009-07-22T09:12:14Z | 1,164,297 | <p>Code 2003 is a <a href="http://dev.mysql.com/doc/refman/5.1/en/error-messages-client.html">standard MySQL client error</a>:</p>
<blockquote>
<p>Error: 2003 (CR_CONN_HOST_ERROR) Message: Can't connect to MySQL server on '%s' (%d)</p>
</blockquote>
<p>I'd guess that your user is not allowed to connect to the MySQL server using an iP-address. What happens if you try a connection usign the MySQL commandline client?</p>
<blockquote>
<p>$ mysql --host=192.168.1.1 -u root bullsorbit</p>
</blockquote>
| 5 | 2009-07-22T10:17:09Z | [
"python",
"mysql"
] |
python mysql connection problem | 1,164,033 | <p>This code works fine:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect("localhost", "root", "","bullsorbit")
cursor = db.cursor()
cursor.execute("Select * from table where conditions'")
numrows = int(cursor.rowcount)
print 'Total number of Pages : %d ' % numrows
</code></pre>
<p>but if I give my IP address </p>
<pre><code>db = MySQLdb.connect("192.168.*.*", "root", "","bullsorbit")
</code></pre>
<p>it will give this error</p>
<pre><code>super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'ip address' (111)")
</code></pre>
| 1 | 2009-07-22T09:12:14Z | 14,125,203 | <p>For the <code>2003</code> error, another possibility is that too many connections are being attempted in too short of time. I noticed this same behavior when I had <code>127.0.0.1</code> as my connect string. First I replaced it with <code>localhost</code> which got me further but still the same <code>2003</code> error. Then I saw that if I scaled back the number of calls the error disappeared completely.</p>
| 0 | 2013-01-02T16:06:39Z | [
"python",
"mysql"
] |
Python object creation | 1,164,309 | <p>I am pretty new to Python world and trying to learn it.</p>
<p>This is what I am trying to achieve: I want to create a Car class, its constructor checks for the input to set the object carName as the input. I try to do this by using the java logic but I seem to fail :)</p>
<pre><code>class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
self.carName = input
def showName():
print carName
a = Car("bmw")
a.showName()
</code></pre>
| 5 | 2009-07-22T10:19:34Z | 1,164,319 | <p>derived from object for <a href="http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes">new-style class</a><br />
use <code>__init__</code> to initialize the new instance, not <code>__self__</code><br />
<code>__main__</code> is <a href="http://docs.python.org/library/%5F%5Fmain%5F%5F.html">helpful too</a>.</p>
<pre><code>class Car(object):
def __init__(self,input):
self.carName = input
def showName(self):
print self.carName
def main():
a = Car("bmw")
a.showName()
if __name__ == "__main__":
main()
</code></pre>
| 13 | 2009-07-22T10:21:37Z | [
"python",
"class",
"object"
] |
Python object creation | 1,164,309 | <p>I am pretty new to Python world and trying to learn it.</p>
<p>This is what I am trying to achieve: I want to create a Car class, its constructor checks for the input to set the object carName as the input. I try to do this by using the java logic but I seem to fail :)</p>
<pre><code>class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
self.carName = input
def showName():
print carName
a = Car("bmw")
a.showName()
</code></pre>
| 5 | 2009-07-22T10:19:34Z | 1,164,328 | <p>You don't define a variable, and you use <strong>init</strong> and self.
Like this:</p>
<pre><code>class Car(Object):
def __init__(self,input):
self.carName = input
def showName(self):
print self.carName
a = Car("bmw")
a.showName()
</code></pre>
| 1 | 2009-07-22T10:22:38Z | [
"python",
"class",
"object"
] |
Python object creation | 1,164,309 | <p>I am pretty new to Python world and trying to learn it.</p>
<p>This is what I am trying to achieve: I want to create a Car class, its constructor checks for the input to set the object carName as the input. I try to do this by using the java logic but I seem to fail :)</p>
<pre><code>class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
self.carName = input
def showName():
print carName
a = Car("bmw")
a.showName()
</code></pre>
| 5 | 2009-07-22T10:19:34Z | 1,164,409 | <p>this is not correct!</p>
<pre><code>class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
self.carName = input
</code></pre>
<p>the first carName is a <strong>class Variable</strong> like static member in c++</p>
<p>the second carName (self.carName) is an <strong>instance variable</strong>,
if you want to set the <strong>class variable</strong> with the constructor you have to do it like this:</p>
<pre><code>class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
Car.carName = input
</code></pre>
| 1 | 2009-07-22T10:40:00Z | [
"python",
"class",
"object"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I have my model setup nicely and plugged into the admin, and the image uploads fine to the directory:</p>
<pre><code>from django.db import models
# This is to list all the countries
# For starters though, this will be just United Kingdom (GB)
class Country(models.Model):
name = models.CharField(max_length=120, help_text="Full name of country")
code = models.CharField(max_length=2, help_text="This is the ISO 3166 2-letter country code (see: http://www.theodora.com/country_digraphs.html)")
flag = models.ImageField(upload_to="images/uploaded/country/", max_length=150, help_text="The flag image of the country.", blank=True)
class Meta:
verbose_name_plural = "Countries"
def __unicode__(self):
return self.name
</code></pre>
<p>The thing I'm now having trouble with is taking that file and making a new file into a thumbnail. Like I say, I'd like to know how to do it without using others' apps (for now). I have got this code from DjangoSnippets:</p>
<pre><code>from PIL import Image
import os.path
import StringIO
def thumbnail(filename, size=(50, 50), output_filename=None):
image = Image.open(filename)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
# get the thumbnail data in memory.
if not output_filename:
output_filename = get_default_thumbnail_filename(filename)
image.save(output_filename, image.format)
return output_filename
def thumbnail_string(buf, size=(50, 50)):
f = StringIO.StringIO(buf)
image = Image.open(f)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
o = StringIO.StringIO()
image.save(o, "JPEG")
return o.getvalue()
def get_default_thumbnail_filename(filename):
path, ext = os.path.splitext(filename)
return path + '.thumb.jpg'
</code></pre>
<p>...but this has ultimately confused me... As I don't know how this 'fits in' to my Django app? And really, is it the best solution for simply making a thumbnail of an image that has been successfully uploaded? Can anyone possibly show me a good, solid, decent way that a beginner like me can learn to do this properly? As in, knowing where to put that sort of code (models.py? forms.py? ...) and how it would work in context? ... I just need a bit of help understanding and working this problem out.</p>
<p>Thank you!</p>
| 11 | 2009-07-22T12:32:54Z | 1,164,988 | <p>If it's OK for you, there is a Django application ready, doing exactly what you want:
<a href="https://github.com/sorl/sorl-thumbnail" rel="nofollow">https://github.com/sorl/sorl-thumbnail</a></p>
| 7 | 2009-07-22T12:43:47Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I have my model setup nicely and plugged into the admin, and the image uploads fine to the directory:</p>
<pre><code>from django.db import models
# This is to list all the countries
# For starters though, this will be just United Kingdom (GB)
class Country(models.Model):
name = models.CharField(max_length=120, help_text="Full name of country")
code = models.CharField(max_length=2, help_text="This is the ISO 3166 2-letter country code (see: http://www.theodora.com/country_digraphs.html)")
flag = models.ImageField(upload_to="images/uploaded/country/", max_length=150, help_text="The flag image of the country.", blank=True)
class Meta:
verbose_name_plural = "Countries"
def __unicode__(self):
return self.name
</code></pre>
<p>The thing I'm now having trouble with is taking that file and making a new file into a thumbnail. Like I say, I'd like to know how to do it without using others' apps (for now). I have got this code from DjangoSnippets:</p>
<pre><code>from PIL import Image
import os.path
import StringIO
def thumbnail(filename, size=(50, 50), output_filename=None):
image = Image.open(filename)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
# get the thumbnail data in memory.
if not output_filename:
output_filename = get_default_thumbnail_filename(filename)
image.save(output_filename, image.format)
return output_filename
def thumbnail_string(buf, size=(50, 50)):
f = StringIO.StringIO(buf)
image = Image.open(f)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
o = StringIO.StringIO()
image.save(o, "JPEG")
return o.getvalue()
def get_default_thumbnail_filename(filename):
path, ext = os.path.splitext(filename)
return path + '.thumb.jpg'
</code></pre>
<p>...but this has ultimately confused me... As I don't know how this 'fits in' to my Django app? And really, is it the best solution for simply making a thumbnail of an image that has been successfully uploaded? Can anyone possibly show me a good, solid, decent way that a beginner like me can learn to do this properly? As in, knowing where to put that sort of code (models.py? forms.py? ...) and how it would work in context? ... I just need a bit of help understanding and working this problem out.</p>
<p>Thank you!</p>
| 11 | 2009-07-22T12:32:54Z | 1,164,993 | <p>Not sure about the code you sent, because I never use Models as such, but there is another method.</p>
<p>You can implement your own <code>FileUploadHandler</code> for handling image file uploads. Example is
<a href="http://www.djangosnippets.org/snippets/1036/" rel="nofollow">here</a>.
Just after line 37 (<code>dest.close()</code>) use <code>thumbnail(upload_dir + upload.name)</code> function (the one you sent).</p>
<p>Hope it helps you.</p>
| 2 | 2009-07-22T12:44:10Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I have my model setup nicely and plugged into the admin, and the image uploads fine to the directory:</p>
<pre><code>from django.db import models
# This is to list all the countries
# For starters though, this will be just United Kingdom (GB)
class Country(models.Model):
name = models.CharField(max_length=120, help_text="Full name of country")
code = models.CharField(max_length=2, help_text="This is the ISO 3166 2-letter country code (see: http://www.theodora.com/country_digraphs.html)")
flag = models.ImageField(upload_to="images/uploaded/country/", max_length=150, help_text="The flag image of the country.", blank=True)
class Meta:
verbose_name_plural = "Countries"
def __unicode__(self):
return self.name
</code></pre>
<p>The thing I'm now having trouble with is taking that file and making a new file into a thumbnail. Like I say, I'd like to know how to do it without using others' apps (for now). I have got this code from DjangoSnippets:</p>
<pre><code>from PIL import Image
import os.path
import StringIO
def thumbnail(filename, size=(50, 50), output_filename=None):
image = Image.open(filename)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
# get the thumbnail data in memory.
if not output_filename:
output_filename = get_default_thumbnail_filename(filename)
image.save(output_filename, image.format)
return output_filename
def thumbnail_string(buf, size=(50, 50)):
f = StringIO.StringIO(buf)
image = Image.open(f)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
o = StringIO.StringIO()
image.save(o, "JPEG")
return o.getvalue()
def get_default_thumbnail_filename(filename):
path, ext = os.path.splitext(filename)
return path + '.thumb.jpg'
</code></pre>
<p>...but this has ultimately confused me... As I don't know how this 'fits in' to my Django app? And really, is it the best solution for simply making a thumbnail of an image that has been successfully uploaded? Can anyone possibly show me a good, solid, decent way that a beginner like me can learn to do this properly? As in, knowing where to put that sort of code (models.py? forms.py? ...) and how it would work in context? ... I just need a bit of help understanding and working this problem out.</p>
<p>Thank you!</p>
| 11 | 2009-07-22T12:32:54Z | 1,165,042 | <p>A key question is: <strong>when</strong> should the thumbnail be generated?</p>
<ol>
<li>Dynamically when the user requests a thumbnail image?</li>
<li>Or do you want to create a physical disk file whenever a country is INSERTed/UPDATEd in the database.</li>
</ol>
<p>If (1) I suggest you create a view that maps to url <code>/flagthumbnail/countryid</code>. The view method would then have to:</p>
<ol>
<li>Get the country instance from the database</li>
<li>Read the flag image into a PIL Image and resize that.</li>
<li>Create (and return) a HTTPResponse with correct content-type and write the PIL Image to the response.</li>
</ol>
<p>Whenever you need to display a thumbnail flag, just use <code><a href="/flagthumbnail/countryid"></code>.</p>
<p>If (2), you could connect to Django's <code>django.db.models.signals.post_save</code> signal and in the signal handler create and save a thumbnail file.</p>
| 2 | 2009-07-22T12:51:25Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I have my model setup nicely and plugged into the admin, and the image uploads fine to the directory:</p>
<pre><code>from django.db import models
# This is to list all the countries
# For starters though, this will be just United Kingdom (GB)
class Country(models.Model):
name = models.CharField(max_length=120, help_text="Full name of country")
code = models.CharField(max_length=2, help_text="This is the ISO 3166 2-letter country code (see: http://www.theodora.com/country_digraphs.html)")
flag = models.ImageField(upload_to="images/uploaded/country/", max_length=150, help_text="The flag image of the country.", blank=True)
class Meta:
verbose_name_plural = "Countries"
def __unicode__(self):
return self.name
</code></pre>
<p>The thing I'm now having trouble with is taking that file and making a new file into a thumbnail. Like I say, I'd like to know how to do it without using others' apps (for now). I have got this code from DjangoSnippets:</p>
<pre><code>from PIL import Image
import os.path
import StringIO
def thumbnail(filename, size=(50, 50), output_filename=None):
image = Image.open(filename)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
# get the thumbnail data in memory.
if not output_filename:
output_filename = get_default_thumbnail_filename(filename)
image.save(output_filename, image.format)
return output_filename
def thumbnail_string(buf, size=(50, 50)):
f = StringIO.StringIO(buf)
image = Image.open(f)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
o = StringIO.StringIO()
image.save(o, "JPEG")
return o.getvalue()
def get_default_thumbnail_filename(filename):
path, ext = os.path.splitext(filename)
return path + '.thumb.jpg'
</code></pre>
<p>...but this has ultimately confused me... As I don't know how this 'fits in' to my Django app? And really, is it the best solution for simply making a thumbnail of an image that has been successfully uploaded? Can anyone possibly show me a good, solid, decent way that a beginner like me can learn to do this properly? As in, knowing where to put that sort of code (models.py? forms.py? ...) and how it would work in context? ... I just need a bit of help understanding and working this problem out.</p>
<p>Thank you!</p>
| 11 | 2009-07-22T12:32:54Z | 1,165,097 | <p>I guess it depends on how and when your using your thumbnails.</p>
<p>If you want to create some thumbnails every time the Country is saved, you could do it like so:</p>
<pre><code>from django.db import models
# This is to list all the countries
# For starters though, this will be just United Kingdom (GB)
class Country(models.Model):
name = models.CharField(max_length=120, help_text="Full name of country")
code = models.CharField(max_length=2, help_text="This is the ISO 3166 2-letter country code (see: http://www.theodora.com/country_digraphs.html)")
flag = models.ImageField(upload_to="images/uploaded/country/", max_length=150, help_text="The flag image of the country.", blank=True)
class Meta:
verbose_name_plural = "Countries"
def __unicode__(self):
return self.name
def save(self, force_insert=False, force_update=False):
resize_image(self.flag)
super(Country, self).save(force_insert, force_update)
</code></pre>
<p>If you aren't 100% sure what sizes you'll need your images, you could resize them last minute. I've seen this effectively done with a templatetag (I believe in a version on Pinax). You create a templatetag that takes the image and a size, then create and save the image of the appropriate size if you need to, or display a previously created one if it's there. It works pretty well.</p>
| 2 | 2009-07-22T13:00:26Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I have my model setup nicely and plugged into the admin, and the image uploads fine to the directory:</p>
<pre><code>from django.db import models
# This is to list all the countries
# For starters though, this will be just United Kingdom (GB)
class Country(models.Model):
name = models.CharField(max_length=120, help_text="Full name of country")
code = models.CharField(max_length=2, help_text="This is the ISO 3166 2-letter country code (see: http://www.theodora.com/country_digraphs.html)")
flag = models.ImageField(upload_to="images/uploaded/country/", max_length=150, help_text="The flag image of the country.", blank=True)
class Meta:
verbose_name_plural = "Countries"
def __unicode__(self):
return self.name
</code></pre>
<p>The thing I'm now having trouble with is taking that file and making a new file into a thumbnail. Like I say, I'd like to know how to do it without using others' apps (for now). I have got this code from DjangoSnippets:</p>
<pre><code>from PIL import Image
import os.path
import StringIO
def thumbnail(filename, size=(50, 50), output_filename=None):
image = Image.open(filename)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
# get the thumbnail data in memory.
if not output_filename:
output_filename = get_default_thumbnail_filename(filename)
image.save(output_filename, image.format)
return output_filename
def thumbnail_string(buf, size=(50, 50)):
f = StringIO.StringIO(buf)
image = Image.open(f)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
o = StringIO.StringIO()
image.save(o, "JPEG")
return o.getvalue()
def get_default_thumbnail_filename(filename):
path, ext = os.path.splitext(filename)
return path + '.thumb.jpg'
</code></pre>
<p>...but this has ultimately confused me... As I don't know how this 'fits in' to my Django app? And really, is it the best solution for simply making a thumbnail of an image that has been successfully uploaded? Can anyone possibly show me a good, solid, decent way that a beginner like me can learn to do this properly? As in, knowing where to put that sort of code (models.py? forms.py? ...) and how it would work in context? ... I just need a bit of help understanding and working this problem out.</p>
<p>Thank you!</p>
| 11 | 2009-07-22T12:32:54Z | 1,165,324 | <p>This is what I use in my models to save a new thumbnail if the uploaded image has changed. It's based of another DjangoSnippet but it I can't remember who wrote the orginal - if you know please add a comment so that I can credit them.</p>
<pre><code>from PIL import Image
from django.db import models
from django.contrib.auth.models import User
import os
import settings
class Photo_Ex(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
photo = models.ImageField(upload_to='photos')
thumbnail = models.ImageField(upload_to='profile_thumb', blank=True,
null=True, editable=False)
def save(self, *args, **kwargs):
size = (256,256)
if not self.id and not self.photo:
return
try:
old_obj = Photo_Ex.objects.get(pk=self.pk)
old_path = old_obj.photo.path
except:
pass
thumb_update = False
if self.thumbnail:
try:
statinfo1 = os.stat(self.photo.path)
statinfo2 = os.stat(self.thumbnail.path)
if statinfo1 > statinfo2:
thumb_update = True
except:
thumb_update = True
pw = self.photo.width
ph = self.photo.height
nw = size[0]
nh = size[1]
if self.photo and not self.thumbnail or thumb_update:
# only do this if the image needs resizing
if (pw, ph) != (nw, nh):
filename = str(self.photo.path)
image = Image.open(filename)
pr = float(pw) / float(ph)
nr = float(nw) / float(nh)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
if pr > nr:
# photo aspect is wider than destination ratio
tw = int(round(nh * pr))
image = image.resize((tw, nh), Image.ANTIALIAS)
l = int(round(( tw - nw ) / 2.0))
image = image.crop((l, 0, l + nw, nh))
elif pr < nr:
# photo aspect is taller than destination ratio
th = int(round(nw / pr))
image = image.resize((nw, th), Image.ANTIALIAS)
t = int(round(( th - nh ) / 2.0))
image = image.crop((0, t, nw, t + nh))
else:
# photo aspect matches the destination ratio
image = image.resize(size, Image.ANTIALIAS)
image.save(self.get_thumbnail_path())
(a, b) = os.path.split(self.photo.name)
self.thumbnail = a + '/thumbs/' + b
super(Photo_Ex, self).save()
try:
os.remove(old_path)
os.remove(self.get_old_thumbnail_path(old_path))
except:
pass
def get_thumbnail_path(self):
(head, tail) = os.path.split(self.photo.path)
if not os.path.isdir(head + '/thumbs'):
os.mkdir(head + '/thumbs')
return head + '/thumbs/' + tail
def get_old_thumbnail_path(self, old_photo_path):
(head, tail) = os.path.split(old_photo_path)
return head + '/thumbs/' + tail
</code></pre>
| 4 | 2009-07-22T13:39:22Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I have my model setup nicely and plugged into the admin, and the image uploads fine to the directory:</p>
<pre><code>from django.db import models
# This is to list all the countries
# For starters though, this will be just United Kingdom (GB)
class Country(models.Model):
name = models.CharField(max_length=120, help_text="Full name of country")
code = models.CharField(max_length=2, help_text="This is the ISO 3166 2-letter country code (see: http://www.theodora.com/country_digraphs.html)")
flag = models.ImageField(upload_to="images/uploaded/country/", max_length=150, help_text="The flag image of the country.", blank=True)
class Meta:
verbose_name_plural = "Countries"
def __unicode__(self):
return self.name
</code></pre>
<p>The thing I'm now having trouble with is taking that file and making a new file into a thumbnail. Like I say, I'd like to know how to do it without using others' apps (for now). I have got this code from DjangoSnippets:</p>
<pre><code>from PIL import Image
import os.path
import StringIO
def thumbnail(filename, size=(50, 50), output_filename=None):
image = Image.open(filename)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
# get the thumbnail data in memory.
if not output_filename:
output_filename = get_default_thumbnail_filename(filename)
image.save(output_filename, image.format)
return output_filename
def thumbnail_string(buf, size=(50, 50)):
f = StringIO.StringIO(buf)
image = Image.open(f)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
o = StringIO.StringIO()
image.save(o, "JPEG")
return o.getvalue()
def get_default_thumbnail_filename(filename):
path, ext = os.path.splitext(filename)
return path + '.thumb.jpg'
</code></pre>
<p>...but this has ultimately confused me... As I don't know how this 'fits in' to my Django app? And really, is it the best solution for simply making a thumbnail of an image that has been successfully uploaded? Can anyone possibly show me a good, solid, decent way that a beginner like me can learn to do this properly? As in, knowing where to put that sort of code (models.py? forms.py? ...) and how it would work in context? ... I just need a bit of help understanding and working this problem out.</p>
<p>Thank you!</p>
| 11 | 2009-07-22T12:32:54Z | 1,165,504 | <p>Overriding the save method is a good option, but I'd be more tempted to use a <a href="http://docs.djangoproject.com/en/dev/topics/signals/" rel="nofollow">signal</a> in this case. Django signals allow you to "listen" to a given model type's various events; in this case, you'd be interested in the <code>post_save</code> event.</p>
<p>I usually subscribe to such signals in my <code>models.py</code> file. Code for you would look something like this:</p>
<pre><code>from django.db.models.signals import post_save
from models import Country
def resize_image(sender, **kwargs):
country = kwargs["instance"]
resize_image(country.flag) # where resize_image generates a thumbnail given a Country instance
post_save.connect(resize_image, sender=Country)
</code></pre>
| 2 | 2009-07-22T14:03:32Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I have my model setup nicely and plugged into the admin, and the image uploads fine to the directory:</p>
<pre><code>from django.db import models
# This is to list all the countries
# For starters though, this will be just United Kingdom (GB)
class Country(models.Model):
name = models.CharField(max_length=120, help_text="Full name of country")
code = models.CharField(max_length=2, help_text="This is the ISO 3166 2-letter country code (see: http://www.theodora.com/country_digraphs.html)")
flag = models.ImageField(upload_to="images/uploaded/country/", max_length=150, help_text="The flag image of the country.", blank=True)
class Meta:
verbose_name_plural = "Countries"
def __unicode__(self):
return self.name
</code></pre>
<p>The thing I'm now having trouble with is taking that file and making a new file into a thumbnail. Like I say, I'd like to know how to do it without using others' apps (for now). I have got this code from DjangoSnippets:</p>
<pre><code>from PIL import Image
import os.path
import StringIO
def thumbnail(filename, size=(50, 50), output_filename=None):
image = Image.open(filename)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
# get the thumbnail data in memory.
if not output_filename:
output_filename = get_default_thumbnail_filename(filename)
image.save(output_filename, image.format)
return output_filename
def thumbnail_string(buf, size=(50, 50)):
f = StringIO.StringIO(buf)
image = Image.open(f)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
o = StringIO.StringIO()
image.save(o, "JPEG")
return o.getvalue()
def get_default_thumbnail_filename(filename):
path, ext = os.path.splitext(filename)
return path + '.thumb.jpg'
</code></pre>
<p>...but this has ultimately confused me... As I don't know how this 'fits in' to my Django app? And really, is it the best solution for simply making a thumbnail of an image that has been successfully uploaded? Can anyone possibly show me a good, solid, decent way that a beginner like me can learn to do this properly? As in, knowing where to put that sort of code (models.py? forms.py? ...) and how it would work in context? ... I just need a bit of help understanding and working this problem out.</p>
<p>Thank you!</p>
| 11 | 2009-07-22T12:32:54Z | 1,165,940 | <p>Ryan is correct signals are a better way to go however the advantage of the overriden save is that we can get the old and new image paths, see if the image has changed (and if it has create a new thumbnail), save the model instance and then delete the old image and thumbnail.</p>
<p><em>Remember django does not clean up the old images for you so unless you have script to check that the images/thumbnails are still in use and clean out any that are not you will leak disk space. (This may or may-not be a problem for you depending on image size and frequency of updates)</em></p>
<p>I'm not sure how you could do this with a post_save signal, and I don't know enough about signals (That's research for tonight!) to know if there is a suitable pre_save signal. If i find one then I'll re-write the code above to use signals as a generic pre save listner.</p>
| 2 | 2009-07-22T15:01:54Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I have my model setup nicely and plugged into the admin, and the image uploads fine to the directory:</p>
<pre><code>from django.db import models
# This is to list all the countries
# For starters though, this will be just United Kingdom (GB)
class Country(models.Model):
name = models.CharField(max_length=120, help_text="Full name of country")
code = models.CharField(max_length=2, help_text="This is the ISO 3166 2-letter country code (see: http://www.theodora.com/country_digraphs.html)")
flag = models.ImageField(upload_to="images/uploaded/country/", max_length=150, help_text="The flag image of the country.", blank=True)
class Meta:
verbose_name_plural = "Countries"
def __unicode__(self):
return self.name
</code></pre>
<p>The thing I'm now having trouble with is taking that file and making a new file into a thumbnail. Like I say, I'd like to know how to do it without using others' apps (for now). I have got this code from DjangoSnippets:</p>
<pre><code>from PIL import Image
import os.path
import StringIO
def thumbnail(filename, size=(50, 50), output_filename=None):
image = Image.open(filename)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
# get the thumbnail data in memory.
if not output_filename:
output_filename = get_default_thumbnail_filename(filename)
image.save(output_filename, image.format)
return output_filename
def thumbnail_string(buf, size=(50, 50)):
f = StringIO.StringIO(buf)
image = Image.open(f)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
o = StringIO.StringIO()
image.save(o, "JPEG")
return o.getvalue()
def get_default_thumbnail_filename(filename):
path, ext = os.path.splitext(filename)
return path + '.thumb.jpg'
</code></pre>
<p>...but this has ultimately confused me... As I don't know how this 'fits in' to my Django app? And really, is it the best solution for simply making a thumbnail of an image that has been successfully uploaded? Can anyone possibly show me a good, solid, decent way that a beginner like me can learn to do this properly? As in, knowing where to put that sort of code (models.py? forms.py? ...) and how it would work in context? ... I just need a bit of help understanding and working this problem out.</p>
<p>Thank you!</p>
| 11 | 2009-07-22T12:32:54Z | 1,335,728 | <p>I also swear by Justin Driscoll's <a href="http://code.google.com/p/django-photologue/" rel="nofollow">django-photologue</a> is also great for resizing. It:</p>
<ol>
<li><strong>Resizes</strong> (that is can be scaled to a height or width proportionately)</li>
<li><strong>Crops</strong> (kind-of intelligently: from the center, top, left, bottom or right)</li>
<li>Optionally <strong>upsizes</strong></li>
<li>Can add <strong>effects</strong> (such as "color", "brightness", "contrast" and "sharpness" as well as filters like "Find Edges" and "Emboss". Sharpen your images. Make your thumbnails black and white.)</li>
<li>Can add simple <strong>watermark</strong></li>
<li><strong>Cache</strong> the results</li>
</ol>
<p>Basically it's awesome.</p>
| 0 | 2009-08-26T15:51:36Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I have my model setup nicely and plugged into the admin, and the image uploads fine to the directory:</p>
<pre><code>from django.db import models
# This is to list all the countries
# For starters though, this will be just United Kingdom (GB)
class Country(models.Model):
name = models.CharField(max_length=120, help_text="Full name of country")
code = models.CharField(max_length=2, help_text="This is the ISO 3166 2-letter country code (see: http://www.theodora.com/country_digraphs.html)")
flag = models.ImageField(upload_to="images/uploaded/country/", max_length=150, help_text="The flag image of the country.", blank=True)
class Meta:
verbose_name_plural = "Countries"
def __unicode__(self):
return self.name
</code></pre>
<p>The thing I'm now having trouble with is taking that file and making a new file into a thumbnail. Like I say, I'd like to know how to do it without using others' apps (for now). I have got this code from DjangoSnippets:</p>
<pre><code>from PIL import Image
import os.path
import StringIO
def thumbnail(filename, size=(50, 50), output_filename=None):
image = Image.open(filename)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
# get the thumbnail data in memory.
if not output_filename:
output_filename = get_default_thumbnail_filename(filename)
image.save(output_filename, image.format)
return output_filename
def thumbnail_string(buf, size=(50, 50)):
f = StringIO.StringIO(buf)
image = Image.open(f)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
o = StringIO.StringIO()
image.save(o, "JPEG")
return o.getvalue()
def get_default_thumbnail_filename(filename):
path, ext = os.path.splitext(filename)
return path + '.thumb.jpg'
</code></pre>
<p>...but this has ultimately confused me... As I don't know how this 'fits in' to my Django app? And really, is it the best solution for simply making a thumbnail of an image that has been successfully uploaded? Can anyone possibly show me a good, solid, decent way that a beginner like me can learn to do this properly? As in, knowing where to put that sort of code (models.py? forms.py? ...) and how it would work in context? ... I just need a bit of help understanding and working this problem out.</p>
<p>Thank you!</p>
| 11 | 2009-07-22T12:32:54Z | 6,321,526 | <p>You can give a try to:</p>
<p><a href="https://github.com/francescortiz/image" rel="nofollow">image headcut</a></p>
<p>features:</p>
<ul>
<li>Allows you to set the center of attention of an image... heads won't get cut anymore.</li>
<li>Video thumbnailing</li>
<li>Prevents cross-site image linking</li>
<li>Simple setup and usage</li>
</ul>
| 2 | 2011-06-12T10:49:44Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Image resizing with django? | 1,164,930 | <p>I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I have my model setup nicely and plugged into the admin, and the image uploads fine to the directory:</p>
<pre><code>from django.db import models
# This is to list all the countries
# For starters though, this will be just United Kingdom (GB)
class Country(models.Model):
name = models.CharField(max_length=120, help_text="Full name of country")
code = models.CharField(max_length=2, help_text="This is the ISO 3166 2-letter country code (see: http://www.theodora.com/country_digraphs.html)")
flag = models.ImageField(upload_to="images/uploaded/country/", max_length=150, help_text="The flag image of the country.", blank=True)
class Meta:
verbose_name_plural = "Countries"
def __unicode__(self):
return self.name
</code></pre>
<p>The thing I'm now having trouble with is taking that file and making a new file into a thumbnail. Like I say, I'd like to know how to do it without using others' apps (for now). I have got this code from DjangoSnippets:</p>
<pre><code>from PIL import Image
import os.path
import StringIO
def thumbnail(filename, size=(50, 50), output_filename=None):
image = Image.open(filename)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
# get the thumbnail data in memory.
if not output_filename:
output_filename = get_default_thumbnail_filename(filename)
image.save(output_filename, image.format)
return output_filename
def thumbnail_string(buf, size=(50, 50)):
f = StringIO.StringIO(buf)
image = Image.open(f)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
o = StringIO.StringIO()
image.save(o, "JPEG")
return o.getvalue()
def get_default_thumbnail_filename(filename):
path, ext = os.path.splitext(filename)
return path + '.thumb.jpg'
</code></pre>
<p>...but this has ultimately confused me... As I don't know how this 'fits in' to my Django app? And really, is it the best solution for simply making a thumbnail of an image that has been successfully uploaded? Can anyone possibly show me a good, solid, decent way that a beginner like me can learn to do this properly? As in, knowing where to put that sort of code (models.py? forms.py? ...) and how it would work in context? ... I just need a bit of help understanding and working this problem out.</p>
<p>Thank you!</p>
| 11 | 2009-07-22T12:32:54Z | 36,697,496 | <p>Another alternative is to use Imagemagick directly, if you want to avoid several difficulties with Pillow and Python 3 such as <a href="http://stackoverflow.com/questions/23970006/using-pillow-with-python-3">this one</a>.</p>
<pre><code>from subprocess import call
call(['convert', img_path_file_name, '-thumbnail', target_size_str, '-antialias', style_path_file_name])
</code></pre>
<p>You could call this on model save, or on a template tag to generate an one-off manipulated copy of the original file in a file-caching fashion, or even a celery task.</p>
<p>You can get an example of how I have used this in one of my projects:</p>
<ul>
<li><a href="https://github.com/Wtower/django-ninecms/blob/devel/ninecms/utils/media.py#L110" rel="nofollow">main function</a></li>
<li><a href="https://github.com/Wtower/django-ninecms/blob/devel/ninecms/settings.py#L289" rel="nofollow">relevant settings</a></li>
<li><a href="https://github.com/Wtower/django-ninecms/blob/devel/ninecms/templatetags/ninecms_extras.py#L20" rel="nofollow">templatetag</a></li>
<li><a href="https://github.com/Wtower/django-ninecms/blob/devel/ninecms/templates/ninecms/block_static.html#L15" rel="nofollow">how to use</a></li>
</ul>
| 0 | 2016-04-18T14:54:54Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
SQLAlchemy - Models - using dynamic fields - ActiveRecord | 1,165,002 | <p>How close can I get to defining a model in SQLAlchemy like:</p>
<pre><code>class Person(Base):
pass
</code></pre>
<p>And just have it dynamically pick up the field names? anyway to get naming conventions to control the relationships between tables? I guess I'm looking for something similar to RoR's ActiveRecord but in Python.</p>
<p>Not sure if this matters but I'll be trying to use this under IronPython rather than cPython.</p>
| 1 | 2009-07-22T12:45:32Z | 1,165,050 | <p>It is very simple to automatically pick up the field names:</p>
<pre><code>from sqlalchemy import Table
from sqlalchemy.orm import MetaData, mapper
metadata = MetaData()
metadata.bind = engine
person_table = Table(metadata, "tablename", autoload=True)
class Person(object):
pass
mapper(Person, person_table)
</code></pre>
<p>Using this approach, you have to define the relationships in the call to <code>mapper()</code>, so no auto-discovery of relationships.</p>
<p>To automatically map classes to tables with same name, you could do:</p>
<pre><code>def map_class(class_):
table = Table(metadata, class_.__name__, autoload=True)
mapper(class_, table)
map_class(Person)
map_class(Order)
</code></pre>
<p>Elixir might do everything you want.</p>
| 4 | 2009-07-22T12:53:21Z | [
"python",
"activerecord",
"ironpython",
"sqlalchemy"
] |
SQLAlchemy - Models - using dynamic fields - ActiveRecord | 1,165,002 | <p>How close can I get to defining a model in SQLAlchemy like:</p>
<pre><code>class Person(Base):
pass
</code></pre>
<p>And just have it dynamically pick up the field names? anyway to get naming conventions to control the relationships between tables? I guess I'm looking for something similar to RoR's ActiveRecord but in Python.</p>
<p>Not sure if this matters but I'll be trying to use this under IronPython rather than cPython.</p>
| 1 | 2009-07-22T12:45:32Z | 1,165,100 | <p>AFAIK sqlalchemy intentionally decouples database metadata and class layout. </p>
<p>You may should investigate Elixir (<a href="http://elixir.ematia.de/trac/wiki" rel="nofollow">http://elixir.ematia.de/trac/wiki</a>): Active Record Pattern for sqlalchemy, but you have to define the classes, not the database tables.</p>
| 2 | 2009-07-22T13:00:43Z | [
"python",
"activerecord",
"ironpython",
"sqlalchemy"
] |
Python: cannot read / write in another commandline application by using subprocess module | 1,165,064 | <p>I am using Python 3.0 in Windows and trying to automate the testing of a commandline application. The user can type commands in Application Under Test and it returns the output as 2 XML packets. One is a packet and the other one is an packet. By analyzing these packets I can verifyt he result. I ahev the code as below</p>
<pre><code>p = subprocess.Popen(SomeCmdAppl, stdout=subprocess.PIPE,
shell = True, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
p.stdin.write((command + '\r\n').encode())
time.sleep(2.5)
testresult = p.stdout.readline()
testresult = testresult.decode()
print(testresult)
</code></pre>
<p>I cannot ge any output back. It get stuck in place where I try to read the output by using readline(). I tried read() and it get stuck too</p>
<p>When I run the commandline application manually and type the command I get the output back correctly as tow xml packets as below</p>
<pre><code>Sent: <PivotNetMessage>
<MessageId>16f8addf-d366-4031-b3d3-5593efb9f7dd</MessageId>
<ConversationId>373323be-31dd-4858-a7f9-37d97e36eb36</ConversationId>
<SageId>4e1e7c04-4cea-49b2-8af1-64d0f348e621</SagaId>
<SourcePath>C:\Python30\PyNTEST</SourcePath>
<Command>echo</Command>
<Content>Hello</Content>
<Time>7/4/2009 11:16:41 PM</Time>
<ErrorCode>0</ErrorCode>
<ErrorInfo></ErrorInfo>
</PivotNetMessagSent>
Recv: <PivotNetMessage>
<MessageId>16f8addf-d366-4031-b3d3-5593efb9f7dd</MessageId>
<ConversationId>373323be-31dd-4858-a7f9-37d97e36eb36</ConversationId>
<SageId>4e1e7c04-4cea-49b2-8af1-64d0f348e621</SagaId>
<SourcePath>C:\PivotNet\Endpoints\Pipeline\Pipeline_2.0.0.202</SourcePath>
<Command>echo</Command>
<Content>Hello</Content>
<Time>7/4/2009 11:16:41 PM</Time>
<ErrorCode>0</ErrorCode>
<ErrorInfo></ErrorInfo>
</PivotNetMessage>
</code></pre>
<p>But when I use the communicate() as below I get the Sent packet and never get the Recv: packet. Why am I missing the recv packet? The communicate(0 is supposed to bring everything from stdout. rt?</p>
<pre><code>p = subprocess.Popen(SomeCmdAppl, stdout=subprocess.PIPE,
shell = True, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
p.stdin.write((command + '\r\n').encode())
time.sleep(2.5)
result = p.communicate()[0]
print(result)
</code></pre>
<p>Can anybody help me with a sample code that should work? I don't know if it is needed to read and write in separate threads. Please help me. I need to do repeated read/write. Is there any advanced level module in python i can use. I think Pexpect module doesn't work in Windows</p>
| 1 | 2009-07-22T12:55:08Z | 1,165,126 | <p>Try sending your input using <code>communicate</code> instead of using <code>write</code>:</p>
<pre><code>result = p.communicate((command + '\r\n').encode())[0]
</code></pre>
| 0 | 2009-07-22T13:04:56Z | [
"python",
"subprocess",
"readline"
] |
Python: cannot read / write in another commandline application by using subprocess module | 1,165,064 | <p>I am using Python 3.0 in Windows and trying to automate the testing of a commandline application. The user can type commands in Application Under Test and it returns the output as 2 XML packets. One is a packet and the other one is an packet. By analyzing these packets I can verifyt he result. I ahev the code as below</p>
<pre><code>p = subprocess.Popen(SomeCmdAppl, stdout=subprocess.PIPE,
shell = True, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
p.stdin.write((command + '\r\n').encode())
time.sleep(2.5)
testresult = p.stdout.readline()
testresult = testresult.decode()
print(testresult)
</code></pre>
<p>I cannot ge any output back. It get stuck in place where I try to read the output by using readline(). I tried read() and it get stuck too</p>
<p>When I run the commandline application manually and type the command I get the output back correctly as tow xml packets as below</p>
<pre><code>Sent: <PivotNetMessage>
<MessageId>16f8addf-d366-4031-b3d3-5593efb9f7dd</MessageId>
<ConversationId>373323be-31dd-4858-a7f9-37d97e36eb36</ConversationId>
<SageId>4e1e7c04-4cea-49b2-8af1-64d0f348e621</SagaId>
<SourcePath>C:\Python30\PyNTEST</SourcePath>
<Command>echo</Command>
<Content>Hello</Content>
<Time>7/4/2009 11:16:41 PM</Time>
<ErrorCode>0</ErrorCode>
<ErrorInfo></ErrorInfo>
</PivotNetMessagSent>
Recv: <PivotNetMessage>
<MessageId>16f8addf-d366-4031-b3d3-5593efb9f7dd</MessageId>
<ConversationId>373323be-31dd-4858-a7f9-37d97e36eb36</ConversationId>
<SageId>4e1e7c04-4cea-49b2-8af1-64d0f348e621</SagaId>
<SourcePath>C:\PivotNet\Endpoints\Pipeline\Pipeline_2.0.0.202</SourcePath>
<Command>echo</Command>
<Content>Hello</Content>
<Time>7/4/2009 11:16:41 PM</Time>
<ErrorCode>0</ErrorCode>
<ErrorInfo></ErrorInfo>
</PivotNetMessage>
</code></pre>
<p>But when I use the communicate() as below I get the Sent packet and never get the Recv: packet. Why am I missing the recv packet? The communicate(0 is supposed to bring everything from stdout. rt?</p>
<pre><code>p = subprocess.Popen(SomeCmdAppl, stdout=subprocess.PIPE,
shell = True, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
p.stdin.write((command + '\r\n').encode())
time.sleep(2.5)
result = p.communicate()[0]
print(result)
</code></pre>
<p>Can anybody help me with a sample code that should work? I don't know if it is needed to read and write in separate threads. Please help me. I need to do repeated read/write. Is there any advanced level module in python i can use. I think Pexpect module doesn't work in Windows</p>
| 1 | 2009-07-22T12:55:08Z | 1,165,421 | <p>This is a popular problem, e.g. see:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/1124884/interact-with-a-windows-console-application-via-python">http://stackoverflow.com/questions/1124884/interact-with-a-windows-console-application-via-python</a></li>
<li><a href="http://stackoverflow.com/questions/874815/how-do-i-get-real-time-information-back-from-a-subprocess-popen-in-python-2-5">http://stackoverflow.com/questions/874815/how-do-i-get-real-time-information-back-from-a-subprocess-popen-in-python-2-5</a></li>
<li><a href="http://stackoverflow.com/questions/1161580/how-do-i-read-everything-currently-in-a-subprocess-stdout-pipe-and-then-return">http://stackoverflow.com/questions/1161580/how-do-i-read-everything-currently-in-a-subprocess-stdout-pipe-and-then-return</a></li>
</ul>
<p>(Actually, you should have seen these during creation of your question...?!).</p>
<p>I have two things of interest:</p>
<ul>
<li>p.stdin.write((command + '\r\n').encode()) is also <em>buffered</em> so your child process might not even have seen its input. You can try flushing this pipe.</li>
<li>In one of the other questions one suggested doing a stdout.<em>read()</em> on the child instead of <em>readline()</em>, with a suitable amount of characters to read. You might want to experiment with this. </li>
</ul>
<p>Post your results.</p>
| 1 | 2009-07-22T13:52:50Z | [
"python",
"subprocess",
"readline"
] |
Python: cannot read / write in another commandline application by using subprocess module | 1,165,064 | <p>I am using Python 3.0 in Windows and trying to automate the testing of a commandline application. The user can type commands in Application Under Test and it returns the output as 2 XML packets. One is a packet and the other one is an packet. By analyzing these packets I can verifyt he result. I ahev the code as below</p>
<pre><code>p = subprocess.Popen(SomeCmdAppl, stdout=subprocess.PIPE,
shell = True, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
p.stdin.write((command + '\r\n').encode())
time.sleep(2.5)
testresult = p.stdout.readline()
testresult = testresult.decode()
print(testresult)
</code></pre>
<p>I cannot ge any output back. It get stuck in place where I try to read the output by using readline(). I tried read() and it get stuck too</p>
<p>When I run the commandline application manually and type the command I get the output back correctly as tow xml packets as below</p>
<pre><code>Sent: <PivotNetMessage>
<MessageId>16f8addf-d366-4031-b3d3-5593efb9f7dd</MessageId>
<ConversationId>373323be-31dd-4858-a7f9-37d97e36eb36</ConversationId>
<SageId>4e1e7c04-4cea-49b2-8af1-64d0f348e621</SagaId>
<SourcePath>C:\Python30\PyNTEST</SourcePath>
<Command>echo</Command>
<Content>Hello</Content>
<Time>7/4/2009 11:16:41 PM</Time>
<ErrorCode>0</ErrorCode>
<ErrorInfo></ErrorInfo>
</PivotNetMessagSent>
Recv: <PivotNetMessage>
<MessageId>16f8addf-d366-4031-b3d3-5593efb9f7dd</MessageId>
<ConversationId>373323be-31dd-4858-a7f9-37d97e36eb36</ConversationId>
<SageId>4e1e7c04-4cea-49b2-8af1-64d0f348e621</SagaId>
<SourcePath>C:\PivotNet\Endpoints\Pipeline\Pipeline_2.0.0.202</SourcePath>
<Command>echo</Command>
<Content>Hello</Content>
<Time>7/4/2009 11:16:41 PM</Time>
<ErrorCode>0</ErrorCode>
<ErrorInfo></ErrorInfo>
</PivotNetMessage>
</code></pre>
<p>But when I use the communicate() as below I get the Sent packet and never get the Recv: packet. Why am I missing the recv packet? The communicate(0 is supposed to bring everything from stdout. rt?</p>
<pre><code>p = subprocess.Popen(SomeCmdAppl, stdout=subprocess.PIPE,
shell = True, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
p.stdin.write((command + '\r\n').encode())
time.sleep(2.5)
result = p.communicate()[0]
print(result)
</code></pre>
<p>Can anybody help me with a sample code that should work? I don't know if it is needed to read and write in separate threads. Please help me. I need to do repeated read/write. Is there any advanced level module in python i can use. I think Pexpect module doesn't work in Windows</p>
| 1 | 2009-07-22T12:55:08Z | 1,377,143 | <p>Have you considered using pexpect instead of subprocess? It handles the details which are probably preventing your code from working (like flushing buffers, etc). It may not be available for Py3k yet, but it works well in 2.x.</p>
<p>See: <a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">http://pexpect.sourceforge.net/pexpect.html</a></p>
| 0 | 2009-09-04T03:49:19Z | [
"python",
"subprocess",
"readline"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 1,165,398 | <p>not sure whether its "fast" or not, but normally, one can do this</p>
<pre><code>dicta = {"a":1,"b":2,"c":3,"d":4}
dictb = {"a":1,"d":2}
for key in dicta.keys():
if not key in dictb:
print key
</code></pre>
| 14 | 2009-07-22T13:48:39Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 1,165,429 | <p>As Alex Martelli wrote, if you simply want to check if any key in B is not in A, <code>any(True for k in dictB if k not in dictA)</code> would be the way to go.</p>
<p>To find the keys that are missing:</p>
<pre><code>diff = set(dictB)-set(dictA) #sets
C:\Dokumente und Einstellungen\thc>python -m timeit -s "dictA =
dict(zip(range(1000),range
(1000))); dictB = dict(zip(range(0,2000,2),range(1000)))" "diff=set(dictB)-set(dictA)"
10000 loops, best of 3: 107 usec per loop
diff = [ k for k in dictB if k not in dictA ] #lc
C:\Dokumente und Einstellungen\thc>python -m timeit -s "dictA =
dict(zip(range(1000),range
(1000))); dictB = dict(zip(range(0,2000,2),range(1000)))" "diff=[ k for k in dictB if
k not in dictA ]"
10000 loops, best of 3: 95.9 usec per loop
</code></pre>
<p>So those two solutions are pretty much the same speed. </p>
| 14 | 2009-07-22T13:53:29Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 1,165,552 | <p>You can use set operations on the keys:</p>
<pre><code>diff = set(dictb.keys()) - set(dicta.keys())
</code></pre>
<p>Here is a class to find all the possibilities: what was added, what was removed, which key-value pairs are the same, and which key-value pairs are changed.</p>
<pre><code>class DictDiffer(object):
"""
Calculate the difference between two dictionaries as:
(1) items added
(2) items removed
(3) keys same in both but changed values
(4) keys same in both and unchanged values
"""
def __init__(self, current_dict, past_dict):
self.current_dict, self.past_dict = current_dict, past_dict
self.set_current, self.set_past = set(current_dict.keys()), set(past_dict.keys())
self.intersect = self.set_current.intersection(self.set_past)
def added(self):
return self.set_current - self.intersect
def removed(self):
return self.set_past - self.intersect
def changed(self):
return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o])
def unchanged(self):
return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o])
</code></pre>
<p>Here is some sample output:</p>
<pre><code>>>> a = {'a': 1, 'b': 1, 'c': 0}
>>> b = {'a': 1, 'b': 2, 'd': 0}
>>> d = DictDiffer(b, a)
>>> print "Added:", d.added()
Added: set(['d'])
>>> print "Removed:", d.removed()
Removed: set(['c'])
>>> print "Changed:", d.changed()
Changed: set(['b'])
>>> print "Unchanged:", d.unchanged()
Unchanged: set(['a'])
</code></pre>
<p>Available as a github repo:
<a href="https://github.com/hughdbrown/dictdiffer">https://github.com/hughdbrown/dictdiffer</a></p>
| 176 | 2009-07-22T14:11:51Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 1,166,569 | <p>If you really mean exactly what you say (that you only need to find out IF "there are any keys" in B and not in A, not WHICH ONES might those be if any), the fastest way should be:</p>
<pre><code>if any(True for k in dictB if k not in dictA): ...
</code></pre>
<p>If you actually need to find out WHICH KEYS, if any, are in B and not in A, and not just "IF" there are such keys, then existing answers are quite appropriate (but I do suggest more precision in future questions if that's indeed what you mean;-).</p>
| 12 | 2009-07-22T16:39:16Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 1,166,667 | <p>Here's a way that will work, allows for keys that evaluate to <code>False</code>, and still uses a generator expression to fall out early if possible. It's not exceptionally pretty though.</p>
<pre><code>any(map(lambda x: True, (k for k in b if k not in a)))
</code></pre>
<p><strong>EDIT:</strong></p>
<p>THC4k posted a reply to my comment on another answer. Here's a better, prettier way to do the above:</p>
<pre><code>any(True for k in b if k not in a)
</code></pre>
<p>Not sure how that never crossed my mind...</p>
| 2 | 2009-07-22T16:56:13Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 7,724,964 | <p>If on Python ⥠2.7:</p>
<pre><code># update different values in dictB
# I would assume only dictA should be updated,
# but the question specifies otherwise
for k in dictA.viewkeys() & dictB.viewkeys():
if dictA[k] != dictB[k]:
dictB[k]= dictA[k]
# add missing keys to dictA
dictA.update( (k,dictB[k]) for k in dictB.viewkeys() - dictA.viewkeys() )
</code></pre>
| 2 | 2011-10-11T11:01:05Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 9,024,729 | <p>what about standart (compare FULL Object)</p>
<p>PyDev->new PyDev Module->Module: unittest</p>
<pre><code>import unittest
class Test(unittest.TestCase):
def testName(self):
obj1 = {1:1, 2:2}
obj2 = {1:1, 2:2}
self.maxDiff = None # sometimes is usefull
self.assertDictEqual(d1, d2)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
</code></pre>
| 0 | 2012-01-26T20:19:12Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 16,451,938 | <p>Not sure if it is still relevant but I came across this problem, my situation i just needed to return a dictionary of the changes for all nested dictionaries etc etc. Could not find a good solution out there but I did end up <a href="https://github.com/jmickle/jmickle/blob/master/recurse_dicts.py" rel="nofollow">writing a simple function to do this</a>. Hope this helps, </p>
| 0 | 2013-05-08T23:33:07Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 19,634,030 | <p>There is an other <a href="http://stackoverflow.com/questions/6632244/difference-in-a-dict">question in stackoverflow about this argument</a> and i have to admit that there is a simple solution explained: the <a href="https://pypi.python.org/pypi/datadiff" rel="nofollow">datadiff library</a> of python helps printing the difference between two dictionaries. </p>
| 4 | 2013-10-28T11:47:32Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 23,134,762 | <p>This is an old question and asks a little bit less than what I needed so this answer actually solves more than this question asks. The answers in this question helped me solve the following:</p>
<ol>
<li>(asked) Record differences between two dictionaries</li>
<li>Merge differences from #1 into base dictionary</li>
<li>(asked) Merge differences between two dictionaries (treat dictionary #2 as if it were a diff dictionary)</li>
<li>Try to detect item movements as well as changes</li>
<li>(asked) Do all of this recursively</li>
</ol>
<p>All this combined with JSON makes for a pretty powerful configuration storage support.</p>
<p>The solution (<a href="https://github.com/velis74/dictdiff" rel="nofollow">also on github</a>):</p>
<pre><code>from collections import OrderedDict
from pprint import pprint
class izipDestinationMatching(object):
__slots__ = ("attr", "value", "index")
def __init__(self, attr, value, index):
self.attr, self.value, self.index = attr, value, index
def __repr__(self):
return "izip_destination_matching: found match by '%s' = '%s' @ %d" % (self.attr, self.value, self.index)
def izip_destination(a, b, attrs, addMarker=True):
"""
Returns zipped lists, but final size is equal to b with (if shorter) a padded with nulls
Additionally also tries to find item reallocations by searching child dicts (if they are dicts) for attribute, listed in attrs)
When addMarker == False (patching), final size will be the longer of a, b
"""
for idx, item in enumerate(b):
try:
attr = next((x for x in attrs if x in item), None) # See if the item has any of the ID attributes
match, matchIdx = next(((orgItm, idx) for idx, orgItm in enumerate(a) if attr in orgItm and orgItm[attr] == item[attr]), (None, None)) if attr else (None, None)
if match and matchIdx != idx and addMarker: item[izipDestinationMatching] = izipDestinationMatching(attr, item[attr], matchIdx)
except:
match = None
yield (match if match else a[idx] if len(a) > idx else None), item
if not addMarker and len(a) > len(b):
for item in a[len(b) - len(a):]:
yield item, item
def dictdiff(a, b, searchAttrs=[]):
"""
returns a dictionary which represents difference from a to b
the return dict is as short as possible:
equal items are removed
added / changed items are listed
removed items are listed with value=None
Also processes list values where the resulting list size will match that of b.
It can also search said list items (that are dicts) for identity values to detect changed positions.
In case such identity value is found, it is kept so that it can be re-found during the merge phase
@param a: original dict
@param b: new dict
@param searchAttrs: list of strings (keys to search for in sub-dicts)
@return: dict / list / whatever input is
"""
if not (isinstance(a, dict) and isinstance(b, dict)):
if isinstance(a, list) and isinstance(b, list):
return [dictdiff(v1, v2, searchAttrs) for v1, v2 in izip_destination(a, b, searchAttrs)]
return b
res = OrderedDict()
if izipDestinationMatching in b:
keepKey = b[izipDestinationMatching].attr
del b[izipDestinationMatching]
else:
keepKey = izipDestinationMatching
for key in sorted(set(a.keys() + b.keys())):
v1 = a.get(key, None)
v2 = b.get(key, None)
if keepKey == key or v1 != v2: res[key] = dictdiff(v1, v2, searchAttrs)
if len(res) <= 1: res = dict(res) # This is only here for pretty print (OrderedDict doesn't pprint nicely)
return res
def dictmerge(a, b, searchAttrs=[]):
"""
Returns a dictionary which merges differences recorded in b to base dictionary a
Also processes list values where the resulting list size will match that of a
It can also search said list items (that are dicts) for identity values to detect changed positions
@param a: original dict
@param b: diff dict to patch into a
@param searchAttrs: list of strings (keys to search for in sub-dicts)
@return: dict / list / whatever input is
"""
if not (isinstance(a, dict) and isinstance(b, dict)):
if isinstance(a, list) and isinstance(b, list):
return [dictmerge(v1, v2, searchAttrs) for v1, v2 in izip_destination(a, b, searchAttrs, False)]
return b
res = OrderedDict()
for key in sorted(set(a.keys() + b.keys())):
v1 = a.get(key, None)
v2 = b.get(key, None)
#print "processing", key, v1, v2, key not in b, dictmerge(v1, v2)
if v2 is not None: res[key] = dictmerge(v1, v2, searchAttrs)
elif key not in b: res[key] = v1
if len(res) <= 1: res = dict(res) # This is only here for pretty print (OrderedDict doesn't pprint nicely)
return res
</code></pre>
| 1 | 2014-04-17T13:40:38Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 26,079,022 | <p>In case you want the difference recursively, I have written a package for python:
<a href="https://github.com/seperman/deepdiff">https://github.com/seperman/deepdiff</a></p>
<h2>Installation</h2>
<p>Install from PyPi:</p>
<pre><code>pip install deepdiff
</code></pre>
<h2>Example usage</h2>
<p>Importing</p>
<pre><code>>>> from deepdiff import DeepDiff
>>> from pprint import pprint
>>> from __future__ import print_function # In case running on Python 2
</code></pre>
<p>Same object returns empty</p>
<pre><code>>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = t1
>>> print(DeepDiff(t1, t2))
{}
</code></pre>
<p>Type of an item has changed</p>
<pre><code>>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:"2", 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{ 'type_changes': { 'root[2]': { 'newtype': <class 'str'>,
'newvalue': '2',
'oldtype': <class 'int'>,
'oldvalue': 2}}}
</code></pre>
<p>Value of an item has changed</p>
<pre><code>>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:4, 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}
</code></pre>
<p>Item added and/or removed</p>
<pre><code>>>> t1 = {1:1, 2:2, 3:3, 4:4}
>>> t2 = {1:1, 2:4, 3:3, 5:5, 6:6}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff)
{'dic_item_added': ['root[5]', 'root[6]'],
'dic_item_removed': ['root[4]'],
'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}
</code></pre>
<p>String difference</p>
<pre><code>>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world"}}
>>> t2 = {1:1, 2:4, 3:3, 4:{"a":"hello", "b":"world!"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { 'root[2]': {'newvalue': 4, 'oldvalue': 2},
"root[4]['b']": { 'newvalue': 'world!',
'oldvalue': 'world'}}}
</code></pre>
<p>String difference 2</p>
<pre><code>>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world!\nGoodbye!\n1\n2\nEnd"}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n1\n2\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { "root[4]['b']": { 'diff': '--- \n'
'+++ \n'
'@@ -1,5 +1,4 @@\n'
'-world!\n'
'-Goodbye!\n'
'+world\n'
' 1\n'
' 2\n'
' End',
'newvalue': 'world\n1\n2\nEnd',
'oldvalue': 'world!\n'
'Goodbye!\n'
'1\n'
'2\n'
'End'}}}
>>>
>>> print (ddiff['values_changed']["root[4]['b']"]["diff"])
---
+++
@@ -1,5 +1,4 @@
-world!
-Goodbye!
+world
1
2
End
</code></pre>
<p>Type change</p>
<pre><code>>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n\n\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'type_changes': { "root[4]['b']": { 'newtype': <class 'str'>,
'newvalue': 'world\n\n\nEnd',
'oldtype': <class 'list'>,
'oldvalue': [1, 2, 3]}}}
</code></pre>
<p>List difference</p>
<pre><code>>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3, 4]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{'iterable_item_removed': {"root[4]['b'][2]": 3, "root[4]['b'][3]": 4}}
</code></pre>
<p>List difference 2:</p>
<pre><code>>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'iterable_item_added': {"root[4]['b'][3]": 3},
'values_changed': { "root[4]['b'][1]": {'newvalue': 3, 'oldvalue': 2},
"root[4]['b'][2]": {'newvalue': 2, 'oldvalue': 3}}}
</code></pre>
<p>List difference ignoring order or duplicates: (with the same dictionaries as above)</p>
<pre><code>>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2, ignore_order=True)
>>> print (ddiff)
{}
</code></pre>
<p>List that contains dictionary:</p>
<pre><code>>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:1, 2:2}]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:3}]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'dic_item_removed': ["root[4]['b'][2][2]"],
'values_changed': {"root[4]['b'][2][1]": {'newvalue': 3, 'oldvalue': 1}}}
</code></pre>
<p>Sets:</p>
<pre><code>>>> t1 = {1, 2, 8}
>>> t2 = {1, 2, 3, 5}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (DeepDiff(t1, t2))
{'set_item_added': ['root[3]', 'root[5]'], 'set_item_removed': ['root[8]']}
</code></pre>
<p>Named Tuples:</p>
<pre><code>>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> t1 = Point(x=11, y=22)
>>> t2 = Point(x=11, y=23)
>>> pprint (DeepDiff(t1, t2))
{'values_changed': {'root.y': {'newvalue': 23, 'oldvalue': 22}}}
</code></pre>
<p>Custom objects:</p>
<pre><code>>>> class ClassA(object):
... a = 1
... def __init__(self, b):
... self.b = b
...
>>> t1 = ClassA(1)
>>> t2 = ClassA(2)
>>>
>>> pprint(DeepDiff(t1, t2))
{'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}
</code></pre>
<p>Object attribute added:</p>
<pre><code>>>> t2.c = "new attribute"
>>> pprint(DeepDiff(t1, t2))
{'attribute_added': ['root.c'],
'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}
</code></pre>
| 23 | 2014-09-27T20:41:27Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 26,776,247 | <p>Here is a solution for deep comparing 2 dictionaries keys:</p>
<pre><code>def compareDictKeys(dict1, dict2):
if type(dict1) != dict or type(dict2) != dict:
return False
keys1, keys2 = dict1.keys(), dict2.keys()
diff = set(keys1) - set(keys2) or set(keys2) - set(keys1)
if not diff:
for key in keys1:
if (type(dict1[key]) == dict or type(dict2[key]) == dict) and not compareDictKeys(dict1[key], dict2[key]):
diff = True
break
return not diff
</code></pre>
| 1 | 2014-11-06T09:49:39Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 27,717,113 | <p>If you want a built-in solution for a full comparison with arbitrary dict structures, @Maxx's answer is a good start.</p>
<pre><code>import unittest
test = unittest.TestCase()
test.assertEqual(dictA, dictB)
</code></pre>
| 0 | 2014-12-31T06:26:57Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 28,974,718 | <p>here's a solution that can compare more than two dicts:</p>
<pre><code>def diff_dict(dicts, default=None):
diff_dict = {}
# add 'list()' around 'd.keys()' for python 3 compatibility
for k in set(sum([d.keys() for d in dicts], [])):
# we can just use "values = [d.get(k, default) ..." below if
# we don't care that d1[k]=default and d2[k]=missing will
# be treated as equal
if any(k not in d for d in dicts):
diff_dict[k] = [d.get(k, default) for d in dicts]
else:
values = [d[k] for d in dicts]
if any(v != values[0] for v in values):
diff_dict[k] = values
return diff_dict
</code></pre>
<p>usage example:</p>
<pre><code>import matplotlib.pyplot as plt
diff_dict([plt.rcParams, plt.rcParamsDefault, plt.matplotlib.rcParamsOrig])
</code></pre>
| 0 | 2015-03-10T21:47:16Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 30,861,178 | <p>Based on ghostdog74's answer,</p>
<pre><code>dicta = {"a":1,"d":2}
dictb = {"a":5,"d":2}
for value in dicta.values():
if not value in dictb.values():
print value
</code></pre>
<p>will print differ value of dicta</p>
| 0 | 2015-06-16T07:20:51Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 35,925,928 | <p>Below i created two dictionaries. I need to return the key and value differences between them. I am stuck here. I am not sure which way is correct. I need to know how to get the key value difference. I want to first check if they are the same and if they are not to print key -value differences. I dont want to use deep diff. I dont know to compare if they are the same ?</p>
<pre><code>num_list = [1,2]
val_list = [0,1]
dict1 = dict(zip(num_list,val_list))
print dict1
num_list2= [1,2]
val_list2 = [0,6]
dict2 = dict(zip(num_list2,val_list2))
print dict2
if dict1 == dict2
</code></pre>
<p>output : currently
{1: 0, 2: 1}
{1: 0, 2: 6}</p>
| 0 | 2016-03-10T19:50:56Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 37,835,849 | <p>My recipe of symmetric difference between two dictionaries:</p>
<pre><code>def find_dict_diffs(dict1, dict2):
unequal_keys = []
unequal_keys.extend(set(dict1.keys()).symmetric_difference(set(dict2.keys())))
for k in dict1.keys():
if dict1.get(k, 'N\A') != dict2.get(k, 'N\A'):
unequal_keys.append(k)
if unequal_keys:
print 'param', 'dict1\t', 'dict2'
for k in set(unequal_keys):
print str(k)+'\t'+dict1.get(k, 'N\A')+'\t '+dict2.get(k, 'N\A')
else:
print 'Dicts are equal'
dict1 = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'}
dict2 = {1:'b', 2:'a', 3:'c', 4:'d', 6:'f'}
find_dict_diffs(dict1, dict2)
</code></pre>
<p>And result is:</p>
<pre><code>param dict1 dict2
1 a b
2 b a
5 e N\A
6 N\A f
</code></pre>
| 0 | 2016-06-15T12:44:04Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 38,405,539 | <p>As mentioned in other answers, unittest produces some nice output for comparing dicts, but in this example we don't want to have to build a whole test first.</p>
<p>Scraping the unittest source, it looks like you can get a fair solution with just this:</p>
<pre><code>import difflib
import pprint
def diff_dicts(a, b):
if a == b:
return ''
return '\n'.join(
difflib.ndiff(pprint.pformat(a, width=30).splitlines(),
pprint.pformat(b, width=30).splitlines())
)
</code></pre>
<p>so</p>
<pre><code>dictA = dict(zip(range(7), map(ord, 'python')))
dictB = {0: 112, 1: 'spam', 2: [1,2,3], 3: 104, 4: 111}
print diff_dicts(dictA, dictB)
</code></pre>
<p>Results in:</p>
<pre><code>{0: 112,
- 1: 121,
- 2: 116,
+ 1: 'spam',
+ 2: [1, 2, 3],
3: 104,
- 4: 111,
? ^
+ 4: 111}
? ^
- 5: 110}
</code></pre>
<p>Where:</p>
<ul>
<li>'-' indicates key/values in the first but not second dict</li>
<li>'+' indicates key/values in the second but not the first dict</li>
</ul>
<p>Like in unittest, the only caveat is that the final mapping can be thought to be a diff, due to the trailing comma/bracket.</p>
| 0 | 2016-07-15T21:55:48Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 38,516,027 | <p>Try this to find de intersection, the keys that is in both dictionarie, if you want the keys not found on second dictionarie, just use the <strong>not in</strong>...</p>
<pre><code>intersect = filter(lambda x, dictB=dictB.keys(): x in dictB, dictA.keys())
</code></pre>
| 0 | 2016-07-21T23:40:03Z | [
"python",
"dictionary"
] |
Calculate difference in keys contained in two Python dictionaries | 1,165,352 | <p>Suppose I have two Python dictionaries - <code>dictA</code> and <code>dictB</code>. I need to find out if there are any keys which are present in <code>dictB</code> but not in <code>dictA</code>. What is the fastest way to go about it?</p>
<p>Should I convert the dictionary keys into a set and then go about?</p>
<p>Interested in knowing your thoughts... </p>
<hr>
<p>Thanks for your responses.</p>
<p>Apologies for not stating my question properly.
My scenario is like this - I have a <code>dictA</code> which can be the same as <code>dictB</code> or may have some keys missing as compared to <code>dictB</code> or else the value of some keys might be different which has to be set to that of <code>dictA</code> key's value.</p>
<p>Problem is the dictionary has no standard and can have values which can be dict of dict.</p>
<p>Say</p>
<pre><code>dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
</code></pre>
<p>So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.</p>
| 112 | 2009-07-22T13:43:13Z | 38,645,967 | <p>use set(), documentation in <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">https://docs.python.org/2/library/sets.html</a></p>
<p>Example:</p>
<p>set(dictA.keys()).intersection(dictB.keys())</p>
| 2 | 2016-07-28T20:16:35Z | [
"python",
"dictionary"
] |
Using select/poll/kqueue/kevent to watch a directory for new files | 1,165,571 | <p>In my app I need to watch a directory for new files. The amount of traffic is very large and there are going to be a minimum of hundreds of new files per second appearing. Currently I'm using a busy loop with this kind of idea:</p>
<pre><code>while True:
time.sleep(0.2)
if len(os.listdir('.')) > 0:
# do stuff
</code></pre>
<p>After running profiling I'm seeing a lot of time spent in the sleep, and I'm wondering if I should change this to use polling instead. </p>
<p>I'm trying to use one of the available classes in <code>select</code> to poll my directory, but I'm not sure if it actually works, or if I'm just doing it wrong.</p>
<p>I get an fd for my directory with:</p>
<pre><code>fd = os.open('.', os.O_DIRECT)
</code></pre>
<p>I've then tried several methods to see when the directory changes. As an example, one of the things I tried was:</p>
<pre><code>poll = select.poll()
poll.register(fd, select.POLLIN)
poll.poll() # returns (fd, 1) meaning 'ready to read'
os.read(fd, 4096) # prints largely gibberish but i can see that i'm pulling the files/folders contained in the directory at least
poll.poll() # returns (fd, 1) again
os.read(fd, 4096) # empty string - no more data
</code></pre>
<p>Why is poll() acting like there is more information to read? I assumed that it would only do that if something had changed in the directory.</p>
<p>Is what I'm trying to do here even possible?</p>
<p>If not, is there any other better alternative to <code>while True: look for changes</code> ?</p>
| 5 | 2009-07-22T14:13:56Z | 1,178,398 | <p>Why not use a Python wrapper for one of the libraries for monitoring file changes, like <a href="http://www.gnome.org/~veillard/gamin/python.html" rel="nofollow">gamin</a> or inotify (search for pyinotify, I'm only allowed to post one hyperlink as a new user...) - that's sure to be faster and the low-level stuff is already done at C level for you, using kernel interfaces...</p>
| 3 | 2009-07-24T15:24:38Z | [
"python",
"asynchronous",
"freebsd",
"polling"
] |
Using select/poll/kqueue/kevent to watch a directory for new files | 1,165,571 | <p>In my app I need to watch a directory for new files. The amount of traffic is very large and there are going to be a minimum of hundreds of new files per second appearing. Currently I'm using a busy loop with this kind of idea:</p>
<pre><code>while True:
time.sleep(0.2)
if len(os.listdir('.')) > 0:
# do stuff
</code></pre>
<p>After running profiling I'm seeing a lot of time spent in the sleep, and I'm wondering if I should change this to use polling instead. </p>
<p>I'm trying to use one of the available classes in <code>select</code> to poll my directory, but I'm not sure if it actually works, or if I'm just doing it wrong.</p>
<p>I get an fd for my directory with:</p>
<pre><code>fd = os.open('.', os.O_DIRECT)
</code></pre>
<p>I've then tried several methods to see when the directory changes. As an example, one of the things I tried was:</p>
<pre><code>poll = select.poll()
poll.register(fd, select.POLLIN)
poll.poll() # returns (fd, 1) meaning 'ready to read'
os.read(fd, 4096) # prints largely gibberish but i can see that i'm pulling the files/folders contained in the directory at least
poll.poll() # returns (fd, 1) again
os.read(fd, 4096) # empty string - no more data
</code></pre>
<p>Why is poll() acting like there is more information to read? I assumed that it would only do that if something had changed in the directory.</p>
<p>Is what I'm trying to do here even possible?</p>
<p>If not, is there any other better alternative to <code>while True: look for changes</code> ?</p>
| 5 | 2009-07-22T14:13:56Z | 1,180,643 | <blockquote>
<p>After running profiling I'm seeing a lot of time spent in the sleep, and I'm wondering if I should change this to use polling instead. </p>
</blockquote>
<p>Looks like you already <em>do</em> synchronous polling, by checking the state at regular intervals. Don't worry about the time "spent" in <code>sleep</code>, it won't eat CPU time. It just passes control to the operating system which wakes the process up after a requested timeout.</p>
<p>You could consider asynchronous event loop using a library that listens to filesystem change notifications provided by the operating system, but consider first if it gives you any real benefits in this particular situation.</p>
| 1 | 2009-07-24T23:24:14Z | [
"python",
"asynchronous",
"freebsd",
"polling"
] |
Using select/poll/kqueue/kevent to watch a directory for new files | 1,165,571 | <p>In my app I need to watch a directory for new files. The amount of traffic is very large and there are going to be a minimum of hundreds of new files per second appearing. Currently I'm using a busy loop with this kind of idea:</p>
<pre><code>while True:
time.sleep(0.2)
if len(os.listdir('.')) > 0:
# do stuff
</code></pre>
<p>After running profiling I'm seeing a lot of time spent in the sleep, and I'm wondering if I should change this to use polling instead. </p>
<p>I'm trying to use one of the available classes in <code>select</code> to poll my directory, but I'm not sure if it actually works, or if I'm just doing it wrong.</p>
<p>I get an fd for my directory with:</p>
<pre><code>fd = os.open('.', os.O_DIRECT)
</code></pre>
<p>I've then tried several methods to see when the directory changes. As an example, one of the things I tried was:</p>
<pre><code>poll = select.poll()
poll.register(fd, select.POLLIN)
poll.poll() # returns (fd, 1) meaning 'ready to read'
os.read(fd, 4096) # prints largely gibberish but i can see that i'm pulling the files/folders contained in the directory at least
poll.poll() # returns (fd, 1) again
os.read(fd, 4096) # empty string - no more data
</code></pre>
<p>Why is poll() acting like there is more information to read? I assumed that it would only do that if something had changed in the directory.</p>
<p>Is what I'm trying to do here even possible?</p>
<p>If not, is there any other better alternative to <code>while True: look for changes</code> ?</p>
| 5 | 2009-07-22T14:13:56Z | 1,458,591 | <p>FreeBSD and thus Mac OS X provide an analog of inotify called kqueue. Type man 2 kqueue on a FreeBSD machine for more information. For kqueue on Freebsd you have PyKQueue available at <a href="http://people.freebsd.org/~dwhite/PyKQueue/">http://people.freebsd.org/~dwhite/PyKQueue/</a>, unfortunately is not actively maintained so your mileage may vary. </p>
| 6 | 2009-09-22T07:24:01Z | [
"python",
"asynchronous",
"freebsd",
"polling"
] |
Using select/poll/kqueue/kevent to watch a directory for new files | 1,165,571 | <p>In my app I need to watch a directory for new files. The amount of traffic is very large and there are going to be a minimum of hundreds of new files per second appearing. Currently I'm using a busy loop with this kind of idea:</p>
<pre><code>while True:
time.sleep(0.2)
if len(os.listdir('.')) > 0:
# do stuff
</code></pre>
<p>After running profiling I'm seeing a lot of time spent in the sleep, and I'm wondering if I should change this to use polling instead. </p>
<p>I'm trying to use one of the available classes in <code>select</code> to poll my directory, but I'm not sure if it actually works, or if I'm just doing it wrong.</p>
<p>I get an fd for my directory with:</p>
<pre><code>fd = os.open('.', os.O_DIRECT)
</code></pre>
<p>I've then tried several methods to see when the directory changes. As an example, one of the things I tried was:</p>
<pre><code>poll = select.poll()
poll.register(fd, select.POLLIN)
poll.poll() # returns (fd, 1) meaning 'ready to read'
os.read(fd, 4096) # prints largely gibberish but i can see that i'm pulling the files/folders contained in the directory at least
poll.poll() # returns (fd, 1) again
os.read(fd, 4096) # empty string - no more data
</code></pre>
<p>Why is poll() acting like there is more information to read? I assumed that it would only do that if something had changed in the directory.</p>
<p>Is what I'm trying to do here even possible?</p>
<p>If not, is there any other better alternative to <code>while True: look for changes</code> ?</p>
| 5 | 2009-07-22T14:13:56Z | 1,459,945 | <p>You might want to have a look at <a href="http://docs.python.org/library/select.html#kqueue-objects" rel="nofollow">select.kqueue</a> - I've not used it but kqueue is the right interface for this under BSD I believe so you can monitor files / directories and be called back when and only when they change</p>
| 0 | 2009-09-22T12:58:52Z | [
"python",
"asynchronous",
"freebsd",
"polling"
] |
Using select/poll/kqueue/kevent to watch a directory for new files | 1,165,571 | <p>In my app I need to watch a directory for new files. The amount of traffic is very large and there are going to be a minimum of hundreds of new files per second appearing. Currently I'm using a busy loop with this kind of idea:</p>
<pre><code>while True:
time.sleep(0.2)
if len(os.listdir('.')) > 0:
# do stuff
</code></pre>
<p>After running profiling I'm seeing a lot of time spent in the sleep, and I'm wondering if I should change this to use polling instead. </p>
<p>I'm trying to use one of the available classes in <code>select</code> to poll my directory, but I'm not sure if it actually works, or if I'm just doing it wrong.</p>
<p>I get an fd for my directory with:</p>
<pre><code>fd = os.open('.', os.O_DIRECT)
</code></pre>
<p>I've then tried several methods to see when the directory changes. As an example, one of the things I tried was:</p>
<pre><code>poll = select.poll()
poll.register(fd, select.POLLIN)
poll.poll() # returns (fd, 1) meaning 'ready to read'
os.read(fd, 4096) # prints largely gibberish but i can see that i'm pulling the files/folders contained in the directory at least
poll.poll() # returns (fd, 1) again
os.read(fd, 4096) # empty string - no more data
</code></pre>
<p>Why is poll() acting like there is more information to read? I assumed that it would only do that if something had changed in the directory.</p>
<p>Is what I'm trying to do here even possible?</p>
<p>If not, is there any other better alternative to <code>while True: look for changes</code> ?</p>
| 5 | 2009-07-22T14:13:56Z | 4,448,422 | <p>I've written a library and a shell tool that should handle this for you.</p>
<p><a href="http://github.com/gorakhargosh/watchdog" rel="nofollow">http://github.com/gorakhargosh/watchdog</a></p>
<p>Although, kqueue is a very heavyweight way to monitor directories
I'd appreciate if you can test and checkout any performance
problems you might encounter. Patches are also welcome. </p>
<p>HTH.</p>
| 0 | 2010-12-15T09:26:56Z | [
"python",
"asynchronous",
"freebsd",
"polling"
] |
Is it safe to track trunk in Django? | 1,165,631 | <p>I'm currently using <code>Django 1.1 beta</code> for some personal projects, and plan to start messing arround with the trunk to see the new stuff under the hood. But I might start using it on a professional basis, and I'd need to know if <code>trunk</code> is stable enough for using in production, or I should stick to 1.0 for mission critical systems.</p>
<h2>Edit</h2>
<p>Putting all the information in answer for correctness.</p>
| 2 | 2009-07-22T14:22:12Z | 1,165,715 | <p>As with the trunk of any software project, it's only as stable as the people commiting things test for. Typically this is probably pretty stable, but you need to be aware that if you get caught with a 'bad' version (which can happen), your site/s just might come down over it temporarily.</p>
| 0 | 2009-07-22T14:32:01Z | [
"python",
"django"
] |
Is it safe to track trunk in Django? | 1,165,631 | <p>I'm currently using <code>Django 1.1 beta</code> for some personal projects, and plan to start messing arround with the trunk to see the new stuff under the hood. But I might start using it on a professional basis, and I'd need to know if <code>trunk</code> is stable enough for using in production, or I should stick to 1.0 for mission critical systems.</p>
<h2>Edit</h2>
<p>Putting all the information in answer for correctness.</p>
| 2 | 2009-07-22T14:22:12Z | 1,165,718 | <p>You probably shouldn't pull Django trunk <em>every</em> day, sometimes there are big commits that might break some things on your site. Also it depends what features you use, the new ones will of cause be a bit more buggy than older features. But all in all there shouldn't be a problem using trunk for production. You just need to be careful when updating to latest revision.</p>
<p>You could for example set up a new virtual environment to test, before updating the live site. There are many ways to do something simelar, but I will let you take your pick. </p>
| 2 | 2009-07-22T14:32:41Z | [
"python",
"django"
] |
Is it safe to track trunk in Django? | 1,165,631 | <p>I'm currently using <code>Django 1.1 beta</code> for some personal projects, and plan to start messing arround with the trunk to see the new stuff under the hood. But I might start using it on a professional basis, and I'd need to know if <code>trunk</code> is stable enough for using in production, or I should stick to 1.0 for mission critical systems.</p>
<h2>Edit</h2>
<p>Putting all the information in answer for correctness.</p>
| 2 | 2009-07-22T14:22:12Z | 1,185,666 | <p>I think you've done a good job of gathering the right links in the question. The only links I would add are:</p>
<ul>
<li><a href="http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges" rel="nofollow">http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges</a></li>
<li><a href="http://code.djangoproject.com/wiki/FutureBackwardsIncompatibleChanges" rel="nofollow">http://code.djangoproject.com/wiki/FutureBackwardsIncompatibleChanges</a></li>
</ul>
<p>The first is for anyone still on a pre 1.0 release and wondering about the upgrade path, even to the trunk. The second is a work in progress it seems, and may be updated as things progress toward the 2.0 release.</p>
| 1 | 2009-07-26T21:55:39Z | [
"python",
"django"
] |
Is it safe to track trunk in Django? | 1,165,631 | <p>I'm currently using <code>Django 1.1 beta</code> for some personal projects, and plan to start messing arround with the trunk to see the new stuff under the hood. But I might start using it on a professional basis, and I'd need to know if <code>trunk</code> is stable enough for using in production, or I should stick to 1.0 for mission critical systems.</p>
<h2>Edit</h2>
<p>Putting all the information in answer for correctness.</p>
| 2 | 2009-07-22T14:22:12Z | 1,249,054 | <p>First, <a href="http://docs.djangoproject.com/en/dev/releases/1.1-rc-1/" rel="nofollow">Django 1.1</a> is <a href="http://www.djangoproject.com/weblog/2009/jul/21/rc/" rel="nofollow">one step closer to being released</a>, as <a href="http://www.djangoproject.com/download/" rel="nofollow">RC1 is available for download</a>.</p>
<p>With that out of the way, I've found some useful things.</p>
<ul>
<li>If you are planning following this project, you should keep an eye in the <a href="http://docs.djangoproject.com/en/dev/internals/deprecation/#internals-deprecation" rel="nofollow">Django deprecation timeline</a>, along the <a href="http://docs.djangoproject.com/en/dev/internals/release-process/#internal-release-deprecation-policy" rel="nofollow">Django deprecation policy</a>.</li>
<li>Another important place to look, is the <a href="http://docs.djangoproject.com/en/dev/misc/api-stability/#misc-api-stability" rel="nofollow">API Stability</a> page of <a href="http://docs.djangoproject.com/" rel="nofollow">the documentation</a>.</li>
<li>Keep an eye on the <a href="http://groups.google.com/group/django-users" rel="nofollow">django-users mailing list</a>, as well as the <a href="http://groups.google.com/group/django-developers" rel="nofollow">django-developer mailing list</a>.</li>
</ul>
<p>Am I missing something I should be looking too?</p>
<h2>Edit</h2>
<p><a href="http://www.djangoproject.com/weblog/2009/jul/29/1-point-1/" rel="nofollow" title="Django weblog: Django 1.1 released">Django 1.1 was released</a>!!! You can <a href="http://www.djangoproject.com/download/1.1/tarball/" rel="nofollow" title="Download Django 1.1 tarball">download it <strong>right now</strong></a>! :)</p>
<p>The question remains if <code>trunk</code> following is not recommended (once upon a time, <em>Django didn't have releases</em>, you only had <code>head</code> of <code>trunk</code>)</p>
<hr>
<p>Acording to the tech team at <a href="http://www.theonion.com" rel="nofollow">The Onion</a>, which <a href="http://www.reddit.com/r/django/comments/bhvhz/the_onion_uses_django_and_why_it_matters_to_us/" rel="nofollow">has migrated from Drupal to Django</a>, <a href="http://www.reddit.com/r/django/comments/bhvhz/the_onion_uses_django_and_why_it_matters_to_us/c0mv32r" rel="nofollow">Django trunk is extremely stable</a>.</p>
| 0 | 2009-08-08T14:39:57Z | [
"python",
"django"
] |
Is it safe to track trunk in Django? | 1,165,631 | <p>I'm currently using <code>Django 1.1 beta</code> for some personal projects, and plan to start messing arround with the trunk to see the new stuff under the hood. But I might start using it on a professional basis, and I'd need to know if <code>trunk</code> is stable enough for using in production, or I should stick to 1.0 for mission critical systems.</p>
<h2>Edit</h2>
<p>Putting all the information in answer for correctness.</p>
| 2 | 2009-07-22T14:22:12Z | 1,249,509 | <p>For what it's worth, I've read in multiple places (in the documentation here: <a href="http://www.djangoproject.com/download/" rel="nofollow">http://www.djangoproject.com/download/</a> (see the side bar) and from the project's lead developers in a book of theirs) that it's fine to use the trunk. Many of their own developers use trunk for their sites and so they have incentive to keep it stable.</p>
<p>Recently, however, they mentioned that the 1.1 RC along with any other pre-release packages should not be used for production ( <a href="http://www.djangoproject.com/weblog/2009/jul/21/rc/" rel="nofollow">http://www.djangoproject.com/weblog/2009/jul/21/rc/</a> ) so the signals are somewhat mixed.</p>
<p>That said, my personal feeling is that the trunk is very stable most of the time but as with any code you haven't used before you should run it through its paces before deploying anything.</p>
<p>As the other posters said though: the choice is ultimately yours to make based on your best judgement.</p>
| 0 | 2009-08-08T18:02:30Z | [
"python",
"django"
] |
Including current date in python logging file | 1,165,856 | <p>I have a process that I run every day. It uses Python logging. How would I configure the python logging module to write to a file containing the current date in the file name?</p>
<p>Because I restart the process every morning the TimedRotatingFileHandler won't work. The project is larger, so I would be interested in keeping the code required for logging into a logging configuration file.</p>
| 2 | 2009-07-22T14:50:32Z | 1,165,912 | <p>You may be interested in the TimedRotatingFileHandler see <a href="http://docs.python.org/library/logging.html#logging.handlers.TimedRotatingFileHandler" rel="nofollow">http://docs.python.org/library/logging.html#logging.handlers.TimedRotatingFileHandler</a></p>
| 0 | 2009-07-22T14:56:06Z | [
"python",
"logging"
] |
Including current date in python logging file | 1,165,856 | <p>I have a process that I run every day. It uses Python logging. How would I configure the python logging module to write to a file containing the current date in the file name?</p>
<p>Because I restart the process every morning the TimedRotatingFileHandler won't work. The project is larger, so I would be interested in keeping the code required for logging into a logging configuration file.</p>
| 2 | 2009-07-22T14:50:32Z | 1,165,931 | <p>You can use the <a href="http://docs.python.org/2/library/logging.handlers.html#timedrotatingfilehandler" rel="nofollow">TimedRotatingFileHandler</a>. For example:</p>
<pre><code>import logging
import logging.handlers
LOG_FILENAME = '/tmp/log'
# Set up a specific logger with our desired output level
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when='D')
log.addHandler(handler)
</code></pre>
<p>But this will probably only work if your program runs for more than one day. If your script starts daily in a cron job you're better off manually formatting the filename which you pass to your log handler to include a timestamp.</p>
| 8 | 2009-07-22T14:59:47Z | [
"python",
"logging"
] |
How to strip decorators from a function in python | 1,166,118 | <p>Let's say I have the following:</p>
<pre><code>def with_connection(f):
def decorated(*args, **kwargs):
f(get_connection(...), *args, **kwargs)
return decorated
@with_connection
def spam(connection):
# Do something
</code></pre>
<p>I want to test the <code>spam</code> function without going through the hassle of setting up a connection (or whatever the decorator is doing).</p>
<p>Given <code>spam</code>, how do I strip the decorator from it and get the underlying "undecorated" function?</p>
| 34 | 2009-07-22T15:29:41Z | 1,166,200 | <p>In the general case, you can't, because</p>
<pre><code>@with_connection
def spam(connection):
# Do something
</code></pre>
<p>is equivalent to</p>
<pre><code>def spam(connection):
# Do something
spam = with_connection(spam)
</code></pre>
<p>which means that the "original" spam might not even exist anymore. A (not too pretty) hack would be this:</p>
<pre><code>def with_connection(f):
def decorated(*args, **kwargs):
f(get_connection(...), *args, **kwargs)
decorated._original = f
return decorated
@with_connection
def spam(connection):
# Do something
spam._original(testcon) # calls the undecorated function
</code></pre>
| 23 | 2009-07-22T15:42:28Z | [
"python",
"decorator"
] |
How to strip decorators from a function in python | 1,166,118 | <p>Let's say I have the following:</p>
<pre><code>def with_connection(f):
def decorated(*args, **kwargs):
f(get_connection(...), *args, **kwargs)
return decorated
@with_connection
def spam(connection):
# Do something
</code></pre>
<p>I want to test the <code>spam</code> function without going through the hassle of setting up a connection (or whatever the decorator is doing).</p>
<p>Given <code>spam</code>, how do I strip the decorator from it and get the underlying "undecorated" function?</p>
| 34 | 2009-07-22T15:29:41Z | 1,166,227 | <p>Behold, FuglyHackThatWillWorkForYourExampleButICantPromiseAnythingElse:</p>
<pre><code> orig_spam = spam.func_closure[0].cell_contents
</code></pre>
<p><strong>Edit</strong>: For functions/methods decorated more than once and with more complicated decorators you can try using the following code. It relies on the fact, that decorated functions are __name__d differently than the original function.</p>
<pre><code>def search_for_orig(decorated, orig_name):
for obj in (c.cell_contents for c in decorated.__closure__):
if hasattr(obj, "__name__") and obj.__name__ == orig_name:
return obj
if hasattr(obj, "__closure__") and obj.__closure__:
found = search_for_orig(obj, orig_name)
if found:
return found
return None
>>> search_for_orig(spam, "spam")
<function spam at 0x027ACD70>
</code></pre>
<p>It's not fool proof though. It will fail if the name of the function returned from a decorator is the same as the decorated one. The order of hasattr() checks is also a heuristic, there are decoration chains that return wrong results in any case.</p>
| 12 | 2009-07-22T15:45:22Z | [
"python",
"decorator"
] |
How to strip decorators from a function in python | 1,166,118 | <p>Let's say I have the following:</p>
<pre><code>def with_connection(f):
def decorated(*args, **kwargs):
f(get_connection(...), *args, **kwargs)
return decorated
@with_connection
def spam(connection):
# Do something
</code></pre>
<p>I want to test the <code>spam</code> function without going through the hassle of setting up a connection (or whatever the decorator is doing).</p>
<p>Given <code>spam</code>, how do I strip the decorator from it and get the underlying "undecorated" function?</p>
| 34 | 2009-07-22T15:29:41Z | 1,167,248 | <p>balpha's solution can be made more generalizable with this meta-decorator:</p>
<pre><code>def include_original(dec):
def meta_decorator(f):
decorated = dec(f)
decorated._original = f
return decorated
return meta_decorator
</code></pre>
<p>Then you can decorate your decorators with @include_original, and every one will have a testable (undecorated) version tucked away inside it.</p>
<pre><code>@include_original
def shout(f):
def _():
string = f()
return string.upper()
@shout
def function():
return "hello world"
>>> print function()
HELLO_WORLD
>>> print function._original()
hello world
</code></pre>
| 22 | 2009-07-22T18:31:07Z | [
"python",
"decorator"
] |
How to strip decorators from a function in python | 1,166,118 | <p>Let's say I have the following:</p>
<pre><code>def with_connection(f):
def decorated(*args, **kwargs):
f(get_connection(...), *args, **kwargs)
return decorated
@with_connection
def spam(connection):
# Do something
</code></pre>
<p>I want to test the <code>spam</code> function without going through the hassle of setting up a connection (or whatever the decorator is doing).</p>
<p>Given <code>spam</code>, how do I strip the decorator from it and get the underlying "undecorated" function?</p>
| 34 | 2009-07-22T15:29:41Z | 1,168,448 | <p>The usual approach to testing such functions is to make any dependencies, such as get_connection, configurable. Then you can override it with a mock while testing. Basically the same as dependency injection in the Java world but a lot simpler thanks to Pythons dynamic nature.</p>
<p>Code for it might look something like this:</p>
<pre><code># decorator definition
def with_connection(f):
def decorated(*args, **kwargs):
f(with_connection.connection_getter(), *args, **kwargs)
return decorated
# normal configuration
with_connection.connection_getter = lambda: get_connection(...)
# inside testsuite setup override it
with_connection.connection_getter = lambda: "a mock connection"
</code></pre>
<p>Depending on your code you could find a better object than the decorator to stick the factory function on. The issue with having it on the decorator is that you'd have to remember to restore it to the old value in the teardown method.</p>
| 2 | 2009-07-22T21:43:04Z | [
"python",
"decorator"
] |
How to strip decorators from a function in python | 1,166,118 | <p>Let's say I have the following:</p>
<pre><code>def with_connection(f):
def decorated(*args, **kwargs):
f(get_connection(...), *args, **kwargs)
return decorated
@with_connection
def spam(connection):
# Do something
</code></pre>
<p>I want to test the <code>spam</code> function without going through the hassle of setting up a connection (or whatever the decorator is doing).</p>
<p>Given <code>spam</code>, how do I strip the decorator from it and get the underlying "undecorated" function?</p>
| 34 | 2009-07-22T15:29:41Z | 1,169,178 | <p>Instead of doing..</p>
<pre><code>def with_connection(f):
def decorated(*args, **kwargs):
f(get_connection(...), *args, **kwargs)
return decorated
@with_connection
def spam(connection):
# Do something
orig_spam = magic_hack_of_a_function(spam)
</code></pre>
<p>You could just do..</p>
<pre><code>def with_connection(f):
....
def spam_f(connection):
...
spam = with_connection(spam_f)
</code></pre>
<p>..which is all the <code>@decorator</code> syntax does - you can then obviously access the original <code>spam_f</code> normally</p>
| 5 | 2009-07-23T01:51:05Z | [
"python",
"decorator"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.