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
Python Win32 - equivalent function to DriveInfo.IsReady
1,290,515
<p>I'm trying to find an equivalent Python function to the Windows function <a href="http://msdn.microsoft.com/en-us/library/system.io.driveinfo.isready.aspx" rel="nofollow">DriveInfo.IsReady</a>. I've spent a while searching through the functions provided by win32api and win32file but I can't find anything (though perhaps that's because I didn't manage to find much useful documentation online, so was simply searching through the listing of functions).</p> <p>Any help would be gratefully received.</p>
1
2009-08-17T21:19:06Z
1,290,729
<p>I've used <code>GetVolumeInformation</code> in the past to determine this. For example, something like:</p> <pre><code>def is_drive_ready(drive_name): try: win32api.GetVolumeInformation(drive_name) return True except: return False print 'ready:', is_drive_ready('c:\\') # true print 'ready:', is_drive_ready('d:\\') # false (on my system) </code></pre> <p>You'll need the <a href="http://sourceforge.net/projects/pywin32/files/" rel="nofollow">win32api</a> module.</p>
1
2009-08-17T22:02:27Z
[ "python", "winapi" ]
UnicodeDecodeError when using socket.gethostname() result
1,290,601
<p>Some of my users report that the following code may raise a UnicodeDecodeError when the hostname contains non-ascii characters (however I haven't been able to replicate this on my Windows Vista machine):</p> <pre><code> self.path = path self.lock_file = os.path.abspath(path) + ".lock" self.hostname = socket.gethostname() self.pid = os.getpid() dirname = os.path.dirname(self.lock_file) self.unique_name = os.path.join(dirname, "%s.%s" % (self.hostname, self.pid)) </code></pre> <p>The last part of the traceback is:</p> <pre><code> File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 537, in FileLock File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 296, in __init__ File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 175, in __init__ File "ntpath.pyo", line 102, in join UnicodeDecodeError: 'ascii' codec can't decode byte 0xcf in position 7: ordinal not in range(128) </code></pre> <p>Any ideas on why and how to prevent it? </p> <p>(The exception occurs with Python 2.5 on Windows XP)</p>
1
2009-08-17T21:36:53Z
1,290,675
<p>Yes, if either the hostname or the dirname is a unicode string, it is likely to give you that error. The best solution is typically to make sure both are unicode, and not just one of them.</p>
0
2009-08-17T21:50:43Z
[ "python", "unicode" ]
UnicodeDecodeError when using socket.gethostname() result
1,290,601
<p>Some of my users report that the following code may raise a UnicodeDecodeError when the hostname contains non-ascii characters (however I haven't been able to replicate this on my Windows Vista machine):</p> <pre><code> self.path = path self.lock_file = os.path.abspath(path) + ".lock" self.hostname = socket.gethostname() self.pid = os.getpid() dirname = os.path.dirname(self.lock_file) self.unique_name = os.path.join(dirname, "%s.%s" % (self.hostname, self.pid)) </code></pre> <p>The last part of the traceback is:</p> <pre><code> File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 537, in FileLock File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 296, in __init__ File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 175, in __init__ File "ntpath.pyo", line 102, in join UnicodeDecodeError: 'ascii' codec can't decode byte 0xcf in position 7: ordinal not in range(128) </code></pre> <p>Any ideas on why and how to prevent it? </p> <p>(The exception occurs with Python 2.5 on Windows XP)</p>
1
2009-08-17T21:36:53Z
1,291,186
<p>You want a unique string based on the hostname, but it's got Unicode characters in it. There are a variety of ways to reduce a Unicode string to an ascii string, depending on how you want to deal with non-ascii characters. Here's one:</p> <pre><code>self.hostname = socket.gethostname().encode('ascii', 'replace').replace('?', '_') </code></pre> <p>This will replace all non-ascii characters with a question mark, then change those to underscore (since file systems don't like questions marks in file names).</p>
0
2009-08-18T00:23:40Z
[ "python", "unicode" ]
UnicodeDecodeError when using socket.gethostname() result
1,290,601
<p>Some of my users report that the following code may raise a UnicodeDecodeError when the hostname contains non-ascii characters (however I haven't been able to replicate this on my Windows Vista machine):</p> <pre><code> self.path = path self.lock_file = os.path.abspath(path) + ".lock" self.hostname = socket.gethostname() self.pid = os.getpid() dirname = os.path.dirname(self.lock_file) self.unique_name = os.path.join(dirname, "%s.%s" % (self.hostname, self.pid)) </code></pre> <p>The last part of the traceback is:</p> <pre><code> File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 537, in FileLock File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 296, in __init__ File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 175, in __init__ File "ntpath.pyo", line 102, in join UnicodeDecodeError: 'ascii' codec can't decode byte 0xcf in position 7: ordinal not in range(128) </code></pre> <p>Any ideas on why and how to prevent it? </p> <p>(The exception occurs with Python 2.5 on Windows XP)</p>
1
2009-08-17T21:36:53Z
1,292,026
<p>I don't think that there is a problem with the actual code that you've posted, even if <code>socket.gethostname()</code> returns a unicode object. There will be a problem when you attempt to use <code>name</code> such that it is converted to a string first:</p> <pre><code>import os hostname = u'\u1306blah' pid = os.getpid() name = os.path.join(os.path.dirname('/tmp/blah.lock'), "%s.%s" % (hostname, pid)) &gt;&gt;&gt; type(name) &lt;type 'unicode'&gt; &gt;&gt;&gt; name u'/tmp/\u1306blah.28292' &gt;&gt;&gt; print name /tmp/ጆblah.29032 &gt;&gt;&gt; str(name) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode character u'\u1306' in position 5: ordinal not in range(128) </code></pre> <p>You can see that <code>str(name)</code> raises the exception that you're seeing, but everything looks OK up until that point. What are you doing with <code>name</code> once you've constructed it?</p>
0
2009-08-18T05:47:35Z
[ "python", "unicode" ]
UnicodeDecodeError when using socket.gethostname() result
1,290,601
<p>Some of my users report that the following code may raise a UnicodeDecodeError when the hostname contains non-ascii characters (however I haven't been able to replicate this on my Windows Vista machine):</p> <pre><code> self.path = path self.lock_file = os.path.abspath(path) + ".lock" self.hostname = socket.gethostname() self.pid = os.getpid() dirname = os.path.dirname(self.lock_file) self.unique_name = os.path.join(dirname, "%s.%s" % (self.hostname, self.pid)) </code></pre> <p>The last part of the traceback is:</p> <pre><code> File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 537, in FileLock File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 296, in __init__ File "taskcoachlib\thirdparty\lockfile\lockfile.pyo", line 175, in __init__ File "ntpath.pyo", line 102, in join UnicodeDecodeError: 'ascii' codec can't decode byte 0xcf in position 7: ordinal not in range(128) </code></pre> <p>Any ideas on why and how to prevent it? </p> <p>(The exception occurs with Python 2.5 on Windows XP)</p>
1
2009-08-17T21:36:53Z
1,762,626
<p>I don't think gethostname() is necessarily giving you a unicode object. It could be the directory name of lockfile. Regardless, one of them is a standard string with a non-ASCII (higher than 127) char in it and the other is a unicode string.</p> <p>The problem is that the join function in the ntpath module (the module Python uses for os.path on Windows) attempts join the arguments given. This causes Python to try to convert the normal string parts to unicode. In your case the non-unicode string appears to have a non-ASCII character. This can't be reliably converted to unicode, so Python raises the exception.</p> <p>A simpler way to trigger the problem:</p> <pre><code>&gt;&gt; from ntpath import join &gt;&gt; join(u'abc', '\xff') --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) /home/msmits/&lt;ipython console&gt; in &lt;module&gt;() /usr/lib64/python2.6/ntpath.pyc in join(a, *p) 106 path += b 107 else: --&gt; 108 path += "\\" + b 109 else: 110 # path is not empty and does not end with a backslash, </code></pre> <p>The traceback shows the problem line in ntpath.py.</p> <p>You could work around this by using converting the args to join() to standard strings first as other answers suggest. Alternatively you could convert everything to unicode first. If a specific encoding is given to decode() high bytes can be converted to unicode.</p> <p>For example:</p> <pre><code>&gt;&gt; '\xff'.decode('latin-1') u'\xff' </code></pre>
1
2009-11-19T11:20:23Z
[ "python", "unicode" ]
Running a python script from the command line in Windows
1,290,659
<p>I'm trying to run <a href="http://furius.ca/snakefood/" rel="nofollow">SnakeFood</a>, to analyze a python project. I'm on a Windows machine and so far I've been able to figure out how to:</p> <ul> <li>install Tortoise for Mercurial to download the SnakeFood code from the site</li> <li>set the windows Path to accept python from the command prompt so I could do <code>python setup.py install</code> and got snakefood to go into my "site-packages" folder</li> </ul> <p>Now, the documentation doesn't say anything else rather than: <code>sfood /path/to/my/project</code></p> <p>I can't get this command to work. What am I missing?</p>
4
2009-08-17T21:47:51Z
1,290,677
<p>Would this work?</p> <pre><code>python "DriveLetter:\path\to\sfood.py" "DriveLetter:\path\to\your\project" </code></pre>
4
2009-08-17T21:51:22Z
[ "python", "windows" ]
Running a python script from the command line in Windows
1,290,659
<p>I'm trying to run <a href="http://furius.ca/snakefood/" rel="nofollow">SnakeFood</a>, to analyze a python project. I'm on a Windows machine and so far I've been able to figure out how to:</p> <ul> <li>install Tortoise for Mercurial to download the SnakeFood code from the site</li> <li>set the windows Path to accept python from the command prompt so I could do <code>python setup.py install</code> and got snakefood to go into my "site-packages" folder</li> </ul> <p>Now, the documentation doesn't say anything else rather than: <code>sfood /path/to/my/project</code></p> <p>I can't get this command to work. What am I missing?</p>
4
2009-08-17T21:47:51Z
1,290,678
<p>Considering the documentation says "sfood /path/to/my/project" it most likely assumes a *nix environment. That leads me to the assumption that sfood probably has a shebang line.</p> <p>On Windows you probably need to use "python sfood ". If "sfood" isn't in your PATH, you'll need to write the full path rather than just "sfood".</p>
1
2009-08-17T21:51:27Z
[ "python", "windows" ]
Running a python script from the command line in Windows
1,290,659
<p>I'm trying to run <a href="http://furius.ca/snakefood/" rel="nofollow">SnakeFood</a>, to analyze a python project. I'm on a Windows machine and so far I've been able to figure out how to:</p> <ul> <li>install Tortoise for Mercurial to download the SnakeFood code from the site</li> <li>set the windows Path to accept python from the command prompt so I could do <code>python setup.py install</code> and got snakefood to go into my "site-packages" folder</li> </ul> <p>Now, the documentation doesn't say anything else rather than: <code>sfood /path/to/my/project</code></p> <p>I can't get this command to work. What am I missing?</p>
4
2009-08-17T21:47:51Z
19,482,391
<p>I was able to resolve this issue, on my Windows 7 machine with Python 2.7.3 installed, like so:</p> <pre><code>C:\&gt; cd \path\to\snakefood\installation\folder C:\path\to\snakefood\installation\folder&gt; python setup.py install ... C:\path\to\snakefood\installation\folder&gt; cd C:\Python27\Scripts C:\Python27\Scripts&gt; python sfood \path\to\my\project ... </code></pre>
1
2013-10-20T20:19:38Z
[ "python", "windows" ]
list of duplicate dictionaries copy single entry to another list
1,290,717
<p>newbie question again.</p> <p>Let's say i have a list of nested dictionaries.</p> <pre><code>a = [{"value1": 1234, "value2": 23423423421, "value3": norway, "value4": charlie}, {"value1": 1398, "value2": 23423412221, "value3": england, "value4": alpha}, {"value1": 1234, "value2": 23234231221, "value3": norway, "value4": charlie}, {"value1": 1398, "value2": 23423213121, "value3": england, "value4": alpha}] </code></pre> <p>What i want is to move a singularis entry of each duplicate where value1, value3 and value4 matches. The result should be looking like this:</p> <pre><code>b = [{"value1": 1398, "value2": 23423412221, "value3": england, "value4": alpha}, {"value1": 1234, "value2": 23234231221, "value3": norway, "value4": charlie}] </code></pre> <p>The orginal list, a, should remain in it's orginal state.</p>
1
2009-08-17T21:59:35Z
1,290,758
<p>There was a similar question on this recently. Try this <a href="http://stackoverflow.com/questions/1279805/remove-duplicates-from-nested-dictionaries-in-list">entry</a>.</p> <p>In fact, you asked that question: "Let's say there exists multiple entries where value3 and value4 are identical to other nested dictionaries. How can i quick and easy find and remove those duplicate dictionaries."</p> <p>It sounds like the same thing, right?</p> <p>Edit: liberally stealing Alex's code, it looks something like this:</p> <pre><code>import itertools import pprint import operator alpha, charlie, norway, england = range(4) a = [{"value1": 1234, "value2": 23423423421, "value3": norway, "value4": charlie}, {"value1": 1398, "value2": 23423412221, "value3": england, "value4": alpha}, {"value1": 1234, "value2": 23234231221, "value3": norway, "value4": charlie}, {"value1": 1398, "value2": 23423213121, "value3": england, "value4": alpha}] getvals = operator.itemgetter('value1', 'value3', 'value4') a.sort(key=getvals) b = [g.next() for _, g in itertools.groupby(a, getvals)] pprint.pprint(b) </code></pre> <p>And the result is:</p> <pre><code>[{'value1': 1234, 'value2': 23423423421L, 'value3': 2, 'value4': 1}, {'value1': 1398, 'value2': 23423412221L, 'value3': 3, 'value4': 0}] </code></pre>
2
2009-08-17T22:08:29Z
[ "python", "dictionary", "list" ]
scrollbar for statictext in wxpython?
1,290,736
<p>is possible to add a scrollbar to a statictext in wxpython?</p> <p>the thing is that i'm creating this statictext:</p> <pre><code>self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1,label=u'some text here',name='staticText1', parent=self.panel1, pos=wx.Point(16, 96), size=wx.Size(408, 216),style=wx.ST_NO_AUTORESIZE | wx.THICK_FRAME | wx.ALIGN_CENTRE | wx.SUNKEN_BORDER) self.staticText1.SetBackgroundColour(wx.Colour(255, 255, 255)) self.staticText1.SetBackgroundStyle(wx.BG_STYLE_SYSTEM) self.staticText1.SetFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD, False,u'MS Shell Dlg 2')) self.staticText1.SetAutoLayout(True) self.staticText1.SetConstraints(LayoutAnchors(self.staticText1, False,True, True, False)) self.staticText1.SetHelpText(u'') </code></pre> <p>but later i use StaticText.SetLabel to change the label and the new text is too big to fit the window, so i need to add a scrollbar to the statictext..</p> <p>i tried adding wx.VSCROLL to the style, and the scrollbar show up but cant scroll down to see the rest of the text..</p>
1
2009-08-17T22:03:43Z
1,291,608
<p><code>wx.StaticText</code> is designed to never respond to mouse events and never take user focus. Given that this is its role in life, it seems that a scrollbar would be inconsistent with its purpose.</p> <p>There are two ways to get what you want: <strong>1)</strong> You could use a regular <code>TextCtrl</code> with the style TE_READONLY (see <a href="http://stackoverflow.com/questions/1254819/non-editable-text-box-in-wxpython">here</a>); or <strong>2)</strong> you could make a scrolled window that contains your <code>StaticText</code> control.</p>
4
2009-08-18T03:16:16Z
[ "python", "wxpython", "scrollbar" ]
IsPointInsideSegment(pt, line) in Python
1,290,779
<p>Is there a nice way to determine if a point lies within a 3D line segment?</p> <p>I know there are algorithms that determine the distance between a point and line segment, but I'm wondering if there's something more compact or efficient.</p>
1
2009-08-17T22:13:55Z
1,290,858
<p>First, find the distance from the point to the line. If the distance from the point to the line is zero, then it's on the line.</p>
0
2009-08-17T22:35:44Z
[ "python", "geometry" ]
IsPointInsideSegment(pt, line) in Python
1,290,779
<p>Is there a nice way to determine if a point lies within a 3D line segment?</p> <p>I know there are algorithms that determine the distance between a point and line segment, but I'm wondering if there's something more compact or efficient.</p>
1
2009-08-17T22:13:55Z
1,290,934
<p>Given three points A, B, and C -- where AB is your line and C is your other point, you can also restate your problem as two lines, AB and AC. If the angle between AB and AC is zero (i.e. if the area of the triangle ABC is zero) then your point C is on the line.</p> <p>If you think about this in terms of angles, you can use the <a href="http://en.wikipedia.org/wiki/Dot%5Fproduct" rel="nofollow">dot product</a> of the two vectors (AB and AC) to find the angle between them. Some quick googling turns up a couple of useful links:</p> <ul> <li><a href="http://knol.google.com/k/koen-samyn/dot-product-cross-product-in-3d/2lijysgth48w1/10#" rel="nofollow">http://knol.google.com/k/koen-samyn/dot-product-cross-product-in-3d/2lijysgth48w1/10#</a></li> <li><a href="http://www.jtaylor1142001.net/calcjat/Solutions/VDotProduct/VDPTheta3D.htm" rel="nofollow">http://www.jtaylor1142001.net/calcjat/Solutions/VDotProduct/VDPTheta3D.htm</a></li> </ul> <p>The bonus of this method is that it's easy to define tolerances in terms of angles; e.g. you may want to consider any point that falls within 5 degrees of the line to be "on the line" even though there is strictly some distance between the line and the point. Depending on your application, this may be more useful than an actual linear measurement.</p>
4
2009-08-17T22:52:38Z
[ "python", "geometry" ]
IsPointInsideSegment(pt, line) in Python
1,290,779
<p>Is there a nice way to determine if a point lies within a 3D line segment?</p> <p>I know there are algorithms that determine the distance between a point and line segment, but I'm wondering if there's something more compact or efficient.</p>
1
2009-08-17T22:13:55Z
1,291,118
<p>One way to restate your question is to ask of the point is a solution to the equation which contains the line segment in question, and (if so) if it lies between the end points of the segment.</p> <p>Since you don't describe the details of how you're representing your line segments and don't mention any modules or libraries that you're using I guess you'd have to code up the algebra yourself. (It's not trivial and my algebra is too rusty in any event).</p> <p>You might consider looking at a library that does the work for you (either to incorporate into your project or to study its code). In this case I'd take a close look at:</p> <ul> <li>[PyEuclid]: <a href="http://code.google.com/p/pyeuclid/" rel="nofollow">http://code.google.com/p/pyeuclid/</a></li> </ul> <p>... claims to be compatible with PyGame and supports objects for 2D and 3D vectors, rays, segments, and circles/spheres. Basically if the distance between your point and your segment is less than <i>epsilon</i> (some threshold appropriate to your calculations) then you treat that as an intersection.</p> <p>(Although it doesn't explicitly say so in the docs that I read, I'm guessing that they must handle floating point rounding issues in their code somewhere. All of PyEuclid seems to be in a single 2200+ line .py file).</p>
1
2009-08-18T00:01:36Z
[ "python", "geometry" ]
Can I store objects in Python class members?
1,290,798
<p>I'm writing a game in Python with the Pygame2 multimedia library, but I'm more accustomed to developing games with ActionScript 3. In AS3, I don't think it was possible to store an object in a static variable, because static variables were initialized before objects could be instantiated. </p> <p>However, in Python, I'm not sure if this holds true. Can I store an object instance in a Python class variable? When will it be instantiated? Will one be instantiated per class or per instance?</p> <pre><code>class Test: counter = Counter() # A class variable counts its instantiations def __init__(self): counter.count() # A method that prints the number of instances of Counter test1 = Test() # Prints 1 test2 = Test() # Prints 1? 2? </code></pre>
0
2009-08-17T22:19:47Z
1,290,827
<p>You can do this:</p> <pre><code>class Test: counter = 0 def __init__(self): Test.counter += 1 print Test.counter </code></pre> <p>And it works as expected.</p>
3
2009-08-17T22:28:30Z
[ "python", "actionscript-3", "pygame", "instantiation" ]
Can I store objects in Python class members?
1,290,798
<p>I'm writing a game in Python with the Pygame2 multimedia library, but I'm more accustomed to developing games with ActionScript 3. In AS3, I don't think it was possible to store an object in a static variable, because static variables were initialized before objects could be instantiated. </p> <p>However, in Python, I'm not sure if this holds true. Can I store an object instance in a Python class variable? When will it be instantiated? Will one be instantiated per class or per instance?</p> <pre><code>class Test: counter = Counter() # A class variable counts its instantiations def __init__(self): counter.count() # A method that prints the number of instances of Counter test1 = Test() # Prints 1 test2 = Test() # Prints 1? 2? </code></pre>
0
2009-08-17T22:19:47Z
1,290,903
<p>Yes.<br> As with most python try it and see.</p> <p>It will be instantiated when a Test object is created. ie your assignment to test1<br> The counter object is created per class</p> <p>Run the following to see (to access the class variable you need the self</p> <pre><code>class Counter: def __init__(self): self.c = 0 def count(self): self.c += 1 print 'in count() value is ' , self.c return self.c class Test: counter = Counter() # A class variable counts its instantiations print 'in class Test' def __init__(self): print 'in Testinit' self.counter.count() # A method that prints the number of instances of Counter test1 = Test() # Prints 1 test2 = Test() </code></pre>
2
2009-08-17T22:43:36Z
[ "python", "actionscript-3", "pygame", "instantiation" ]
Can't get Beaker sessions to work (KeyError)
1,290,840
<p>I'm a newb to the Python world and am having the dangest time with getting sessions to work in my web frameworks. I've tried getting Beaker sessions to work with the webpy framework and the Juno framework. And in both frameworks I always get a KeyError when I try to start the session.</p> <p>Here is the error message in webpy (its pretty much the exact same thing when I try to use beaker sessions in Juno too)...</p> <p>ERROR</p> <pre><code>&lt;type 'exceptions.KeyError'&gt; at / 'beaker.session' Python /Users/tyler/Dropbox/Code/sites/webpy1/code.py in GET, line 15 Web GET http://localhost:1234/ 15. session = web.ctx.environ['beaker.session'] </code></pre> <p>CODE</p> <pre><code>import web import beaker.session from beaker.middleware import SessionMiddleware urls = ( '/', 'index' ) class index: def GET(self): session = web.ctx.environ['beaker.session'] return "hello" app = web.application(urls, globals()) if __name__ == "__main__": app.run() </code></pre>
0
2009-08-17T22:30:26Z
1,295,549
<p>You haven't created the session object yet, so you can't find it in the environment (the <code>KeyError</code> simply means "<code>beaker.session</code> is not in this dictionary").</p> <p>Note that I don't know either webpy nor beaker very well, so I can't give you deeper advice, but from what I understand from the docs and source this should get you started:</p> <pre><code>if __name__ == "__main__": app.run(SessionMiddleware) </code></pre>
2
2009-08-18T18:04:53Z
[ "python", "django", "session", "web.py" ]
Django MVC pattern for non database driven models?
1,290,891
<p>I'm just working my way through Django, and really liking it so far, but I have an issue and I'm not sure what the typical way to solve it.</p> <p>Suppose I have a View which is supposed to be updated when some complex Python object is updated, but this object is not driven by the database, say it is driven by AJAX calls or directly by the user or something.</p> <p>Where does this code go? Should it still go in models.py????</p>
20
2009-08-17T22:40:35Z
1,290,978
<p>Your <code>models.py</code> can be (and sometimes is) empty. You are not obligated to have a model which maps to a database. </p> <p>You should still have a <code>models.py</code> file, to make Django's admin happy. The <code>models.py</code> file name is important, and it's easier to have an empty file than to try and change the file expected by various admin commands.</p> <p>The "model" -- in general -- does not have to map to a database. The "model" -- as a general component of MVC design -- can be anything.</p> <p>You can -- and often do -- define your own "model" module that your views use. <strong>Just don't call it <code>models.py</code> because it will confuse Django admin.</strong> Call it something meaningful to your application: <code>foo.py</code>. This <code>foo.py</code> manipulates the real things that underpin your application -- not necessarily a Django <code>Model.model</code> subclass.</p> <p>Django MVC does not require a database mapping. <strong>It does explicitly expect that the module named <code>models.py</code> has a database mapping in it.</strong> So, use an empty <code>models.py</code> if you have no actual database mapping.</p> <p>Your <code>views.py</code> can use</p> <pre><code>import foo def index( request ): objects = foo.somelistofobjects() *etc.* </code></pre> <p>Django allows you to easily work with no database mapping. Your model can easily be anything. Just don't call it <code>models.py</code>.</p> <hr> <p><strong>Edit</strong>.</p> <p>Are Views registered with Models? No.</p> <p>On update to the Model by the Controller the Views get notified? No.</p> <p>Is the Model strictly the data respresentation as this is really MVP? Yes.</p> <p>Read the Django docs. It's simple.</p> <p>Web Request -> URL mapping -> View function -> Template -> Response.</p> <p>The model can be used by the view function. The model can be a database mapping, or it can be any other thing.</p>
31
2009-08-17T23:07:15Z
[ "python", "django", "model-view-controller", "models" ]
Python capture output from wget?
1,290,910
<p>Is it possible to capture output from wget and other command line programs that use curses? Here is what I have right now:</p> <pre><code>p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=0) for line in p.stdout: print "a" </code></pre> <p>This works fine for programs that have simple output, but not for wget and other programs that use curses.</p>
1
2009-08-17T22:45:08Z
1,290,984
<p>I don't believe that <code>wget</code> is using curses.</p> <p>Normally when I want to use <code>wget</code> in a script I'd use the <strong><code>-O -</code></strong> option to force its output to <i>stdout</i>. I suspect you're trying to capture the text that you <strong>normally</strong> see on your console when you're running it, which would be <strong><i>stderr</i></strong>.</p> <p>From the command line, outside of Python, just run a command like:</p> <pre><code>wget -O - http://www.somesite.org/ &gt; /tmp/wget.out 2&gt; /tmp/wget.err </code></pre> <p>Then look at the two output files. If you see any output from <code>wget</code> on your console/terminal then you are running some different flavor of the command than I've seen.</p> <p>If, as I suspect, you're actually interested in the <i>stderr</i> messages then you have two choices.</p> <ul> <li>Change your command to add 2>&amp;1 and add <code>shell=True</code> to your <code>Popen()</code> arguments</li> <li>Alternatively add <code>stderr=subprocess.PIPE</code> to your <code>Popen()</code> arguments</li> </ul> <p>The former is handy if you weren't using <i>stdout</i> anyway (assuming your using <code>wget</code> to fetch the data and write it into files). In the latter case you read from the <i>stderr</i> file option to get your data.</p> <p>BTW: if you really did need to capture <strong>curses</strong> data ... you could try to use the standard <strong><i>pty</i></strong> module but I wouldn't recommend that. You'd be far better off fetching the <strong><code>pexpect</code></strong> module from:</p> <ul> <li>[PyPI: pexpect]: <a href="http://pypi.python.org/pypi?%3Aaction=search&amp;term=pexpect&amp;submit=search" rel="nofollow">http://pypi.python.org/pypi?%3Aaction=search&amp;term=pexpect&amp;submit=search</a></li> </ul> <p>And don't be scared off by the age or version numbering, it works on Python 2.5 and 2.6 as well as 2.4 and 2.3.</p>
6
2009-08-17T23:09:14Z
[ "python" ]
Phonon VideoWidget error: "the video widget could not be initialized correctly"
1,291,068
<p>I asked this question on the PyQt mailing list, and didn't get any responses, so I'll try my luck here.</p> <p>I've encountered a frustrating issue (on Windows only): when trying to create a VideoWidget instance, I'm getting the error message "the video widget could not be initialized correctly". Oddly, this just surfaced in the code after several weeks of perfect operation, on two separate Windows boxes (one Vista, the other an XP image running via Parallels). I'm not aware of anything having changed in the environment that may have caused it.</p> <p>I'm using Python 2.6 and the PyQt 4.5.4 Windows installer. I notice this issue was raised last November, but no solutions were offered:</p> <p><a href="http://www.riverbankcomputing.com/pipermail/pyqt/2008-November/021029.html" rel="nofollow">http://www.riverbankcomputing.com/pipermail/pyqt/2008-November/021029.html</a></p> <p>My Googling hasn't turned up any explanations of what may cause this. Can anyone clue me in?</p>
0
2009-08-17T23:42:35Z
1,291,283
<p>The code that generates that message is in <code>3rdparty/phonon/ds9/videorenderer_vmr9.cpp</code>:</p> <pre><code>m_filter = Filter(CLSID_VideoMixingRenderer9, IID_IBaseFilter); if (!m_filter) { qWarning("the video widget could not be initialized correctly"); return; } </code></pre> <p>Filter is type <code>ComPointer&lt;IBaseFilter&gt;</code> and its constructor makes the following failing call (an operator call returns m_t which is assigned to m_filter above):</p> <pre><code>::CoCreateInstance(clsid, 0, CLSCTX_INPROC_SERVER, iid, reinterpret_cast&lt;void**&gt;(&amp;m_t)); </code></pre> <p>Thus, it's failing in a Windows API call. You could modify the source code to find out what the return value of CoCreateInstance is in order to isolate the cause, but it looks like it's related to a change on your system and I don't know how to help further. Good luck.</p>
3
2009-08-18T00:56:12Z
[ "python", "qt", "pyqt", "phonon" ]
Phonon VideoWidget error: "the video widget could not be initialized correctly"
1,291,068
<p>I asked this question on the PyQt mailing list, and didn't get any responses, so I'll try my luck here.</p> <p>I've encountered a frustrating issue (on Windows only): when trying to create a VideoWidget instance, I'm getting the error message "the video widget could not be initialized correctly". Oddly, this just surfaced in the code after several weeks of perfect operation, on two separate Windows boxes (one Vista, the other an XP image running via Parallels). I'm not aware of anything having changed in the environment that may have caused it.</p> <p>I'm using Python 2.6 and the PyQt 4.5.4 Windows installer. I notice this issue was raised last November, but no solutions were offered:</p> <p><a href="http://www.riverbankcomputing.com/pipermail/pyqt/2008-November/021029.html" rel="nofollow">http://www.riverbankcomputing.com/pipermail/pyqt/2008-November/021029.html</a></p> <p>My Googling hasn't turned up any explanations of what may cause this. Can anyone clue me in?</p>
0
2009-08-17T23:42:35Z
1,764,250
<p>Hate to answer my own question, but if anyone else encounters this:</p> <p>The solution to this ended up being hardware-specific. Phonon appears to have issues with the video drivers for particular virtual machines - Parallels in my case. Physical hardware doesn't exhibit the issue. There is no workaround I've been able to find.</p>
0
2009-11-19T15:47:58Z
[ "python", "qt", "pyqt", "phonon" ]
Checking for group membership (Many to Many in Django)
1,291,167
<p>I have two models in Django: groups and entries. Groups has a many-to-many field that connects it to entries. I want to select all entries that have a group (as not all do!) and be able to access their group.title field.</p> <p>I've tried something along the lines of: </p> <pre><code>t = Entries.objects.select_related().exclude(group=None) </code></pre> <p>and while this returns all entries that have groups, I can't do t[0].groups to get the title. Any ideas on how this could be done?</p> <p>Edit: more info</p> <p>When ever I use Django's shell to inspect what is returned in t (in this example), t[0].group does not exist. The only way I can access this is via t[0].group_set.all()[0].title, which seems inefficient and like I'm doing something incorrectly. </p>
2
2009-08-18T00:17:10Z
1,291,202
<p>You don't show the model code, so I can't be sure, but instead of t[0].groups, I think you want:</p> <pre><code>for g in t[0].groups.all(): print g.title </code></pre>
3
2009-08-18T00:27:49Z
[ "python", "django" ]
Abstraction and client/server architecture questions for Python game program
1,291,179
<p>Here is where I am at presently. I am designing a card game with the aim of utilizing major components for future work. The part that is hanging me up is creating a layer of abstraction between the server and the client(s). A server is started, and then one or more clients can connect (locally or remotely). I am designing a thick client but my friend is looking at doing a web-based client. I would like to design the server in a manner that allows a variety of different clients to call a common set of server commands.</p> <p>So, for a start, I would like to create a 'server' which manages the game rules and player interactions, and a 'client' on the local CLI (I'm running Ubuntu Linux for convenience). I'm attempting to flesh out how the two pieces are supposed to interact, without mandating that future clients be CLI-based or on the local machine.</p> <p>I've found the following two questions which are beneficial, but don't quite answer the above.</p> <ul> <li><a href="http://stackoverflow.com/questions/487229/client-server-programming-in-python">Client Server programming in python?</a></li> <li><a href="http://stackoverflow.com/questions/456753/evaluate-my-python-server-structure">Evaluate my Python server structure</a></li> </ul> <p>I don't require anything full-featured right away; I just want to establish the basic mechanisms for abstraction so that the resulting mock-up code reflects the relationship appropriately: there are different assumptions at play with a client/server relationship than with an all-in-one application.</p> <p>Where do I start? What resources do you recommend?</p> <p>Disclaimers: I am familiar with code in a variety of languages and general programming/logic concepts, but have little real experience writing substantial amounts of code. This pet project is an attempt at rectifying this.</p> <p>Also, I know the information is out there already, but I have the strong impression that I am missing the forest for the trees.</p>
2
2009-08-18T00:21:00Z
1,291,227
<p>Read up on RESTful architectures.</p> <p>Your fat client can use REST. It will use <code>urllib2</code> to make RESTful requests of a server. It can exchange data in JSON notation.</p> <p>A web client can use REST. It can make simple browser HTTP requests or a Javascript component can make more sophisticated REST requests using JSON.</p> <p>Your server can be built as a simple WSGI application using any simple WSGI components. You have nice ones in the standard library, or you can use <a href="http://werkzeug.pocoo.org/" rel="nofollow">Werkzeug</a>. Your server simply accepts REST requests and makes REST responses. Your server can work in HTML (for a browser) or JSON (for a fat client or Javascript client.)</p>
2
2009-08-18T00:35:39Z
[ "python", "client-server", "abstraction" ]
Abstraction and client/server architecture questions for Python game program
1,291,179
<p>Here is where I am at presently. I am designing a card game with the aim of utilizing major components for future work. The part that is hanging me up is creating a layer of abstraction between the server and the client(s). A server is started, and then one or more clients can connect (locally or remotely). I am designing a thick client but my friend is looking at doing a web-based client. I would like to design the server in a manner that allows a variety of different clients to call a common set of server commands.</p> <p>So, for a start, I would like to create a 'server' which manages the game rules and player interactions, and a 'client' on the local CLI (I'm running Ubuntu Linux for convenience). I'm attempting to flesh out how the two pieces are supposed to interact, without mandating that future clients be CLI-based or on the local machine.</p> <p>I've found the following two questions which are beneficial, but don't quite answer the above.</p> <ul> <li><a href="http://stackoverflow.com/questions/487229/client-server-programming-in-python">Client Server programming in python?</a></li> <li><a href="http://stackoverflow.com/questions/456753/evaluate-my-python-server-structure">Evaluate my Python server structure</a></li> </ul> <p>I don't require anything full-featured right away; I just want to establish the basic mechanisms for abstraction so that the resulting mock-up code reflects the relationship appropriately: there are different assumptions at play with a client/server relationship than with an all-in-one application.</p> <p>Where do I start? What resources do you recommend?</p> <p>Disclaimers: I am familiar with code in a variety of languages and general programming/logic concepts, but have little real experience writing substantial amounts of code. This pet project is an attempt at rectifying this.</p> <p>Also, I know the information is out there already, but I have the strong impression that I am missing the forest for the trees.</p>
2
2009-08-18T00:21:00Z
1,291,243
<p>I would consider basing all server / client interactions on HTTP -- probably with JSON payloads. This doesn't directly allow server-initiated interactions ("server push"), but the (newish but already traditional;-) workaround for that is AJAX-y (even though the X makes little sense as I suggest JSON payloads, not XML ones;-) -- the client initiates an async request (via a separate thread or otherwise) to a special URL on the server, and the server responds to those requests to (in practice) do "pushes". From what you say it looks like the limitations of this approach might not be a problem.</p> <p>The key advantage of specifying the interactions in such terms is that they're entirely independent from the programming language -- so the web-based client in Javascript will be just as doable as your CLI one in Python, etc etc. Of course, the server can live on localhost as a special case, but there is no constraint for that as the HTTP URLs can specify whatever host is running the server; etc, etc.</p>
2
2009-08-18T00:39:44Z
[ "python", "client-server", "abstraction" ]
Abstraction and client/server architecture questions for Python game program
1,291,179
<p>Here is where I am at presently. I am designing a card game with the aim of utilizing major components for future work. The part that is hanging me up is creating a layer of abstraction between the server and the client(s). A server is started, and then one or more clients can connect (locally or remotely). I am designing a thick client but my friend is looking at doing a web-based client. I would like to design the server in a manner that allows a variety of different clients to call a common set of server commands.</p> <p>So, for a start, I would like to create a 'server' which manages the game rules and player interactions, and a 'client' on the local CLI (I'm running Ubuntu Linux for convenience). I'm attempting to flesh out how the two pieces are supposed to interact, without mandating that future clients be CLI-based or on the local machine.</p> <p>I've found the following two questions which are beneficial, but don't quite answer the above.</p> <ul> <li><a href="http://stackoverflow.com/questions/487229/client-server-programming-in-python">Client Server programming in python?</a></li> <li><a href="http://stackoverflow.com/questions/456753/evaluate-my-python-server-structure">Evaluate my Python server structure</a></li> </ul> <p>I don't require anything full-featured right away; I just want to establish the basic mechanisms for abstraction so that the resulting mock-up code reflects the relationship appropriately: there are different assumptions at play with a client/server relationship than with an all-in-one application.</p> <p>Where do I start? What resources do you recommend?</p> <p>Disclaimers: I am familiar with code in a variety of languages and general programming/logic concepts, but have little real experience writing substantial amounts of code. This pet project is an attempt at rectifying this.</p> <p>Also, I know the information is out there already, but I have the strong impression that I am missing the forest for the trees.</p>
2
2009-08-18T00:21:00Z
1,291,311
<p>First of all, regardless of the locality or type of the client, you will be communicating through an established message-based interface. All clients will be operating based on a common set of requests and responses, and the server will handle and reject these based on their validity according to game state. Whether you are dealing with local clients on the same machine or remote clients via HTTP does not matter whatsoever from an abstraction standpoint, as they will all be communicating through the same set of requests/responses.</p> <p>What this comes down to is your <em>protocol</em>. Your protocol should be a well-defined and technically sound language between client and server that will allow clients to a) participate effectively, and b) participate fairly. This protocol should define what messages ('moves') a client can do, and when, and how the server will react.</p> <p>Your protocol should be fully fleshed out and documented before you even start on game logic - the two are intrinsically connected and you will save a lot of wasted time and effort by competely defining your protocol first.</p> <p>You protocol <em>is</em> the abstraction between client and server and it will also serve as the design document and programming guide for both.</p> <p>Protocol design is all about state, state transitions, and validation. Game servers usually have a set of fairly common, generic states for each game instance e.g. initialization, lobby, gameplay, pause, recap, close game, etc...</p> <p>Each one of these states has important state data related with it. For example, a 'lobby' state on the server-side might contain the known state of each player...how long since the last message or ping, what the player is doing (selecting an avatar, switching settings, going to the fridge, etc.). Organizing and managing state and substate data in code is important.</p> <p>Managing these states, and the associated data requirements for each is a process that should be exquisitely planned out as they are directly related to volume of work and project complexity - this is very important and also great practice if you are using this project to step up into larger things.</p> <p>Also, you must keep in mind that if you have a game, and you let people play, people will cheat. It's a fact of life. In order to minimize this, you must carefully design your protocol and state management to only ever allow valid state transitions. Never trust a single client packet.</p> <p>For every permutation of client/server state, you must enforce a limited set of valid game messages, and you must be very careful in what you allow players to do, and when you allow them to do it.</p> <p>Project complexity is generally exponential and not linear - client/server game programming is usually a good/painful way to learn this. Great question. Hope this helps, and good luck!</p>
2
2009-08-18T01:08:35Z
[ "python", "client-server", "abstraction" ]
Confused by Django's claim to MVC, what is it exactly?
1,291,213
<p>So what exactly is Django implementing?</p> <p>Seems like there are</p> <pre><code>Models Views Templates </code></pre> <blockquote> <p>Models = Database mappings</p> <p>Views = Grab relevant data from the models and formats it via templates</p> <p>Templates = Display HTML depending on data given by Views</p> </blockquote> <p>EDIT: S. Lott cleared a lot up with this in an edit to a previous post, but I would still like to hear other feedback. Thanks!</p> <p>Is this correct? It really seems like Django is nowhere near the same as MVC and just confuses people by calling it that.</p>
6
2009-08-18T00:30:28Z
1,291,223
<p>Django's developers have a slightly non-traditional view on the MVC paradigm. They actually address this question in their FAQs, which you can read <a href="http://docs.djangoproject.com/en/dev/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names">here</a>. In their own words:</p> <blockquote> <p>In our interpretation of MVC, the “view” describes the data that gets presented to the user. It’s not necessarily how the data looks, but which data is presented. The view describes which data you see, not how you see it. It’s a subtle distinction.</p> <p>So, in our case, a “view” is the Python callback function for a particular URL, because that callback function describes which data is presented.</p> <p>Furthermore, it’s sensible to separate content from presentation – which is where templates come in. In Django, a “view” describes which data is presented, but a view normally delegates to a template, which describes how the data is presented.</p> <p>Where does the “controller” fit in, then? In Django’s case, it’s probably the framework itself: the machinery that sends a request to the appropriate view, according to the Django URL configuration.</p> </blockquote>
14
2009-08-18T00:33:51Z
[ "python", "django", "model-view-controller", "design-patterns" ]
When I catch an exception, how do I get the type, file, and line number of the previous frame?
1,291,438
<p>From <a href="http://stackoverflow.com/questions/1278705/python-when-i-catch-an-exception-how-do-i-get-the-type-file-and-line-number/1278740#1278740">this question</a>, I'm now doing error handling one level down. That is, I call a function which calls another larger function, and I want where it failed in that larger function, not in the smaller function. Specific example. Code is:</p> <pre><code>import sys, os def workerFunc(): return 4/0 def runTest(): try: print workerFunc() except: ty,val,tb = sys.exc_info() print "Error: %s,%s,%s" % ( ty.__name__, os.path.split(tb.tb_frame.f_code.co_filename)[1], tb.tb_lineno) runTest() </code></pre> <p>Output is:</p> <pre><code>Error: ZeroDivisionError,tmp2.py,8 </code></pre> <p>but line 8 is "print workerFunc()" - I know that line failed, but I want the line before:</p> <pre><code>Error: ZeroDivisionError,tmp2.py,4 </code></pre>
6
2009-08-18T02:08:47Z
1,291,463
<p>Add a line:</p> <pre><code> tb = tb.tb_next </code></pre> <p>just after your call to <code>sys.exc_info</code>.</p> <p>See the docs <a href="http://docs.python.org/reference/datamodel.html" rel="nofollow">here</a> under "Traceback objects".</p>
4
2009-08-18T02:18:45Z
[ "python", "exception", "exception-handling", "error-handling" ]
When I catch an exception, how do I get the type, file, and line number of the previous frame?
1,291,438
<p>From <a href="http://stackoverflow.com/questions/1278705/python-when-i-catch-an-exception-how-do-i-get-the-type-file-and-line-number/1278740#1278740">this question</a>, I'm now doing error handling one level down. That is, I call a function which calls another larger function, and I want where it failed in that larger function, not in the smaller function. Specific example. Code is:</p> <pre><code>import sys, os def workerFunc(): return 4/0 def runTest(): try: print workerFunc() except: ty,val,tb = sys.exc_info() print "Error: %s,%s,%s" % ( ty.__name__, os.path.split(tb.tb_frame.f_code.co_filename)[1], tb.tb_lineno) runTest() </code></pre> <p>Output is:</p> <pre><code>Error: ZeroDivisionError,tmp2.py,8 </code></pre> <p>but line 8 is "print workerFunc()" - I know that line failed, but I want the line before:</p> <pre><code>Error: ZeroDivisionError,tmp2.py,4 </code></pre>
6
2009-08-18T02:08:47Z
1,291,469
<p>You need to find the bottom of the traceback, so you need to loop along until there are no more frames. Do this to find the frame you want:</p> <pre><code>while tb.tb_next: tb = tb.tb_next </code></pre> <p>after sys.exc_info. This will find the exception no matter how many call frames down it happened.</p>
2
2009-08-18T02:21:09Z
[ "python", "exception", "exception-handling", "error-handling" ]
When I catch an exception, how do I get the type, file, and line number of the previous frame?
1,291,438
<p>From <a href="http://stackoverflow.com/questions/1278705/python-when-i-catch-an-exception-how-do-i-get-the-type-file-and-line-number/1278740#1278740">this question</a>, I'm now doing error handling one level down. That is, I call a function which calls another larger function, and I want where it failed in that larger function, not in the smaller function. Specific example. Code is:</p> <pre><code>import sys, os def workerFunc(): return 4/0 def runTest(): try: print workerFunc() except: ty,val,tb = sys.exc_info() print "Error: %s,%s,%s" % ( ty.__name__, os.path.split(tb.tb_frame.f_code.co_filename)[1], tb.tb_lineno) runTest() </code></pre> <p>Output is:</p> <pre><code>Error: ZeroDivisionError,tmp2.py,8 </code></pre> <p>but line 8 is "print workerFunc()" - I know that line failed, but I want the line before:</p> <pre><code>Error: ZeroDivisionError,tmp2.py,4 </code></pre>
6
2009-08-18T02:08:47Z
1,291,491
<p><code>tb.tb_next</code> is your friend:</p> <pre><code>import sys, os def workerFunc(): return 4/0 def runTest(): try: print workerFunc() except: ty,val,tb = sys.exc_info() print "Error: %s,%s,%s" % ( ty.__name__, os.path.split(tb.tb_frame.f_code.co_filename)[1], tb.tb_next.tb_lineno) runTest() </code></pre> <p>But the <a href="http://docs.python.org/library/traceback.html" rel="nofollow">traceback module</a> does this and much more:</p> <pre><code>import traceback def workerFunc(): return 4/0 def runTest(): try: print workerFunc() except: print traceback.format_exc() runTest() </code></pre>
3
2009-08-18T02:26:16Z
[ "python", "exception", "exception-handling", "error-handling" ]
Django : get entries of today and SplitDateTime Widget?
1,291,537
<p>I used : SplitDateTimeWidget to split DateTime field ,</p> <pre><code>appointment = forms.DateTimeField(widget=forms.SplitDateTimeWidget) </code></pre> <p>In the template side i manage to use datePicker and TimePicker for each field , using jQuery .</p> <p>When i try to filter the entries regarding to today date as in this code :</p> <pre><code>d = datetime.date.today() entries = Entry.objects.filter(appointment__year=d.year ,appointment__month=d.month ,appointment__day=d.day ) </code></pre> <p>It shows the entries of yesterday 17 aug :( which is really weird !</p> <p>I Tried to split the Date and Time in the model , i got the same result as well !</p> <p>Any idea how to fix this ?!</p>
0
2009-08-18T02:42:59Z
1,291,628
<p>Fix your timezone settings, in <code>settings.py TIME_ZONE</code></p> <p><strong>Default:</strong> <code>'America/Chicago'</code></p> <p>Some excerpts of useful info from <a href="http://docs.djangoproject.com/en/dev/ref/settings/#time-zone" rel="nofollow">the docs</a>:</p> <blockquote> <p>A string representing the time zone for this installation. <a href="http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE" rel="nofollow">See available choices.</a> </p> <p><em>(...)</em></p> <p><strong>Note that this is the time zone to which Django will convert all dates/times</strong> -- not necessarily the timezone of the server. </p> <p><em>(...)</em></p> <p>Django cannot reliably use alternate time zones in a Windows environment. If you're running Django on Windows, this variable must be set to match the system timezone.</p> </blockquote>
2
2009-08-18T03:23:54Z
[ "python", "django", "django-forms" ]
microcrontroller output to python cgi script
1,291,624
<p>I bought this temperature sensor logger kit: <a href="http://quozl.netrek.org/ts/" rel="nofollow">http://quozl.netrek.org/ts/</a>. It works great with the supplied C code, I like to use python because of its simplicity, so I wrote a script in python that displays the output from the microcontroller. I only have one temperature sensor hooked up to the kit. I want the temperature to be displayed on a web page, but can't seem to figure it out, I'm pretty sure it has something to do with the output from the micro having a \r\n DOS EOL character and linux web servers do not interpret it properly. The book I have says "Depending on the web server you are using, you might need to make configuration changes to understand how to serve CGI files." I am using debian and apache2 and basic cgi scripts work fine.</p> <p>Here is my code for just displaying the sensor to the console (this works fine):</p> <pre><code>import serial ser = serial.Serial('/dev/ttyS0', 2400) while 1: result = ser.readline() if result: print result </code></pre> <p>Here is my test.cgi script that works:</p> <pre><code>#!/usr/bin/python print "Content-type: text/html\n" print "&lt;title&gt;CGI Text&lt;/title&gt;\n" print "&lt;h1&gt;cgi works!&lt;/h1&gt;" </code></pre> <p>Here is the cgi script I have started to display temp (doesn't work - 500 internal server error):</p> <pre><code>#!/usr/bin/python import sys, serial sys.stderr = sys.stdout ser = serial.Serial('/dev/ttyS0', 2400) print "Content-type: text/html\n" print """ &lt;title&gt;Real Time Temperature&lt;/title&gt; &lt;h1&gt;Real Time Temperature:&lt;/h1&gt; """ #result = ser.readline() #if result: print ser.readline() </code></pre> <p>If i run python rtt.cgi in the console it outputs the correct html and temperature, I know this will not be real time and that the page will have to be reloaded every time that the user wants to see the temperature, but that stuff is coming in the future.. From my apache2 error log it says: malformed header from script. Bad header= File "/usr/lib/cgi-bin/rtt.c: rtt.cgi</p>
1
2009-08-18T03:22:26Z
1,291,762
<p>I'm guessing that the execution context under which your CGI is running is unable to complete the <code>read()</code> from the serial port.</p> <p>Incidentally the Python standard libraries have MUCH better ways for writing CGI scripts than what you're doing here; and even the basic string handling offers a better way to interpolate your results (assuming you code has the necessary permissions to <code>read()</code> them) into the HTML.</p> <p>At least I'd recommend something like:</p> <pre><code>#!/usr/bin/python import sys, serial sys.stderr = sys.stdout ser = serial.Serial('/dev/ttyS0', 2400) html = """Content-type: text/html &lt;html&gt;&lt;head&gt;&lt;title&gt;Real Time Temperature&lt;/title&gt;&lt;/head&gt;&lt;body&gt; &lt;h1&gt;Real Time Temperature:&lt;/h1&gt; &lt;p&gt;%s&lt;/p&gt; &lt;/body&gt;&lt;/html&gt; """ % ser.readline() # should be cgi.escape(ser.readline())! ser.close() sys.exit(0) </code></pre> <p>Notice we just interpolate the results of <code>ser.readline()</code> into our string using the <strong>%</strong> string operator. (Incidentally your HTML was missing <code>&lt;html&gt;, &lt;head&gt;</code>, <code>&lt;body&gt;</code>, and <code>&lt;p&gt;</code> (paragraph) tags).</p> <p>There are still problems with this. For example we really should at least import <code>cgi</code> wrap the foreign data in that to ensure that HTML entities are properly substituted for any reserved characters, etc).</p> <p>I'd suggest further reading: [Python Docs]: <a href="http://docs.python.org/library/cgi.html" rel="nofollow">http://docs.python.org/library/cgi.html</a></p>
2
2009-08-18T04:11:53Z
[ "python", "serial-port", "cgi" ]
microcrontroller output to python cgi script
1,291,624
<p>I bought this temperature sensor logger kit: <a href="http://quozl.netrek.org/ts/" rel="nofollow">http://quozl.netrek.org/ts/</a>. It works great with the supplied C code, I like to use python because of its simplicity, so I wrote a script in python that displays the output from the microcontroller. I only have one temperature sensor hooked up to the kit. I want the temperature to be displayed on a web page, but can't seem to figure it out, I'm pretty sure it has something to do with the output from the micro having a \r\n DOS EOL character and linux web servers do not interpret it properly. The book I have says "Depending on the web server you are using, you might need to make configuration changes to understand how to serve CGI files." I am using debian and apache2 and basic cgi scripts work fine.</p> <p>Here is my code for just displaying the sensor to the console (this works fine):</p> <pre><code>import serial ser = serial.Serial('/dev/ttyS0', 2400) while 1: result = ser.readline() if result: print result </code></pre> <p>Here is my test.cgi script that works:</p> <pre><code>#!/usr/bin/python print "Content-type: text/html\n" print "&lt;title&gt;CGI Text&lt;/title&gt;\n" print "&lt;h1&gt;cgi works!&lt;/h1&gt;" </code></pre> <p>Here is the cgi script I have started to display temp (doesn't work - 500 internal server error):</p> <pre><code>#!/usr/bin/python import sys, serial sys.stderr = sys.stdout ser = serial.Serial('/dev/ttyS0', 2400) print "Content-type: text/html\n" print """ &lt;title&gt;Real Time Temperature&lt;/title&gt; &lt;h1&gt;Real Time Temperature:&lt;/h1&gt; """ #result = ser.readline() #if result: print ser.readline() </code></pre> <p>If i run python rtt.cgi in the console it outputs the correct html and temperature, I know this will not be real time and that the page will have to be reloaded every time that the user wants to see the temperature, but that stuff is coming in the future.. From my apache2 error log it says: malformed header from script. Bad header= File "/usr/lib/cgi-bin/rtt.c: rtt.cgi</p>
1
2009-08-18T03:22:26Z
1,303,699
<p>one more time:</p> <pre><code># Added to allow cgi-bin to execute cgi, python and perl scripts ScriptAlias /cgi-bin/ /var/www/cgi-bin/ AddHandler cgi-script .cgi .py .pl &lt;Directory /var/www&gt; Options +Execcgi AddHandler cgi-script .cgi .py .pl &lt;/Directory&gt; </code></pre>
0
2009-08-20T02:48:55Z
[ "python", "serial-port", "cgi" ]
microcrontroller output to python cgi script
1,291,624
<p>I bought this temperature sensor logger kit: <a href="http://quozl.netrek.org/ts/" rel="nofollow">http://quozl.netrek.org/ts/</a>. It works great with the supplied C code, I like to use python because of its simplicity, so I wrote a script in python that displays the output from the microcontroller. I only have one temperature sensor hooked up to the kit. I want the temperature to be displayed on a web page, but can't seem to figure it out, I'm pretty sure it has something to do with the output from the micro having a \r\n DOS EOL character and linux web servers do not interpret it properly. The book I have says "Depending on the web server you are using, you might need to make configuration changes to understand how to serve CGI files." I am using debian and apache2 and basic cgi scripts work fine.</p> <p>Here is my code for just displaying the sensor to the console (this works fine):</p> <pre><code>import serial ser = serial.Serial('/dev/ttyS0', 2400) while 1: result = ser.readline() if result: print result </code></pre> <p>Here is my test.cgi script that works:</p> <pre><code>#!/usr/bin/python print "Content-type: text/html\n" print "&lt;title&gt;CGI Text&lt;/title&gt;\n" print "&lt;h1&gt;cgi works!&lt;/h1&gt;" </code></pre> <p>Here is the cgi script I have started to display temp (doesn't work - 500 internal server error):</p> <pre><code>#!/usr/bin/python import sys, serial sys.stderr = sys.stdout ser = serial.Serial('/dev/ttyS0', 2400) print "Content-type: text/html\n" print """ &lt;title&gt;Real Time Temperature&lt;/title&gt; &lt;h1&gt;Real Time Temperature:&lt;/h1&gt; """ #result = ser.readline() #if result: print ser.readline() </code></pre> <p>If i run python rtt.cgi in the console it outputs the correct html and temperature, I know this will not be real time and that the page will have to be reloaded every time that the user wants to see the temperature, but that stuff is coming in the future.. From my apache2 error log it says: malformed header from script. Bad header= File "/usr/lib/cgi-bin/rtt.c: rtt.cgi</p>
1
2009-08-18T03:22:26Z
1,320,294
<p>Michael,</p> <p>It looks like the issue is definitely permissions, however, you shouldn't try to make your script have the permission of /dev/ttyS0. What you will probably need to do is spawn another process where the first thing you do is change your group to the group of the /dev/ttyS0 device. On my box that's 'dialout' you're may be different.</p> <p>You'll need to import the os package, look in the docs for the Process Parameters, on that page you will find some functions that allow you to change your ownership. You will also need to use one of the functions in Process Management also in the os package, these functions spawn processes, but you will need to choose one that will return the data from the spawned process. The subprocess package may be better for this.</p> <p>The reason you need to spawn another process is that the CGI script need to run under the Apache process and the spawn process needs to access the serial port.</p> <p>If I get a chance in the next few days I'll try to put something together for you, but give it a try, don't wait for me.</p> <p>Also one other thing all HTTP headers need to end in two CRLF sequences. So your header needs to be:</p> <p>print "Content-type: text/html\r\n\r\n"</p> <p>If you don't do this your browser may not know when the header ends and the entity data begins. Read RFC-2616</p> <p>~Carl</p>
0
2009-08-24T02:56:48Z
[ "python", "serial-port", "cgi" ]
How can I tell whether my Django application is running on development server or not?
1,291,755
<p>How can I be certain that my application is running on development server or not? I suppose I could check value of <code>settings.DEBUG</code> and assume if <code>DEBUG</code> is <code>True</code> then it's running on development server, but I'd prefer to know for sure than relying on convention.</p>
36
2009-08-18T04:10:26Z
1,291,769
<p>settings.DEBUG could be True and running under Apache or some other non-development server. It will still run. As far as I can tell, there is nothing in the run-time environment short of examining the pid and comparing to pids in the OS that will give you this information.</p>
1
2009-08-18T04:14:19Z
[ "python", "django", "wsgi" ]
How can I tell whether my Django application is running on development server or not?
1,291,755
<p>How can I be certain that my application is running on development server or not? I suppose I could check value of <code>settings.DEBUG</code> and assume if <code>DEBUG</code> is <code>True</code> then it's running on development server, but I'd prefer to know for sure than relying on convention.</p>
36
2009-08-18T04:10:26Z
1,291,819
<p>One difference between the development and deployment environment is going to be the server that it’s running on. What exactly is different will depend on your dev and deployment environments.</p> <p>Knowing your own dev and deploy environments, the HTTP request variables could be used to distinguish between the two. Look at <a href="http://docs.djangoproject.com/en/dev/ref/request-response/" rel="nofollow">request variables</a> like <code>request.META.HTTP_HOST</code>, <code>request.META.SERVER_NAME</code> and <code>request.META.SERVER_PORT</code> and compare them in the two environments.</p> <p>I bet you’ll find something quite obvious that’s different and can be used to detect your development environment. Do the test in <code>settings.py</code> and set a variable that you can use elsewhere.</p>
0
2009-08-18T04:32:07Z
[ "python", "django", "wsgi" ]
How can I tell whether my Django application is running on development server or not?
1,291,755
<p>How can I be certain that my application is running on development server or not? I suppose I could check value of <code>settings.DEBUG</code> and assume if <code>DEBUG</code> is <code>True</code> then it's running on development server, but I'd prefer to know for sure than relying on convention.</p>
36
2009-08-18T04:10:26Z
1,291,858
<pre><code>server = request.META.get('wsgi.file_wrapper', None) if server is not None and server.__module__ == 'django.core.servers.basehttp': print('inside dev') </code></pre> <p>Of course, <code>wsgi.file_wrapper</code> might be set on META, and have a class from a module named <code>django.core.servers.basehttp</code> by extreme coincidence on another server environment, but I hope this will have you covered.</p> <p>By the way, I discovered this by making a syntatically invalid template while running on the development server, and searched for interesting stuff on the <code>Traceback</code> and the <code>Request information</code> sections, so I'm just editing my answer to corroborate with Nate's ideas.</p>
16
2009-08-18T04:49:39Z
[ "python", "django", "wsgi" ]
How can I tell whether my Django application is running on development server or not?
1,291,755
<p>How can I be certain that my application is running on development server or not? I suppose I could check value of <code>settings.DEBUG</code> and assume if <code>DEBUG</code> is <code>True</code> then it's running on development server, but I'd prefer to know for sure than relying on convention.</p>
36
2009-08-18T04:10:26Z
1,291,864
<p>Typically I set an variable called <code>environment</code> and set it to "DEVELOPMENT", "STAGING" or "PRODUCTION". Within the settings file I can then add basic logic to change which settings are being used, based on environment.</p> <p><strong>EDIT:</strong> Additionally, you can simply use this logic to include different <code>settings.py</code> files that override the base settings. For example:</p> <pre><code>if environment == "DEBUG": from debugsettings import * </code></pre>
9
2009-08-18T04:54:41Z
[ "python", "django", "wsgi" ]
How can I tell whether my Django application is running on development server or not?
1,291,755
<p>How can I be certain that my application is running on development server or not? I suppose I could check value of <code>settings.DEBUG</code> and assume if <code>DEBUG</code> is <code>True</code> then it's running on development server, but I'd prefer to know for sure than relying on convention.</p>
36
2009-08-18T04:10:26Z
1,292,019
<p>Relying on settings.DEBUG is the most elegant way AFAICS as it is also used in Django code base on occasion. </p> <p>I suppose what you really want is a way to set that flag automatically without needing you update it manually everytime you upload the project to production servers. </p> <p>For that I check the path of settings.py (in settings.py) to determine what server the project is running on:</p> <pre><code>if __file__ == "path to settings.py in my development machine": DEBUG = True elif __file__ in [paths of production servers]: DEBUG = False else: raise WhereTheHellIsThisServedException() </code></pre> <p>Mind you, you might also prefer doing this check with environment variables as @Soviut suggests. But as someone developing on Windows and serving on Linux checking the file paths was plain easier than going with environment variables.</p>
4
2009-08-18T05:44:47Z
[ "python", "django", "wsgi" ]
How can I tell whether my Django application is running on development server or not?
1,291,755
<p>How can I be certain that my application is running on development server or not? I suppose I could check value of <code>settings.DEBUG</code> and assume if <code>DEBUG</code> is <code>True</code> then it's running on development server, but I'd prefer to know for sure than relying on convention.</p>
36
2009-08-18T04:10:26Z
4,277,798
<p>I put the following in my settings.py to distinguish between the standard dev server and production:</p> <pre><code>import sys RUNNING_DEVSERVER = (len(sys.argv) &gt; 1 and sys.argv[1] == 'runserver') </code></pre> <p>This also relies on convention, however. </p> <p>(Amended per Daniel Magnusson's comment)</p>
22
2010-11-25T13:54:22Z
[ "python", "django", "wsgi" ]
How can I tell whether my Django application is running on development server or not?
1,291,755
<p>How can I be certain that my application is running on development server or not? I suppose I could check value of <code>settings.DEBUG</code> and assume if <code>DEBUG</code> is <code>True</code> then it's running on development server, but I'd prefer to know for sure than relying on convention.</p>
36
2009-08-18T04:10:26Z
8,900,872
<p>I came across this problem just now, and ended up writing a solution similar to Aryeh Leib Taurog's. My main difference is that I want to differentiate between a production and dev environments when running the server, but also when running some one-off scripts for my app (which I run like DJANGO_SETTINGS_MODULE=settings python [the script] ). In this case, simply looking at whether argv[1] == runserver isn't enough. So what I came up with is to pass an extra command-line argument when I run the devserver, and also when I run my scripts, and just look for that argument in settings.py. So the code looks like this:</p> <pre><code>if '--in-development' in sys.argv: ## YES! we're in dev pass else: ## Nope, this is prod pass </code></pre> <p>then, running the django server becomes</p> <p>python manage.py runserver [whatever options you want] --in-development</p> <p>and running my scripts is as easy as</p> <p>DJANGO_SETTINGS_MODULE=settings python [myscript] --in-development</p> <p>Just make sure the extra argument you pass along doens't conflict with anything django (in reality I use my app's name as part of the argument). I think this is pretty decent, as it lets me control exactly when my server and scripts will behave as prod or dev, and I'm not relying on anyone else's conventions, other than my own.</p> <p>EDIT: manage.py complains if you pass unrecognized options, so you need to change the code in settings.py to be something like</p> <pre><code>if sys.argv[0] == 'manage.py' or '--in-development' in sys.argv: # ... pass </code></pre> <p>Although this works, I recognize it's not the most elegant of solutions...</p>
3
2012-01-17T19:58:10Z
[ "python", "django", "wsgi" ]
How can I tell whether my Django application is running on development server or not?
1,291,755
<p>How can I be certain that my application is running on development server or not? I suppose I could check value of <code>settings.DEBUG</code> and assume if <code>DEBUG</code> is <code>True</code> then it's running on development server, but I'd prefer to know for sure than relying on convention.</p>
36
2009-08-18T04:10:26Z
10,732,264
<p>Inspired by Aryeh's answer, the trick I devised for my own use is to just look for the name of my management script in <code>sys.argv[0]</code>:</p> <pre><code>USING_DEV_SERVER = "pulpdist/manage_site.py" in sys.argv[0] </code></pre> <p>(My use case is to automatically enable Django native authentication when running the test server - when running under Apache, even on development servers, all authentication for my current project is handled via Kerberos)</p>
0
2012-05-24T06:28:47Z
[ "python", "django", "wsgi" ]
How can I tell whether my Django application is running on development server or not?
1,291,755
<p>How can I be certain that my application is running on development server or not? I suppose I could check value of <code>settings.DEBUG</code> and assume if <code>DEBUG</code> is <code>True</code> then it's running on development server, but I'd prefer to know for sure than relying on convention.</p>
36
2009-08-18T04:10:26Z
11,232,206
<p>I use:</p> <pre><code>DEV_SERVERS = [ 'mymachine.local', ] DEVELOPMENT = platform.node() in DEV_SERVERS </code></pre> <p>which requires paying attention to what is returned by <code>.node()</code> on your machines. It's important that the default be non-development so that you don't accidentally expose sensitive development information.</p> <p>You could also look into <a href="http://serialsense.com/blog/2011/02/generating-unique-machine-ids/" rel="nofollow">more complicated ways of uniquely identifying computers</a>.</p>
0
2012-06-27T17:53:33Z
[ "python", "django", "wsgi" ]
How can I tell whether my Django application is running on development server or not?
1,291,755
<p>How can I be certain that my application is running on development server or not? I suppose I could check value of <code>settings.DEBUG</code> and assume if <code>DEBUG</code> is <code>True</code> then it's running on development server, but I'd prefer to know for sure than relying on convention.</p>
36
2009-08-18T04:10:26Z
12,706,200
<p>If you want to switch your settings files automatically dependent on the runtime environment you could just use something that differs in environ, e.g.</p> <pre><code>from os import environ if environ.get('_', ''): print "This is dev - not Apache mod_wsgi" </code></pre>
1
2012-10-03T10:04:27Z
[ "python", "django", "wsgi" ]
How can I tell whether my Django application is running on development server or not?
1,291,755
<p>How can I be certain that my application is running on development server or not? I suppose I could check value of <code>settings.DEBUG</code> and assume if <code>DEBUG</code> is <code>True</code> then it's running on development server, but I'd prefer to know for sure than relying on convention.</p>
36
2009-08-18T04:10:26Z
37,880,897
<p>Usually this works:</p> <pre><code>import sys if 'runserver' in sys.argv: # you use runserver </code></pre>
1
2016-06-17T11:52:44Z
[ "python", "django", "wsgi" ]
Django ImageField validation & PIL
1,292,061
<p>On sunday, I had problems with python modules, when I installed stackless python. Now I have compiled and installed : </p> <p>setuptools &amp; python-mysqldb and i got my django project up and running again. (i also reinstalled django-1.1), </p> <p>Then I compiled and installed, jpeg, freetype2 and PIL. I also started using mod_wsgi instead of mod_python.</p> <p>But when uploading imagefield in form I get validationerror: </p> <p>Upload a valid image. The file you uploaded was either not an image or a corrupted image. </p> <p>Searchmonkey shows that it comes from field.py imagefield validation. before raising this error it imports Image from PIL, opens file and verfies it. I tried importing PIL from python prompt manually - it worked just fine. Same with Image.open and Image.verify. So what could be causing this problem? </p> <p>Alan</p>
1
2009-08-18T05:59:17Z
2,776,304
<p>Might want to check out this blog post and see if it addresses your problem.</p> <p><a href="http://www.chipx86.com/blog/2008/07/25/django-tips-pil-imagefield-and-unit-tests/" rel="nofollow">http://www.chipx86.com/blog/2008/07/25/django-tips-pil-imagefield-and-unit-tests/</a></p>
0
2010-05-05T19:52:13Z
[ "python", "django", "python-imaging-library", "mod-wsgi", "python-stackless" ]
Is there a quick way to tell if an app is in Django's installed_apps?
1,292,074
<p>I'm writing a quick Django module and want to check for another module. Is there's a shortcut to check if another module is in the installed_apps list in Django's settings?</p>
1
2009-08-18T06:04:12Z
1,292,103
<pre><code>from settings import INSTALLED_APPS if 'appname' in INSTALLED_APPS: print 'we have app' </code></pre> <p>And this way is somewhat <a href="http://code.djangoproject.com/browser/django/trunk/django/db/models/loading.py?rev=10088#L55" rel="nofollow">how Django itself does</a>. Also check the <code>load_app</code> method on the linked page.</p>
4
2009-08-18T06:19:44Z
[ "python", "django" ]
Is it possible to filter on a related item in Django annotations?
1,292,081
<p>I have the following 2 models:</p> <pre><code>class Job(models.Model): title = models.CharField(_('title'), max_length=50) description = models.TextField(_('description')) category = models.ForeignKey(JobCategory, related_name='jobs') created_date = models.DateTimeField(auto_now_add=True) class JobCategory(models.Model): title = models.CharField(_('title'), max_length=50) slug = models.SlugField(_('slug')) </code></pre> <p>Here is where I am at with the query thus far:</p> <pre><code>def job_categories(): categories = JobCategory.objects.annotate(num_postings=Count('jobs')) return {'categories': categories} </code></pre> <p>The problem is that I only want to count jobs that were created in the past 30 days. I want to return all categories however, not only those categories that have qualifying jobs.</p>
1
2009-08-18T06:09:56Z
1,292,300
<p>Just a guess... but would this work?</p> <pre><code>def job_categories(): thritydaysago = datetime.datetime.now() - datetime.timedelta(days=30) categories = JobCategory.objects.filter(job__created_date__gte=thritydaysago).annotate(num_postings=Count('jobs')) return {'categories': categories} </code></pre> <p>See"<a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships" rel="nofollow">lookups-that-span-relationships</a>" for more details on spanning queries. Hmmm... probably need another query in there to get all categories...</p>
4
2009-08-18T07:18:26Z
[ "python", "django", "annotations", "django-queryset" ]
Is it possible to filter on a related item in Django annotations?
1,292,081
<p>I have the following 2 models:</p> <pre><code>class Job(models.Model): title = models.CharField(_('title'), max_length=50) description = models.TextField(_('description')) category = models.ForeignKey(JobCategory, related_name='jobs') created_date = models.DateTimeField(auto_now_add=True) class JobCategory(models.Model): title = models.CharField(_('title'), max_length=50) slug = models.SlugField(_('slug')) </code></pre> <p>Here is where I am at with the query thus far:</p> <pre><code>def job_categories(): categories = JobCategory.objects.annotate(num_postings=Count('jobs')) return {'categories': categories} </code></pre> <p>The problem is that I only want to count jobs that were created in the past 30 days. I want to return all categories however, not only those categories that have qualifying jobs.</p>
1
2009-08-18T06:09:56Z
1,310,533
<p>I decided to approach this differently and chose not to use annotations at all. I added a manager to the Job model that returned only active (30 days or less old) jobs, and created a property on the JobCategory model that queried for the instance's job count. My templatetag simply returned all categories. Here is the relevant code.</p> <pre><code>class JobCategory(models.Model): title = models.CharField(_('title'), max_length=50, help_text=_("Max 50 chars. Required.")) slug = models.SlugField(_('slug'), help_text=_("Only letters, numbers, or hyphens. Required.")) class Meta: verbose_name = _('job category') verbose_name_plural = _('job categories') def __unicode__(self): return self.title def get_absolute_url(self): return reverse('djobs_category_jobs', args=[self.slug]) @property def active_job_count(self): return len(Job.active.filter(category=self)) class ActiveJobManager(models.Manager): def get_query_set(self): return super(ActiveJobManager, self).get_query_set().filter(created_date__gte=datetime.datetime.now() - datetime.timedelta(days=30)) class Job(models.Model): title = models.CharField(_('title'), max_length=50, help_text=_("Max 50 chars. Required.")) description = models.TextField(_('description'), help_text=_("Required.")) category = models.ForeignKey(JobCategory, related_name='jobs') employment_type = models.CharField(_('employment type'), max_length=5, choices=EMPLOYMENT_TYPE_CHOICES, help_text=_("Required.")) employment_level = models.CharField(_('employment level'), max_length=5, choices=EMPLOYMENT_LEVEL_CHOICES, help_text=_("Required.")) employer = models.ForeignKey(Employer) location = models.ForeignKey(Location) contact = models.ForeignKey(Contact) allow_applications = models.BooleanField(_('allow applications')) created_date = models.DateTimeField(auto_now_add=True) objects = models.Manager() active = ActiveJobManager() class Meta: verbose_name = _('job') verbose_name_plural = _('jobs') def __unicode__(self): return '%s at %s' % (self.title, self.employer.name) </code></pre> <p>and the tag...</p> <pre><code>def job_categories(): categories = JobCategory.objects.all() return {'categories': categories} </code></pre>
0
2009-08-21T07:41:27Z
[ "python", "django", "annotations", "django-queryset" ]
google python data example: pizza party
1,292,095
<p>hey i started learning python and am quite confused as how the google data library works. google has a pizza party example over at this <a href="http://code.google.com/p/gdata-python-client/wiki/WritingDataModelClasses" rel="nofollow">link</a></p> <p>can anyone here please take the time to explain how it is being done. i would be so grateful.</p> <p>WHAT I UNDERSTAND:</p> <pre><code>&lt;entry xmlns='http://www.w3.org/2005/Atom' xmlns:p='http://example.com/pizza/1.0'&gt; &lt;id&gt;http://www.example.com/pizzaparty/223&lt;/id&gt; &lt;title type='text'&gt;Pizza at my house!&lt;/title&gt; &lt;author&gt; &lt;name&gt;Joe&lt;/name&gt; &lt;email&gt;joe@example.com&lt;/email&gt; &lt;/author&gt; &lt;content type='text'&gt; Join us for a fun filled evening of pizza and games! &lt;/content&gt; &lt;link rel='alternate' type='text/html' href='http://www.example.com/joe_user/pizza_at_my_house.html'/&gt; &lt;p:pizza toppings='pepperoni, sausage' size='large'&gt;Pepperoni with cheese and sausage&lt;/p:pizza&gt; &lt;p:pizza toppings='mushrooms' size='medium'&gt;Mushroom&lt;/p:pizza&gt; &lt;p:pizza toppings='ham, pineapple' size='extra large'&gt;Hawaiian&lt;/p:pizza&gt; &lt;p:capacity&gt;25&lt;/p:capacity&gt; &lt;p:location&gt;My place.&lt;p:address&gt;123 Imaginary Ln, Sometown MO 63000&lt;/p:address&gt;&lt;/p:location&gt; &lt;/entry&gt; </code></pre> <p>this is the XML feed for the pizza. why it is created i do not understand.</p> <p>NOW this is the linking to the XML feed:</p> <pre><code>import atom.core PIZZA_TEMPLATE = '{http://example.com/pizza/1.0}%s' class Capacity(atom.core.XmlElement): _qname = PIZZA_TEMPLATE % 'capacity' </code></pre> <p>in PIZZA_TEMPLATE, what is "%s"? what is atom.core?</p> <p>i am a little confused. please help me.</p>
0
2009-08-18T06:17:00Z
1,292,124
<p>%s is a string placeholder, and % is the string interpolation operator. See the <a href="http://docs.python.org/library/stdtypes.html#string-formatting-operations" rel="nofollow">Python docs on string formatting</a> for more information.</p> <p><a href="http://gdata-python-client.googlecode.com/svn/trunk/pydocs/atom.core.html" rel="nofollow"><code>atom.core</code></a> is a Python module to work with <a href="http://en.wikipedia.org/wiki/Atom%5F%28standard%29" rel="nofollow">Atom feeds</a>.</p>
2
2009-08-18T06:27:23Z
[ "python", "xml" ]
google python data example: pizza party
1,292,095
<p>hey i started learning python and am quite confused as how the google data library works. google has a pizza party example over at this <a href="http://code.google.com/p/gdata-python-client/wiki/WritingDataModelClasses" rel="nofollow">link</a></p> <p>can anyone here please take the time to explain how it is being done. i would be so grateful.</p> <p>WHAT I UNDERSTAND:</p> <pre><code>&lt;entry xmlns='http://www.w3.org/2005/Atom' xmlns:p='http://example.com/pizza/1.0'&gt; &lt;id&gt;http://www.example.com/pizzaparty/223&lt;/id&gt; &lt;title type='text'&gt;Pizza at my house!&lt;/title&gt; &lt;author&gt; &lt;name&gt;Joe&lt;/name&gt; &lt;email&gt;joe@example.com&lt;/email&gt; &lt;/author&gt; &lt;content type='text'&gt; Join us for a fun filled evening of pizza and games! &lt;/content&gt; &lt;link rel='alternate' type='text/html' href='http://www.example.com/joe_user/pizza_at_my_house.html'/&gt; &lt;p:pizza toppings='pepperoni, sausage' size='large'&gt;Pepperoni with cheese and sausage&lt;/p:pizza&gt; &lt;p:pizza toppings='mushrooms' size='medium'&gt;Mushroom&lt;/p:pizza&gt; &lt;p:pizza toppings='ham, pineapple' size='extra large'&gt;Hawaiian&lt;/p:pizza&gt; &lt;p:capacity&gt;25&lt;/p:capacity&gt; &lt;p:location&gt;My place.&lt;p:address&gt;123 Imaginary Ln, Sometown MO 63000&lt;/p:address&gt;&lt;/p:location&gt; &lt;/entry&gt; </code></pre> <p>this is the XML feed for the pizza. why it is created i do not understand.</p> <p>NOW this is the linking to the XML feed:</p> <pre><code>import atom.core PIZZA_TEMPLATE = '{http://example.com/pizza/1.0}%s' class Capacity(atom.core.XmlElement): _qname = PIZZA_TEMPLATE % 'capacity' </code></pre> <p>in PIZZA_TEMPLATE, what is "%s"? what is atom.core?</p> <p>i am a little confused. please help me.</p>
0
2009-08-18T06:17:00Z
1,292,522
<p>Given that this question is about Python and involves a pizza party, I'd say you were biting off more than you can chew ...</p> <p>But seriously, if you're just learning Python, start with something simpler.</p>
0
2009-08-18T08:20:00Z
[ "python", "xml" ]
How does Python for loop work?
1,292,189
<p>I am used to the C++ way of for loops, but the Python loops have left me confused.</p> <pre><code>for party in feed.entry: print party.location.address.text </code></pre> <p>Here <code>party</code> in <code>feed.entry</code>. What does it signify and how does it actually work?</p>
4
2009-08-18T06:44:12Z
1,292,205
<p>feed.entry is something that allows iteration, and contains objects of some type. This is roughly similar to c++:</p> <pre><code>for (feed::iterator party = feed.entry.begin(); party != feed.entry.end(); ++party) { cout &lt;&lt; (*party).location.address.text; } </code></pre>
5
2009-08-18T06:50:53Z
[ "python", "for-loop" ]
How does Python for loop work?
1,292,189
<p>I am used to the C++ way of for loops, but the Python loops have left me confused.</p> <pre><code>for party in feed.entry: print party.location.address.text </code></pre> <p>Here <code>party</code> in <code>feed.entry</code>. What does it signify and how does it actually work?</p>
4
2009-08-18T06:44:12Z
1,292,214
<p>feed.entry is property of feed and it's value is (if it's not, this code will fail) object implementing iteration protocol (array, for example) and has <strong>iter</strong> method, which returns iterator object</p> <p>Iterator has next() method, returning next element or raising exception, so python for loop is actually:</p> <pre><code>iterator = feed.entry.__iter__() while True: try: party = iterator.next() except StopIteration: # StopIteration exception is raised after last element break # loop code print party.location.address.text </code></pre>
20
2009-08-18T06:53:46Z
[ "python", "for-loop" ]
How does Python for loop work?
1,292,189
<p>I am used to the C++ way of for loops, but the Python loops have left me confused.</p> <pre><code>for party in feed.entry: print party.location.address.text </code></pre> <p>Here <code>party</code> in <code>feed.entry</code>. What does it signify and how does it actually work?</p>
4
2009-08-18T06:44:12Z
1,292,215
<p><strong>party</strong> simply iterates over the list <strong>feed.entry</strong></p> <p>Take a look at <a href="http://diveintopython-cached.muellerware.org/file%5Fhandling/for%5Floops.html">Dive into Python</a> explainations.</p>
5
2009-08-18T06:54:10Z
[ "python", "for-loop" ]
How does Python for loop work?
1,292,189
<p>I am used to the C++ way of for loops, but the Python loops have left me confused.</p> <pre><code>for party in feed.entry: print party.location.address.text </code></pre> <p>Here <code>party</code> in <code>feed.entry</code>. What does it signify and how does it actually work?</p>
4
2009-08-18T06:44:12Z
1,292,309
<p>In Python, <em>for</em> bucles aren't like the C/C++ ones, they're most like PHP's <em>foreach</em>. What you do isn't iterate like in a <em>while</em> with "(initialization; condition; increment)", it simply iterates over each element in a list (strings are ITERABLE like lists).</p> <p>For example:</p> <pre><code>for number in range(5): print number </code></pre> <p>will output</p> <pre><code>0 1 2 3 4 </code></pre>
3
2009-08-18T07:20:36Z
[ "python", "for-loop" ]
How does Python for loop work?
1,292,189
<p>I am used to the C++ way of for loops, but the Python loops have left me confused.</p> <pre><code>for party in feed.entry: print party.location.address.text </code></pre> <p>Here <code>party</code> in <code>feed.entry</code>. What does it signify and how does it actually work?</p>
4
2009-08-18T06:44:12Z
1,292,388
<p>To add my 0.05$ to the previous answers you might also want to take a look at the <a href="http://docs.python.org/library/functions.html#enumerate">enumerate builtin function</a></p> <pre><code>for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']): print i, season 0 Spring 1 Summer 2 Fall 3 Winter </code></pre>
5
2009-08-18T07:45:23Z
[ "python", "for-loop" ]
How does Python for loop work?
1,292,189
<p>I am used to the C++ way of for loops, but the Python loops have left me confused.</p> <pre><code>for party in feed.entry: print party.location.address.text </code></pre> <p>Here <code>party</code> in <code>feed.entry</code>. What does it signify and how does it actually work?</p>
4
2009-08-18T06:44:12Z
1,292,952
<p>Python's <code>for</code> loop works with <code>iterators</code>, which must implement the <code>iterator</code> protocol. For more details see:</p> <ul> <li><a href="http://stackoverflow.com/questions/19151/build-a-basic-python-iterator/24377#24377">Build a Basic Python Iterator</a></li> </ul>
0
2009-08-18T10:02:07Z
[ "python", "for-loop" ]
How does Python for loop work?
1,292,189
<p>I am used to the C++ way of for loops, but the Python loops have left me confused.</p> <pre><code>for party in feed.entry: print party.location.address.text </code></pre> <p>Here <code>party</code> in <code>feed.entry</code>. What does it signify and how does it actually work?</p>
4
2009-08-18T06:44:12Z
19,322,006
<p>I just wanted to provide a more generic explanation for people new to this.</p> <p>Syntactically, the <code>for</code> loop looks like...</p> <pre><code>for &lt;name to be assigned to&gt; in &lt;some sequence&gt;: &lt;block of code, optionally referencing the name&gt; </code></pre> <p>The interpreter runs the block once for each item in the sequence (anything that can iterated over). Each time it runs the block, it first assigns the next object in the sequence to the name, which can be any valid variable name.</p> <p>Doing <code>for each in (1, 2, 3): print(each)</code> is [more or less] the same as doing...</p> <pre><code>i = 0 sequence = (1, 2, 3) while True: try: each = sequence[i] print(each) i += 1 except IndexError: pass </code></pre> <p>You can also unpack arguments in the assignment part. In the same way that you can do stuff like...</p> <pre><code>a, b = 1, 2 </code></pre> <p>...you can also do stuff like...</p> <pre><code>for a, b in [(1, 2), (3, 4), (5, 6)]: print(a + b) </code></pre> <p>...which prints...</p> <pre><code>3 7 11 </code></pre>
1
2013-10-11T15:35:23Z
[ "python", "for-loop" ]
How to open a file and find the longest length of a line and then print it out
1,292,630
<p>Here's is what I have done so far but the length function isn't working.</p> <pre><code>import string def main(): print " This program reads from a file and then prints out the" print " line with the longest length the line ,or with the highest sum" print " of ASCII values , or the line with the greatest number of words" infile = open("30075165.txt","r") for line in infile: print line infile.close() def length(): maxlength = 0 infile = open("30075165.txt","r") for line in infile: linelength = lengthofline if linelength &gt; maxlength: #If linelength is greater than maxlength value the new value is linelength maxlength = linelength linelength = line print ,maxlinetext infile.close() </code></pre>
1
2009-08-18T08:46:06Z
1,292,665
<p>Try this:</p> <pre><code>def main(): print " This program reads from a file and then prints out the" print " line with the longest length the line ,or with the highest sum" print " of ASCII values , or the line with the greatest number of words" length() def length(): maxlength = 0 maxlinetext = "" infile = open("30075165.txt","r") for line in infile: linelength = len(line) if linelength &gt; maxlength: #If linelength is greater than maxlength value the new value is linelength maxlength = linelength maxlinetext = line print maxlinetext infile.close() </code></pre> <p>EDIT: Added main() function.</p>
1
2009-08-18T08:52:55Z
[ "python" ]
How to open a file and find the longest length of a line and then print it out
1,292,630
<p>Here's is what I have done so far but the length function isn't working.</p> <pre><code>import string def main(): print " This program reads from a file and then prints out the" print " line with the longest length the line ,or with the highest sum" print " of ASCII values , or the line with the greatest number of words" infile = open("30075165.txt","r") for line in infile: print line infile.close() def length(): maxlength = 0 infile = open("30075165.txt","r") for line in infile: linelength = lengthofline if linelength &gt; maxlength: #If linelength is greater than maxlength value the new value is linelength maxlength = linelength linelength = line print ,maxlinetext infile.close() </code></pre>
1
2009-08-18T08:46:06Z
1,292,676
<pre><code>large_line = '' large_line_len = 0 filename = r"C:\tmp\TestFile.txt" with open(filename, 'r') as f: for line in f: if len(line) &gt; large_line_len: large_line_len = len(line) large_line = line print large_line </code></pre> <p>output:</p> <pre><code>This Should Be Largest Line </code></pre> <p>And as a function:</p> <pre><code>def get_longest_line(filename): large_line = '' large_line_len = 0 with open(filename, 'r') as f: for line in f: if len(line) &gt; large_line_len: large_line_len = len(line) large_line = line return large_line print get_longest_line(r"C:\tmp\TestFile.txt") </code></pre> <p>Here is another way, you would need to wrap this in a try/catch for various problems (empty file, etc).</p> <pre><code>def get_longest_line(filename): mydict = {} for line in open(filename, 'r'): mydict[len(line)] = line return mydict[sorted(mydict)[-1]] </code></pre> <p>You also need to decide that happens when you have two 'winning' lines with equal length? Pick first or last? The former function will return the first, the latter will return the last. File contains</p> <pre><code>Small Line Small Line Another Small Line This Should Be Largest Line Small Line </code></pre> <h2>Update</h2> <p>The comment in your original post:</p> <pre><code>print " This program reads from a file and then prints out the" print " line with the longest length the line ,or with the highest sum" print " of ASCII values , or the line with the greatest number of words" </code></pre> <p>Makes me think you are going to scan the file for length of lines, then for ascii sum, then for number of words. It would probably be better to read the file once and then extract what data you need from the findings.</p> <pre><code>def get_file_data(filename): def ascii_sum(line): return sum([ord(x) for x in line]) def word_count(line): return len(line.split(None)) filedata = [(line, len(line), ascii_sum(line), word_count(line)) for line in open(filename, 'r')] return filedata </code></pre> <p>This function will return a list of each line of the file in the format: <code>line, line_length, line_ascii_sum, line_word_count</code></p> <p>This can be used as so:</p> <pre><code>afile = r"C:\Tmp\TestFile.txt" for line, line_len, ascii_sum, word_count in get_file_data(afile): print 'Line: %s, Len: %d, Sum: %d, WordCount: %d' % ( line.strip(), line_len, ascii_sum, word_count) </code></pre> <p>to output:</p> <pre><code>Line: Small Line, Len: 11, Sum: 939, WordCount: 2 Line: Small Line, Len: 11, Sum: 939, WordCount: 2 Line: Another Small Line, Len: 19, Sum: 1692, WordCount: 3 Line: This Should Be Largest Line, Len: 28, Sum: 2450, WordCount: 5 Line: Small Line, Len: 11, Sum: 939, WordCount: 2 </code></pre> <p>You can mix this with Steef's solution like so:</p> <pre><code>&gt;&gt;&gt; afile = r"C:\Tmp\TestFile.txt" &gt;&gt;&gt; file_data = get_file_data(afile) &gt;&gt;&gt; max(file_data, key=lambda line: line[1]) # Longest Line ('This Should Be Largest Line\n', 28, 2450, 5) &gt;&gt;&gt; max(file_data, key=lambda line: line[2]) # Largest ASCII sum ('This Should Be Largest Line\n', 28, 2450, 5) &gt;&gt;&gt; max(file_data, key=lambda line: line[3]) # Most Words ('This Should Be Largest Line\n', 28, 2450, 5) </code></pre>
4
2009-08-18T08:55:54Z
[ "python" ]
How to open a file and find the longest length of a line and then print it out
1,292,630
<p>Here's is what I have done so far but the length function isn't working.</p> <pre><code>import string def main(): print " This program reads from a file and then prints out the" print " line with the longest length the line ,or with the highest sum" print " of ASCII values , or the line with the greatest number of words" infile = open("30075165.txt","r") for line in infile: print line infile.close() def length(): maxlength = 0 infile = open("30075165.txt","r") for line in infile: linelength = lengthofline if linelength &gt; maxlength: #If linelength is greater than maxlength value the new value is linelength maxlength = linelength linelength = line print ,maxlinetext infile.close() </code></pre>
1
2009-08-18T08:46:06Z
1,292,696
<pre><code>linelength = lengthofline # bug? </code></pre> <p>It should be:</p> <pre><code>linelength = len(line) # fix </code></pre>
0
2009-08-18T08:58:49Z
[ "python" ]
How to open a file and find the longest length of a line and then print it out
1,292,630
<p>Here's is what I have done so far but the length function isn't working.</p> <pre><code>import string def main(): print " This program reads from a file and then prints out the" print " line with the longest length the line ,or with the highest sum" print " of ASCII values , or the line with the greatest number of words" infile = open("30075165.txt","r") for line in infile: print line infile.close() def length(): maxlength = 0 infile = open("30075165.txt","r") for line in infile: linelength = lengthofline if linelength &gt; maxlength: #If linelength is greater than maxlength value the new value is linelength maxlength = linelength linelength = line print ,maxlinetext infile.close() </code></pre>
1
2009-08-18T08:46:06Z
1,292,741
<p>Python might not be the right tool for this job.</p> <pre><code>$ awk 'length() &gt; n { n = length(); x = $0 } END { print x }' 30075165.txt </code></pre>
0
2009-08-18T09:06:53Z
[ "python" ]
How to open a file and find the longest length of a line and then print it out
1,292,630
<p>Here's is what I have done so far but the length function isn't working.</p> <pre><code>import string def main(): print " This program reads from a file and then prints out the" print " line with the longest length the line ,or with the highest sum" print " of ASCII values , or the line with the greatest number of words" infile = open("30075165.txt","r") for line in infile: print line infile.close() def length(): maxlength = 0 infile = open("30075165.txt","r") for line in infile: linelength = lengthofline if linelength &gt; maxlength: #If linelength is greater than maxlength value the new value is linelength maxlength = linelength linelength = line print ,maxlinetext infile.close() </code></pre>
1
2009-08-18T08:46:06Z
1,292,743
<p>For Python 2.5 and up</p> <pre><code>print max(open(your_filename, 'r'), key=len) </code></pre>
19
2009-08-18T09:06:59Z
[ "python" ]
How to open a file and find the longest length of a line and then print it out
1,292,630
<p>Here's is what I have done so far but the length function isn't working.</p> <pre><code>import string def main(): print " This program reads from a file and then prints out the" print " line with the longest length the line ,or with the highest sum" print " of ASCII values , or the line with the greatest number of words" infile = open("30075165.txt","r") for line in infile: print line infile.close() def length(): maxlength = 0 infile = open("30075165.txt","r") for line in infile: linelength = lengthofline if linelength &gt; maxlength: #If linelength is greater than maxlength value the new value is linelength maxlength = linelength linelength = line print ,maxlinetext infile.close() </code></pre>
1
2009-08-18T08:46:06Z
1,292,751
<p>My solution (also works in Python 2.5):</p> <pre><code>import os.path def getLongestLineFromFile(fileName): longestLine = "" if not os.path.exists(fileName): raise "File not found" file = open(fileName, "r") for line in file: if len(line) &gt; len(longestLine): longestLine = line return longestLine if __name__ == "__main__": print getLongestLineFromFile("input.data") </code></pre> <p>Example "input.data" contents:</p> <blockquote> <pre><code>111111111 1111111111111111111111 111111111 22222222222222222 4444444444444444444444444444444 444444444444444 5555 </code></pre> </blockquote>
0
2009-08-18T09:07:45Z
[ "python" ]
How to automate browsing using python?
1,292,817
<p>suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to do this without invoking any web browser. It hast to be a pure script.</p> <p>Is there a module available in python, which can help me do that?<br /> thanks</p>
17
2009-08-18T09:23:10Z
1,292,854
<p>You likely want <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a>. It can handle things like HTTPS, cookies, and authentication. You will probably also want <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> to help parse the HTML pages.</p>
0
2009-08-18T09:31:19Z
[ "python", "browser-automation" ]
How to automate browsing using python?
1,292,817
<p>suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to do this without invoking any web browser. It hast to be a pure script.</p> <p>Is there a module available in python, which can help me do that?<br /> thanks</p>
17
2009-08-18T09:23:10Z
1,292,876
<p>There are plenty of built in python modules that whould help with this. For example <a href="http://docs.python.org/library/urllib.html" rel="nofollow">urllib</a> and <a href="http://docs.python.org/library/htmllib.html" rel="nofollow">htmllib</a>.</p> <p>The problem will be simpler if you change the way you're approaching it. You say you want to "fill some forms, click submit button, send the data back to server, recieve the response", which sounds like a four stage process.</p> <p>In fact, what you need to do is post some data to a webserver and get a response.</p> <p>This is as simple as:</p> <pre><code>&gt;&gt;&gt; import urllib &gt;&gt;&gt; params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) &gt;&gt;&gt; f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params) &gt;&gt;&gt; print f.read() </code></pre> <p>(example taken from the urllib docs).</p> <p>What you do with the response depends on how complex the HTML is and what you want to do with it. You might get away with parsing it using a regular expression or two, or you can use the htmllib.HTMLParser class, or maybe a higher level more flexible parser like <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>.</p>
2
2009-08-18T09:38:11Z
[ "python", "browser-automation" ]
How to automate browsing using python?
1,292,817
<p>suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to do this without invoking any web browser. It hast to be a pure script.</p> <p>Is there a module available in python, which can help me do that?<br /> thanks</p>
17
2009-08-18T09:23:10Z
1,292,892
<p>You can also take a look at <a href="http://wwwsearch.sourceforge.net/mechanize/">mechanize</a>. Its meant to handle <em>"stateful programmatic web browsing"</em> (as per their site).</p>
13
2009-08-18T09:43:36Z
[ "python", "browser-automation" ]
How to automate browsing using python?
1,292,817
<p>suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to do this without invoking any web browser. It hast to be a pure script.</p> <p>Is there a module available in python, which can help me do that?<br /> thanks</p>
17
2009-08-18T09:23:10Z
1,292,894
<p>You may have a look at these slides from the <a href="http://www.pycon.it/static/stuff/slides/tecniche-di-scraping-in-python.pdf" rel="nofollow">last italian pycon</a> (pdf): The author listed most of the library for doing scraping and autoted browsing in python. so you may have a look at it.</p> <p>I like very much <a href="http://twill.idyll.org/" rel="nofollow">twill</a> (which has already been suggested), which has been developed by one of the authors of nose and it is specifically aimed at testing web sites.</p>
0
2009-08-18T09:44:37Z
[ "python", "browser-automation" ]
How to automate browsing using python?
1,292,817
<p>suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to do this without invoking any web browser. It hast to be a pure script.</p> <p>Is there a module available in python, which can help me do that?<br /> thanks</p>
17
2009-08-18T09:23:10Z
1,293,086
<p>Internet Explorer specific, but rather good:</p> <p><a href="http://pamie.sourceforge.net/" rel="nofollow">http://pamie.sourceforge.net/</a></p> <p>The advantage compared to urllib/BeautifulSoup is that it executes Javascript as well since it uses IE.</p>
0
2009-08-18T10:36:51Z
[ "python", "browser-automation" ]
How to automate browsing using python?
1,292,817
<p>suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to do this without invoking any web browser. It hast to be a pure script.</p> <p>Is there a module available in python, which can help me do that?<br /> thanks</p>
17
2009-08-18T09:23:10Z
3,486,971
<p>selenium will do exactly what you want and it handles javascript</p>
14
2010-08-15T10:19:57Z
[ "python", "browser-automation" ]
How to automate browsing using python?
1,292,817
<p>suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to do this without invoking any web browser. It hast to be a pure script.</p> <p>Is there a module available in python, which can help me do that?<br /> thanks</p>
17
2009-08-18T09:23:10Z
3,988,708
<p>httplib2 + beautifulsoup</p> <p>Use firefox + firebug + httpreplay to see what the javascript passes to and from the browser from the website. Using httplib2 you can essentially do the same via post and get</p>
0
2010-10-21T14:45:39Z
[ "python", "browser-automation" ]
How to automate browsing using python?
1,292,817
<p>suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to do this without invoking any web browser. It hast to be a pure script.</p> <p>Is there a module available in python, which can help me do that?<br /> thanks</p>
17
2009-08-18T09:23:10Z
6,295,138
<p><a href="http://code.google.com/p/selenium/" rel="nofollow">Selenium2</a> includes webdriver, which has <a href="http://pypi.python.org/pypi/selenium/2.0rc2" rel="nofollow">python bindings</a> and allows one to use the headless htmlUnit driver, or switch to firefox or chrome for graphical debugging.</p>
1
2011-06-09T15:14:40Z
[ "python", "browser-automation" ]
How to automate browsing using python?
1,292,817
<p>suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to do this without invoking any web browser. It hast to be a pure script.</p> <p>Is there a module available in python, which can help me do that?<br /> thanks</p>
17
2009-08-18T09:23:10Z
19,256,265
<p>All answers are old, I recommend and I am a big fan of <a href="http://docs.python-requests.org/en/latest/" rel="nofollow">requests</a></p> <p>From homepage:</p> <blockquote> <p>Python’s standard urllib2 module provides most of the HTTP capabilities you need, but the API is thoroughly broken. It was built for a different time — and a different web. It requires an enormous amount of work (even method overrides) to perform the simplest of tasks.</p> <p>Things shouldn't be this way. Not in Python.</p> </blockquote>
7
2013-10-08T19:11:27Z
[ "python", "browser-automation" ]
How to automate browsing using python?
1,292,817
<p>suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to do this without invoking any web browser. It hast to be a pure script.</p> <p>Is there a module available in python, which can help me do that?<br /> thanks</p>
17
2009-08-18T09:23:10Z
19,666,844
<p>I think the best solutions is the mix of <a href="http://www.python-requests.org/en/latest/">requests</a> and <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a>, I just wanted to update the question so it can be kept updated.</p>
6
2013-10-29T18:55:48Z
[ "python", "browser-automation" ]
How to automate browsing using python?
1,292,817
<p>suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to do this without invoking any web browser. It hast to be a pure script.</p> <p>Is there a module available in python, which can help me do that?<br /> thanks</p>
17
2009-08-18T09:23:10Z
20,245,252
<p>Selenium <a href="http://www.seleniumhq.org/" rel="nofollow">http://www.seleniumhq.org/</a> is the best solution for me. you can code it with python, java, or anything programming language you like with ease. and easy simulation that convert into program.</p>
2
2013-11-27T14:36:59Z
[ "python", "browser-automation" ]
How to automate browsing using python?
1,292,817
<p>suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to do this without invoking any web browser. It hast to be a pure script.</p> <p>Is there a module available in python, which can help me do that?<br /> thanks</p>
17
2009-08-18T09:23:10Z
20,679,640
<p>The best solution that i have found (and currently implementing) is : - scripts in python using selenium webdriver - PhantomJS headless browser (if firefox is used you will have a GUI and will be slower)</p>
1
2013-12-19T10:48:59Z
[ "python", "browser-automation" ]
How to automate browsing using python?
1,292,817
<p>suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to do this without invoking any web browser. It hast to be a pure script.</p> <p>Is there a module available in python, which can help me do that?<br /> thanks</p>
17
2009-08-18T09:23:10Z
21,130,760
<p>Do not forget <a href="https://pypi.python.org/pypi/zope.testbrowser" rel="nofollow">zope.testbrowser</a> which is wrapper around <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a> .</p> <blockquote> <p>zope.testbrowser provides an easy-to-use programmable web browser with special focus on testing.</p> </blockquote>
2
2014-01-15T06:46:06Z
[ "python", "browser-automation" ]
How to automate browsing using python?
1,292,817
<p>suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to do this without invoking any web browser. It hast to be a pure script.</p> <p>Is there a module available in python, which can help me do that?<br /> thanks</p>
17
2009-08-18T09:23:10Z
27,397,694
<p>HTMLUNIT is the package if you're a java developer. <a href="http://htmlunit.sourceforge.net/apidocs/index.html" rel="nofollow">http://htmlunit.sourceforge.net/apidocs/index.html</a></p>
1
2014-12-10T09:43:08Z
[ "python", "browser-automation" ]
How to automate browsing using python?
1,292,817
<p>suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to do this without invoking any web browser. It hast to be a pure script.</p> <p>Is there a module available in python, which can help me do that?<br /> thanks</p>
17
2009-08-18T09:23:10Z
28,440,512
<p>I have found the <a href="https://addons.mozilla.org/en-US/firefox/addon/imacros-for-firefox/" rel="nofollow">iMacros Firefox plugin</a> (which is free) to work very well.</p> <p>It can be automated with Python using Windows COM object interfaces. Here's some example code from <a href="http://wiki.imacros.net/Python" rel="nofollow">http://wiki.imacros.net/Python</a>. It requires <a href="http://sourceforge.net/projects/pywin32/files/" rel="nofollow">Python Windows Extensions</a>:</p> <pre><code>import win32com.client def Hello(): w=win32com.client.Dispatch("imacros") w.iimInit("", 1) w.iimPlay("Demo\\FillForm") if __name__=='__main__': Hello() </code></pre>
1
2015-02-10T19:48:20Z
[ "python", "browser-automation" ]
Renaming objects with Wing IDE
1,292,931
<p>I am just transitioning from Eclipse to Wing IDE for my Python code. In Eclipse I had an option to "rename" objects. I could take any object defined in my code, it could be a variable or a function or a method or whatever, and I could rename it automatically in all the files that referenced it.</p> <p>Is there a similar feature in Wing IDE?</p>
3
2009-08-18T09:56:38Z
1,293,438
<p>The refactoruing is a feature asked for <a href="http://wingware.com/pipermail/wingide-users/2002-May/001102.html" rel="nofollow">since 2002</a>, but even then, the answer was already:</p> <p>"<a href="http://www.wingware.com/doc/intro/tutorial-search" rel="nofollow">search and replace</a>"</p> <blockquote> <p>BTW, one somewhat related thing we're doing is adding better global replace. <code>[...]</code> This isn't informed by source analysis but it's still a useful tool for some kinds of refactoring (like renaming poorly named variables or classes).</p> </blockquote> <p>So their advanced search, even based on regex, is still the refactoring of the day for this 3.1.8 Wing IDE: as <a href="http://wingware.com/pipermail/wingide-users/2007-July/004506.html" rel="nofollow">said in 2007</a>, the 3.0, 3.1 releases were focused on debugging even though:</p> <blockquote> <p>Refactoring is in our plans for future releases.</p> </blockquote> <p>(but not yet for the <a href="http://wingware.com/wingide/beta" rel="nofollow">upcoming 3.2</a>, it seems: see here the <a href="http://wingware.com/pub/wingide/prerelease/3.2.0-b3/CHANGELOG.txt" rel="nofollow">full CHANGELOG</a>)</p> <p><img src="http://www.wingware.com/images/doc/en/intro/search-regex.png" alt="alt text" /></p>
4
2009-08-18T12:05:26Z
[ "python", "eclipse", "ide" ]
Renaming objects with Wing IDE
1,292,931
<p>I am just transitioning from Eclipse to Wing IDE for my Python code. In Eclipse I had an option to "rename" objects. I could take any object defined in my code, it could be a variable or a function or a method or whatever, and I could rename it automatically in all the files that referenced it.</p> <p>Is there a similar feature in Wing IDE?</p>
3
2009-08-18T09:56:38Z
5,147,647
<p>WingIDE 4 now has support for refactoring.</p>
0
2011-02-28T21:14:01Z
[ "python", "eclipse", "ide" ]
Display Django form inputs on thanks page
1,292,951
<p>I'm attempting to take 4-5 fields from a large django form and display them on the thanks page.</p> <p>I want to disply the values with a good degree of control, as i'll be building an iFrame with parameterd querystrings based on the form inputs.</p> <p>Currently I have:</p> <p>forms.py ----</p> <pre><code>-*- encoding: utf-8 -*- from django import forms from django.forms import extras, ModelForm from django.utils.safestring import mark_safe from siteapp.compare.models import Compare HOWMUCH_CHOICES = ( ('', '--------------------------'), ('20000', '20,000'), ('30000', '30,000'), ... ('2000000', '2,000,000'), ) HOWLONG_CHOICES = ( ('', '--------------------------'), ('1', '1 Year'), ... ('39', '39 Years'), ('40', '40 Years'), ) </code></pre> <p>...etc.</p> <pre><code>class ComparisonForm(forms.Form): js = mark_safe(u"document.compareForm.how_much.selectedindex = 4;") how_much = forms.ChoiceField(choices=HOWMUCH_CHOICES, widget=forms.Select(attrs={'onMouseOver':'setDefaults()','class':'required validate-selection','title':'Select value of cover required','onLoad': js})) how_long = forms.ChoiceField(choices=HOWLONG_CHOICES, widget=forms.Select(attrs={'class':'required validate-selection','title':'Select length of cover required'})) who_for = forms.ChoiceField(choices=WHOFOR_CHOICES, widget=forms.Select(attrs={'class':'required validate-selection','title':'Select whether you require cover for a partner also'})) ... class Meta: model = Compare </code></pre> <p>models.py -----</p> <pre><code>class Compare(models.Model): how_much = models.CharField(max_length=28,choices=HOWMUCH_CHOICES#,default='100000' ) how_long = models.CharField(max_length=28,choices=HOWLONG_CHOICES) who_for = models.CharField(max_length=28,choices=WHOFOR_CHOICES) ... partner_date_of_birth = models.DateField(blank=True) def __unicode__(self): return self.name </code></pre> <p>views.py----</p> <pre><code>def qc_comparison(request): return render_to_response('compare/compare.html', locals(), context_instance=RequestContext(request)) </code></pre> <p>urls.py----</p> <pre><code>(r'^compare/thanks/$', 'django.views.generic.simple.direct_to_template', {'template': 'compare/thanks.html'}), </code></pre> <p>I'm trying to dig out the best way to do this from the documentation, but it's not clear how to pass the variables correctly to a thanks page. </p>
0
2009-08-18T10:02:02Z
1,293,021
<p>The values available to the template are provided by the view.</p> <p>The <code>render_to_response</code> function provides a dictionary of values that are passed to the template. See <a href="http://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render-to-response" rel="nofollow">this</a>.</p> <p>For no good reason, you've provided <code>locals()</code>. Not sure why.</p> <p>You want to provide a dictionary like <code>request.POST</code> -- not <code>locals()</code>.</p> <p><hr /></p> <p>Your <code>locals()</code> will have <code>request</code>. That means your template can use <code>request.POST</code> to access the form.</p>
0
2009-08-18T10:16:29Z
[ "python", "django", "forms" ]
Display Django form inputs on thanks page
1,292,951
<p>I'm attempting to take 4-5 fields from a large django form and display them on the thanks page.</p> <p>I want to disply the values with a good degree of control, as i'll be building an iFrame with parameterd querystrings based on the form inputs.</p> <p>Currently I have:</p> <p>forms.py ----</p> <pre><code>-*- encoding: utf-8 -*- from django import forms from django.forms import extras, ModelForm from django.utils.safestring import mark_safe from siteapp.compare.models import Compare HOWMUCH_CHOICES = ( ('', '--------------------------'), ('20000', '20,000'), ('30000', '30,000'), ... ('2000000', '2,000,000'), ) HOWLONG_CHOICES = ( ('', '--------------------------'), ('1', '1 Year'), ... ('39', '39 Years'), ('40', '40 Years'), ) </code></pre> <p>...etc.</p> <pre><code>class ComparisonForm(forms.Form): js = mark_safe(u"document.compareForm.how_much.selectedindex = 4;") how_much = forms.ChoiceField(choices=HOWMUCH_CHOICES, widget=forms.Select(attrs={'onMouseOver':'setDefaults()','class':'required validate-selection','title':'Select value of cover required','onLoad': js})) how_long = forms.ChoiceField(choices=HOWLONG_CHOICES, widget=forms.Select(attrs={'class':'required validate-selection','title':'Select length of cover required'})) who_for = forms.ChoiceField(choices=WHOFOR_CHOICES, widget=forms.Select(attrs={'class':'required validate-selection','title':'Select whether you require cover for a partner also'})) ... class Meta: model = Compare </code></pre> <p>models.py -----</p> <pre><code>class Compare(models.Model): how_much = models.CharField(max_length=28,choices=HOWMUCH_CHOICES#,default='100000' ) how_long = models.CharField(max_length=28,choices=HOWLONG_CHOICES) who_for = models.CharField(max_length=28,choices=WHOFOR_CHOICES) ... partner_date_of_birth = models.DateField(blank=True) def __unicode__(self): return self.name </code></pre> <p>views.py----</p> <pre><code>def qc_comparison(request): return render_to_response('compare/compare.html', locals(), context_instance=RequestContext(request)) </code></pre> <p>urls.py----</p> <pre><code>(r'^compare/thanks/$', 'django.views.generic.simple.direct_to_template', {'template': 'compare/thanks.html'}), </code></pre> <p>I'm trying to dig out the best way to do this from the documentation, but it's not clear how to pass the variables correctly to a thanks page. </p>
0
2009-08-18T10:02:02Z
1,332,943
<p>I'm not sure if I understand what you are trying to do.</p> <p>But if you want to render form values in plain text you can try <a href="http://github.com/muhuk/django-renderformplain/tree/master" rel="nofollow">django-renderformplain</a>. Just initalize your form with POST (or GET) data as you would in any other form processing view, and pass your <strong>form</strong> instance in the context.</p>
0
2009-08-26T07:30:28Z
[ "python", "django", "forms" ]
Storing dynamically generated code as string or as code object?
1,292,994
<p>I'm hacking a little template engine. I've a class (pompously named the <em>template compiler</em>) that produce a string of dynamically generated code.</p> <p>for instance :</p> <pre><code>def dynamic_function(arg): #statement return rendered_template </code></pre> <p>At rendering time, I call the built-in function <em>exec</em> against this code, with a custom <em>globals</em> dictionary (in order to control as mush as possible the code inserted into the template by a potential malicious user).</p> <p>But, I need to cache the compiled template to avoid compiling it each execution. I wonder if it's better to store the string as plain text and load it each time or use <em>compile</em> to produce code_object and store that object (using the shelve module for example).</p> <p>Maybe it worth mentioning that ultimately I would like to make my template engine thread safe.</p> <p>Thank for reading ! Thomas</p> <p>edit : as S.Lott is underlining better doesn't have a sense itself. I mean by better faster, consume less memory simpler and easier debugging. Of course, more and tastier free coffee would have been even better.</p>
0
2009-08-18T10:10:41Z
1,293,039
<p>Mako template library caches the compiled template as a python module and uses the built in <code>imp</code> module to handle byte-code caching and code loading. This seems reasonably robust to changes in the interpreter, fast and easily debuggable (you can view the source of the generated code in the cache).</p> <p>See the <a href="http://www.makotemplates.org/trac/browser/mako/trunk/lib/mako/template.py#L61" rel="nofollow">mako.template</a> module for how it handles this.</p>
0
2009-08-18T10:22:21Z
[ "python", "exec" ]
Storing dynamically generated code as string or as code object?
1,292,994
<p>I'm hacking a little template engine. I've a class (pompously named the <em>template compiler</em>) that produce a string of dynamically generated code.</p> <p>for instance :</p> <pre><code>def dynamic_function(arg): #statement return rendered_template </code></pre> <p>At rendering time, I call the built-in function <em>exec</em> against this code, with a custom <em>globals</em> dictionary (in order to control as mush as possible the code inserted into the template by a potential malicious user).</p> <p>But, I need to cache the compiled template to avoid compiling it each execution. I wonder if it's better to store the string as plain text and load it each time or use <em>compile</em> to produce code_object and store that object (using the shelve module for example).</p> <p>Maybe it worth mentioning that ultimately I would like to make my template engine thread safe.</p> <p>Thank for reading ! Thomas</p> <p>edit : as S.Lott is underlining better doesn't have a sense itself. I mean by better faster, consume less memory simpler and easier debugging. Of course, more and tastier free coffee would have been even better.</p>
0
2009-08-18T10:10:41Z
1,293,107
<p>You don't mention where you are going to store these templates, but if you are persisting them "permanently", keep in mind that Python doesn't guarantee byte-code compatibility across major versions. So either choose a method that does guarantee compatibility (like storing the source code), or also store enough information alongside the compiled template that you can throw away the compiled template when it is invalid.</p> <p>The same goes for the marshal module, for example: a value marshaled with Python 2.5 is not promised to be readable with Python 2.6.</p>
2
2009-08-18T10:42:21Z
[ "python", "exec" ]
Storing dynamically generated code as string or as code object?
1,292,994
<p>I'm hacking a little template engine. I've a class (pompously named the <em>template compiler</em>) that produce a string of dynamically generated code.</p> <p>for instance :</p> <pre><code>def dynamic_function(arg): #statement return rendered_template </code></pre> <p>At rendering time, I call the built-in function <em>exec</em> against this code, with a custom <em>globals</em> dictionary (in order to control as mush as possible the code inserted into the template by a potential malicious user).</p> <p>But, I need to cache the compiled template to avoid compiling it each execution. I wonder if it's better to store the string as plain text and load it each time or use <em>compile</em> to produce code_object and store that object (using the shelve module for example).</p> <p>Maybe it worth mentioning that ultimately I would like to make my template engine thread safe.</p> <p>Thank for reading ! Thomas</p> <p>edit : as S.Lott is underlining better doesn't have a sense itself. I mean by better faster, consume less memory simpler and easier debugging. Of course, more and tastier free coffee would have been even better.</p>
0
2009-08-18T10:10:41Z
1,293,209
<p>Personally, i'd store text. You can look at text with an editor or whatever, which will make debugging and mucking about easier. It's also vastly easier to write unit tests for, if you want to test that the contents of the cache file are what you expect.</p> <p>Later, <em>if</em> you find that your system isn't fast enough, and <em>if</em> profiling reveals that parsing the cached templates is taking a lot of time, you can try switching to storing bytecode - but only then. As long as the storage mechanism is properly encapsulated, this change should be fairly painless.</p>
1
2009-08-18T11:07:18Z
[ "python", "exec" ]
bulk insert in db table
1,293,056
<p>I'm having an array I want to insert in a single query in a table. Any idea?</p>
-2
2009-08-18T10:26:36Z
1,293,159
<p>If you are using PostgreSQL, you can use the <a href="http://www.postgresql.org/docs/8.1/interactive/sql-copy.html" rel="nofollow">COPY statement</a>.</p>
0
2009-08-18T10:57:01Z
[ "python", "database" ]
bulk insert in db table
1,293,056
<p>I'm having an array I want to insert in a single query in a table. Any idea?</p>
-2
2009-08-18T10:26:36Z
1,293,223
<p>If you are using dbapi to access the database, then the connection.executemany() method works.</p> <pre><code>con.executemany("INSERT INTO some_table (field) VALUES (?)", [(v,) for v in your_array]) </code></pre> <p>The format of the bindparameter depends on the database, sqlite uses ?, mysql uses %s, postgresl uses %s or %(key)s if passing in dicts. To abstract this you can use SQLAlchemy:</p> <pre><code>import sqlalchemy as sa metadata = sa.MetaData(sa.create_engine(database_url)) some_table = Table('some_table', metadata, autoload=True) some_table.insert([{'field': v} for v in your_array]).execute() </code></pre>
3
2009-08-18T11:11:13Z
[ "python", "database" ]
bulk insert in db table
1,293,056
<p>I'm having an array I want to insert in a single query in a table. Any idea?</p>
-2
2009-08-18T10:26:36Z
1,293,245
<p>As uneffective (individual inserts) one-liner:</p> <pre><code>data = [{'id': 1, 'x': 2, 'y': 4}, {'somethig': 'other', 'otherfield': 5, 'y': 6}] table = 'table_name' connection = connect() # DBAPI connection map(connection.cursor().execute, ('INSERT INTO %s (%s) VALUES (%s)' % ('table', ','.join(x), ','.join(['%s'] * len(x))) for x in data), (x.values() for x in data)) </code></pre>
1
2009-08-18T11:16:37Z
[ "python", "database" ]
Replace AppEngine Devserver With Spawning (BaseHTTPRequestHandler as WSGI)
1,293,249
<p>I'm looking to replace AppEngine's devserver with <a href="http://pypi.python.org/pypi/Spawning/0.8.10" rel="nofollow">spawning</a>. Spawning handles standard wsgi handlers, just like appengine, so running your app on it is easy.</p> <p>But the devserver takes into account your app.yaml file that has url redirects etc. I've been going through the devserver code and it is pretty easy to get the BaseHTTPRequestHandler like this:</p> <pre><code>from google.appengine.tools.dev_appserver import CreateRequestHandler dev = CreateRequestHandler(os.path.dirname(__file__), '', require_indexes=False, static_caching=True) </code></pre> <p>But the BaseHTTPRequestHandler is not a WSGI app, so my guess is I need to put something around it to make it work. Any hints?</p>
1
2009-08-18T11:16:57Z
1,366,653
<p>I don't think you're going to be able to pull out a part of the dev_appserver and use it in a custom WSGI server quite so easily. The dev_appserver does a lot of 'magic', and it isn't really structured to be pulled out and used as a WSGI wrapper in another server (more's the pity).</p> <p>You may want to check out T<a href="http://code.google.com/p/twistedae/" rel="nofollow">wistedAE</a>, which is working on creating an alternate serving environment; if you really want to use spawning, you can probably use TwistedAE's work as a basis.</p> <p>That said, if you do want to do it yourself, there's a couple of options: </p> <ol> <li>You can write your own shim to interface WSGI with the class returned by CreateRequestHandler. In that case, you need to replicate the interface in <a href="http://docs.python.org/library/basehttpserver.html" rel="nofollow">BaseHTTPServer</a>.BaseHTTPRequestHandler from the Python SDK. Converting WSGI to that, just so the dev_appserver code can convert it back seems a bit perverse, though.</li> <li>You can rip out the code from the _HandleRequest method of DevAppServerRequestHandler, modify it to work with WSGI, and create a WSGI app from that (probably your best bet if you want to DIY).</li> <li>You can start from scratch, which I believe is the approach taken by TwistedAE.</li> </ol> <p>One thing to bear in mind whatever you do: App Engine explicitly expects a single-threaded environment for its apps. Don't use a multithreaded approach if you want apps to work the same locally as they do in production or on the dev_appserver!</p>
2
2009-09-02T09:24:15Z
[ "python", "google-app-engine", "wsgi" ]
How to convince my boss to use Django?
1,293,361
<p>I have an unusual problem: I have to convince my superiors to use Django for our new project. Alternative is some PHP framework. I've programmed in PHP for 2 years and then switched to Python and have about 3 years of experience in it. However I'm not too good in business speech. </p> <p>I know all the technical pros and cons but when it comes to discussing business issues things blur a bit.</p> <p>EDIT:</p> <p>Reasons I want to use Python + Django:</p> <ul> <li>experience in Django</li> <li>beauty of pythonic code (and all it's benefits)</li> <li>lots of third party libraries</li> <li>efficiency</li> <li>less code = less bugs</li> </ul> <p>Reasons why my new boss wants to use PHP:</p> <ul> <li>he knows it</li> <li>he can estimate on his own</li> <li>he doesn't know Python</li> </ul> <p>@Vinko Vrsalovic: All requirements for both technologies are met.</p> <ul> <li>we have both our own servers and external Python hosting</li> <li>PHP costs of course less, however the difference is really tiny in comparison to support cost</li> <li>we have suitable resources for both PHP and Python projects</li> </ul> <p>I think problem is with my <a href="http://en.wikipedia.org/wiki/Project%5Fmanager">PM</a>: he is afraid of new technologies. For him it's something new. So quoting the basic question from Robertos answer "why can't we just use the old system?".</p> <p>I think I'm just too old :D to write a prototype in my free time. However this had worked a few times in past.</p>
18
2009-08-18T11:47:10Z
1,293,401
<p>People like to see tangible results. <em>On your own time</em> implement a small portion of the project using Django that can demonstrate what you believe to be some of the advantages of switching the project to Django. Besides demonstrating technical advantages, it will demonstrate your commitment to the idea.</p> <p>From your boss' point of view, switching frameworks is a risk that she will have to explain. So you will need to show that you are motivated and committed to making it work.</p> <p>Here is a somewhat related article by Joel Spolsky about <a href="http://www.joelonsoftware.com/articles/fog0000000332.html" rel="nofollow">Getting Things Done When You're Only a Grunt</a>. You might need to take a longer term approach to introducing Python and Django. Perhaps you could write some scripts in python that other people on the team will find useful. Maybe you could implement an internal tool using Django, which people will start using.</p>
7
2009-08-18T11:57:46Z
[ "php", "python", "django" ]
How to convince my boss to use Django?
1,293,361
<p>I have an unusual problem: I have to convince my superiors to use Django for our new project. Alternative is some PHP framework. I've programmed in PHP for 2 years and then switched to Python and have about 3 years of experience in it. However I'm not too good in business speech. </p> <p>I know all the technical pros and cons but when it comes to discussing business issues things blur a bit.</p> <p>EDIT:</p> <p>Reasons I want to use Python + Django:</p> <ul> <li>experience in Django</li> <li>beauty of pythonic code (and all it's benefits)</li> <li>lots of third party libraries</li> <li>efficiency</li> <li>less code = less bugs</li> </ul> <p>Reasons why my new boss wants to use PHP:</p> <ul> <li>he knows it</li> <li>he can estimate on his own</li> <li>he doesn't know Python</li> </ul> <p>@Vinko Vrsalovic: All requirements for both technologies are met.</p> <ul> <li>we have both our own servers and external Python hosting</li> <li>PHP costs of course less, however the difference is really tiny in comparison to support cost</li> <li>we have suitable resources for both PHP and Python projects</li> </ul> <p>I think problem is with my <a href="http://en.wikipedia.org/wiki/Project%5Fmanager">PM</a>: he is afraid of new technologies. For him it's something new. So quoting the basic question from Robertos answer "why can't we just use the old system?".</p> <p>I think I'm just too old :D to write a prototype in my free time. However this had worked a few times in past.</p>
18
2009-08-18T11:47:10Z
1,293,405
<p>Why do you <em>have</em> to convince your boss to use Django?</p> <p>Your boss should understand that it's in his best interest to work in what the people he'll be employing know best. </p> <p>But, how can you tell that Django is really the best suit all things considered? </p> <p>For example:</p> <ul> <li>Are the servers in-house? do the sysadmins know how to maintain servers for Django? </li> <li>Are the servers in a webhost, do you know how much does it cost to have a Django webhost versus a PHP one?</li> <li>Are the rest of the team familiarized with Django/Python? If you are a one man team, what if your boss wants to make the team bigger, will he be able to? At what cost? PHP devs abound.</li> <li>Given the PHP framework of choice, can you honestly give some criteria that will translate to dollars (or whatever your currency is) giving Django the advantage? Say, time to market, or some features that will be used and come for free in Django but not in the other alternative? Don't forget that if you are a good programmer you can create good programs in any language.</li> </ul> <p>This are just some things you have to consider before presenting with your boss with a "PHP sucks, let's use Python instead" speech. I understand the feeling but it really might not make sense in the long run in certain cases. If, after all these things are answered (and some more), you can still present a good case for Django, then you should do so. Just don't do what sounds to a business man like fanboy speech.</p> <p>UPDATE: If the only thing stopping you from doing in Django is your boss' fear <strong>and you both know that you can make it work at a comparable cost in infrastructure</strong>, then the only way to alleviate that fear is to jump in and do something like it. You might get authorization for a prototype, for example. No amount of talking will relieve him from his fear, he'll need to see something. You should also tutor him (if possible) on how Python works while you go at it, so he can appreciate the beauty of the beast.</p>
13
2009-08-18T11:58:26Z
[ "php", "python", "django" ]
How to convince my boss to use Django?
1,293,361
<p>I have an unusual problem: I have to convince my superiors to use Django for our new project. Alternative is some PHP framework. I've programmed in PHP for 2 years and then switched to Python and have about 3 years of experience in it. However I'm not too good in business speech. </p> <p>I know all the technical pros and cons but when it comes to discussing business issues things blur a bit.</p> <p>EDIT:</p> <p>Reasons I want to use Python + Django:</p> <ul> <li>experience in Django</li> <li>beauty of pythonic code (and all it's benefits)</li> <li>lots of third party libraries</li> <li>efficiency</li> <li>less code = less bugs</li> </ul> <p>Reasons why my new boss wants to use PHP:</p> <ul> <li>he knows it</li> <li>he can estimate on his own</li> <li>he doesn't know Python</li> </ul> <p>@Vinko Vrsalovic: All requirements for both technologies are met.</p> <ul> <li>we have both our own servers and external Python hosting</li> <li>PHP costs of course less, however the difference is really tiny in comparison to support cost</li> <li>we have suitable resources for both PHP and Python projects</li> </ul> <p>I think problem is with my <a href="http://en.wikipedia.org/wiki/Project%5Fmanager">PM</a>: he is afraid of new technologies. For him it's something new. So quoting the basic question from Robertos answer "why can't we just use the old system?".</p> <p>I think I'm just too old :D to write a prototype in my free time. However this had worked a few times in past.</p>
18
2009-08-18T11:47:10Z
1,293,450
<p>You want to know how to convince a business person?</p> <p>Two words: "<a href="http://blog.cusec.net/2009/01/05/zed-shaw-the-acl-is-dead-cusec-2008/" rel="nofollow">steaks and strippers</a>" (Zed Shaw).</p>
2
2009-08-18T12:08:32Z
[ "php", "python", "django" ]
How to convince my boss to use Django?
1,293,361
<p>I have an unusual problem: I have to convince my superiors to use Django for our new project. Alternative is some PHP framework. I've programmed in PHP for 2 years and then switched to Python and have about 3 years of experience in it. However I'm not too good in business speech. </p> <p>I know all the technical pros and cons but when it comes to discussing business issues things blur a bit.</p> <p>EDIT:</p> <p>Reasons I want to use Python + Django:</p> <ul> <li>experience in Django</li> <li>beauty of pythonic code (and all it's benefits)</li> <li>lots of third party libraries</li> <li>efficiency</li> <li>less code = less bugs</li> </ul> <p>Reasons why my new boss wants to use PHP:</p> <ul> <li>he knows it</li> <li>he can estimate on his own</li> <li>he doesn't know Python</li> </ul> <p>@Vinko Vrsalovic: All requirements for both technologies are met.</p> <ul> <li>we have both our own servers and external Python hosting</li> <li>PHP costs of course less, however the difference is really tiny in comparison to support cost</li> <li>we have suitable resources for both PHP and Python projects</li> </ul> <p>I think problem is with my <a href="http://en.wikipedia.org/wiki/Project%5Fmanager">PM</a>: he is afraid of new technologies. For him it's something new. So quoting the basic question from Robertos answer "why can't we just use the old system?".</p> <p>I think I'm just too old :D to write a prototype in my free time. However this had worked a few times in past.</p>
18
2009-08-18T11:47:10Z
1,293,588
<p>If you have the possibility, you could create a prototype in Django.<br /> Your boss will see it, and will be able to measure the advantages. A good presentation in powerpoint with explained required effort, advantages, etc. may be also a way to increase the chances of success. </p> <p>And, over all, make sure to reply to the question: "why can't we just use the old system".</p>
2
2009-08-18T12:44:43Z
[ "php", "python", "django" ]
How to convince my boss to use Django?
1,293,361
<p>I have an unusual problem: I have to convince my superiors to use Django for our new project. Alternative is some PHP framework. I've programmed in PHP for 2 years and then switched to Python and have about 3 years of experience in it. However I'm not too good in business speech. </p> <p>I know all the technical pros and cons but when it comes to discussing business issues things blur a bit.</p> <p>EDIT:</p> <p>Reasons I want to use Python + Django:</p> <ul> <li>experience in Django</li> <li>beauty of pythonic code (and all it's benefits)</li> <li>lots of third party libraries</li> <li>efficiency</li> <li>less code = less bugs</li> </ul> <p>Reasons why my new boss wants to use PHP:</p> <ul> <li>he knows it</li> <li>he can estimate on his own</li> <li>he doesn't know Python</li> </ul> <p>@Vinko Vrsalovic: All requirements for both technologies are met.</p> <ul> <li>we have both our own servers and external Python hosting</li> <li>PHP costs of course less, however the difference is really tiny in comparison to support cost</li> <li>we have suitable resources for both PHP and Python projects</li> </ul> <p>I think problem is with my <a href="http://en.wikipedia.org/wiki/Project%5Fmanager">PM</a>: he is afraid of new technologies. For him it's something new. So quoting the basic question from Robertos answer "why can't we just use the old system?".</p> <p>I think I'm just too old :D to write a prototype in my free time. However this had worked a few times in past.</p>
18
2009-08-18T11:47:10Z
1,293,613
<p>It would be unfair on your fellow programmers to move to django, if they happen to only know php.</p>
2
2009-08-18T12:49:37Z
[ "php", "python", "django" ]
How to convince my boss to use Django?
1,293,361
<p>I have an unusual problem: I have to convince my superiors to use Django for our new project. Alternative is some PHP framework. I've programmed in PHP for 2 years and then switched to Python and have about 3 years of experience in it. However I'm not too good in business speech. </p> <p>I know all the technical pros and cons but when it comes to discussing business issues things blur a bit.</p> <p>EDIT:</p> <p>Reasons I want to use Python + Django:</p> <ul> <li>experience in Django</li> <li>beauty of pythonic code (and all it's benefits)</li> <li>lots of third party libraries</li> <li>efficiency</li> <li>less code = less bugs</li> </ul> <p>Reasons why my new boss wants to use PHP:</p> <ul> <li>he knows it</li> <li>he can estimate on his own</li> <li>he doesn't know Python</li> </ul> <p>@Vinko Vrsalovic: All requirements for both technologies are met.</p> <ul> <li>we have both our own servers and external Python hosting</li> <li>PHP costs of course less, however the difference is really tiny in comparison to support cost</li> <li>we have suitable resources for both PHP and Python projects</li> </ul> <p>I think problem is with my <a href="http://en.wikipedia.org/wiki/Project%5Fmanager">PM</a>: he is afraid of new technologies. For him it's something new. So quoting the basic question from Robertos answer "why can't we just use the old system?".</p> <p>I think I'm just too old :D to write a prototype in my free time. However this had worked a few times in past.</p>
18
2009-08-18T11:47:10Z
1,293,893
<p>The problem is your Boss who knows PHP but doesn't know Python. And I can imagine that he doesn't want to spend valuable time learning to become familiar with a new technique.</p> <p>About 16 years ago, I've tried to convince my employer to use Delphi (then a new product) instead of some other RAD tools that he was considering. I did my best to convince him and managed to convince him that Gupta SQL-Windows was a bad choice. I also made it clear that Visual Basic would be less powerful than Delphi, since Delphi had much better database-aware components. So he decided to not use VB either. But Delphi was Pascal and he knew nothing about Pascal and couldn't be bothered to learn more about it so he chose to develop in PowerBuilder for new projects. And I decided to move to a company with a smarter Boss who did believe in Delphi. It was frustrating as Hell to try to convince my Boss and I found more than enough satisfaction with my next employer, who did use Delphi. My old employer did manage to write some application with PowerBuilder but it never resulted in the profits he'd expected. (Not a surprise either, since another developer had used two days work just to create an animated trash-bin icon on a button.) His company went chapter 11 and he went on an early retirement...</p> <p>Now, if your Boss doesn't listen to your advise, you have two options: Accept it or leave for another Boss. He <em>is</em> the Boss, so if you continue to nag him about this issue then he might decide you're better off working for someone else...</p>
2
2009-08-18T13:35:27Z
[ "php", "python", "django" ]
How to convince my boss to use Django?
1,293,361
<p>I have an unusual problem: I have to convince my superiors to use Django for our new project. Alternative is some PHP framework. I've programmed in PHP for 2 years and then switched to Python and have about 3 years of experience in it. However I'm not too good in business speech. </p> <p>I know all the technical pros and cons but when it comes to discussing business issues things blur a bit.</p> <p>EDIT:</p> <p>Reasons I want to use Python + Django:</p> <ul> <li>experience in Django</li> <li>beauty of pythonic code (and all it's benefits)</li> <li>lots of third party libraries</li> <li>efficiency</li> <li>less code = less bugs</li> </ul> <p>Reasons why my new boss wants to use PHP:</p> <ul> <li>he knows it</li> <li>he can estimate on his own</li> <li>he doesn't know Python</li> </ul> <p>@Vinko Vrsalovic: All requirements for both technologies are met.</p> <ul> <li>we have both our own servers and external Python hosting</li> <li>PHP costs of course less, however the difference is really tiny in comparison to support cost</li> <li>we have suitable resources for both PHP and Python projects</li> </ul> <p>I think problem is with my <a href="http://en.wikipedia.org/wiki/Project%5Fmanager">PM</a>: he is afraid of new technologies. For him it's something new. So quoting the basic question from Robertos answer "why can't we just use the old system?".</p> <p>I think I'm just too old :D to write a prototype in my free time. However this had worked a few times in past.</p>
18
2009-08-18T11:47:10Z
1,293,964
<p>Bottom line is what it is all about really. How much money does a move to python/django save the company overall in terms of dev effort, testing and support? </p> <p>If you can demonstrate that python out performs php in these areas then its going to make a saving for the company. More savings means better profit margin - that should be pretty convincing.</p>
1
2009-08-18T13:45:07Z
[ "php", "python", "django" ]
How to convince my boss to use Django?
1,293,361
<p>I have an unusual problem: I have to convince my superiors to use Django for our new project. Alternative is some PHP framework. I've programmed in PHP for 2 years and then switched to Python and have about 3 years of experience in it. However I'm not too good in business speech. </p> <p>I know all the technical pros and cons but when it comes to discussing business issues things blur a bit.</p> <p>EDIT:</p> <p>Reasons I want to use Python + Django:</p> <ul> <li>experience in Django</li> <li>beauty of pythonic code (and all it's benefits)</li> <li>lots of third party libraries</li> <li>efficiency</li> <li>less code = less bugs</li> </ul> <p>Reasons why my new boss wants to use PHP:</p> <ul> <li>he knows it</li> <li>he can estimate on his own</li> <li>he doesn't know Python</li> </ul> <p>@Vinko Vrsalovic: All requirements for both technologies are met.</p> <ul> <li>we have both our own servers and external Python hosting</li> <li>PHP costs of course less, however the difference is really tiny in comparison to support cost</li> <li>we have suitable resources for both PHP and Python projects</li> </ul> <p>I think problem is with my <a href="http://en.wikipedia.org/wiki/Project%5Fmanager">PM</a>: he is afraid of new technologies. For him it's something new. So quoting the basic question from Robertos answer "why can't we just use the old system?".</p> <p>I think I'm just too old :D to write a prototype in my free time. However this had worked a few times in past.</p>
18
2009-08-18T11:47:10Z
1,294,098
<p>The best way to persuade people (coworkers, pointy-haired-bosses, peers, etc) is to help them reach their own conclusions by continually demonstrating your awesomeness.</p> <p>Implement a cool prototype-demo of a cool technology on your own time, using the tools you want to use. Then show it off as a "check-out-what-I-did-this-weekend" demonstration. In doing this, you'll plant the seed of your new way of doing things that will inevitably win them over.</p>
1
2009-08-18T14:02:29Z
[ "php", "python", "django" ]
How to convince my boss to use Django?
1,293,361
<p>I have an unusual problem: I have to convince my superiors to use Django for our new project. Alternative is some PHP framework. I've programmed in PHP for 2 years and then switched to Python and have about 3 years of experience in it. However I'm not too good in business speech. </p> <p>I know all the technical pros and cons but when it comes to discussing business issues things blur a bit.</p> <p>EDIT:</p> <p>Reasons I want to use Python + Django:</p> <ul> <li>experience in Django</li> <li>beauty of pythonic code (and all it's benefits)</li> <li>lots of third party libraries</li> <li>efficiency</li> <li>less code = less bugs</li> </ul> <p>Reasons why my new boss wants to use PHP:</p> <ul> <li>he knows it</li> <li>he can estimate on his own</li> <li>he doesn't know Python</li> </ul> <p>@Vinko Vrsalovic: All requirements for both technologies are met.</p> <ul> <li>we have both our own servers and external Python hosting</li> <li>PHP costs of course less, however the difference is really tiny in comparison to support cost</li> <li>we have suitable resources for both PHP and Python projects</li> </ul> <p>I think problem is with my <a href="http://en.wikipedia.org/wiki/Project%5Fmanager">PM</a>: he is afraid of new technologies. For him it's something new. So quoting the basic question from Robertos answer "why can't we just use the old system?".</p> <p>I think I'm just too old :D to write a prototype in my free time. However this had worked a few times in past.</p>
18
2009-08-18T11:47:10Z
1,297,544
<p>I agree with the 'just hack out a demo' school. The beauty of Django is that you can set up a quick project with SQLite, define the models, and then instantly have a database API, a slick admin and databrowse to play with. If databrowse doesn't cut it, write just enough views to demonstrate django's benefits. </p> <p>I know PHP people that are queasy about taking on a large-ish content management project, but django makes those kinds of projects relatively easy. When they see what you did in a few hours, they may come around.</p>
0
2009-08-19T02:28:15Z
[ "php", "python", "django" ]
How to convince my boss to use Django?
1,293,361
<p>I have an unusual problem: I have to convince my superiors to use Django for our new project. Alternative is some PHP framework. I've programmed in PHP for 2 years and then switched to Python and have about 3 years of experience in it. However I'm not too good in business speech. </p> <p>I know all the technical pros and cons but when it comes to discussing business issues things blur a bit.</p> <p>EDIT:</p> <p>Reasons I want to use Python + Django:</p> <ul> <li>experience in Django</li> <li>beauty of pythonic code (and all it's benefits)</li> <li>lots of third party libraries</li> <li>efficiency</li> <li>less code = less bugs</li> </ul> <p>Reasons why my new boss wants to use PHP:</p> <ul> <li>he knows it</li> <li>he can estimate on his own</li> <li>he doesn't know Python</li> </ul> <p>@Vinko Vrsalovic: All requirements for both technologies are met.</p> <ul> <li>we have both our own servers and external Python hosting</li> <li>PHP costs of course less, however the difference is really tiny in comparison to support cost</li> <li>we have suitable resources for both PHP and Python projects</li> </ul> <p>I think problem is with my <a href="http://en.wikipedia.org/wiki/Project%5Fmanager">PM</a>: he is afraid of new technologies. For him it's something new. So quoting the basic question from Robertos answer "why can't we just use the old system?".</p> <p>I think I'm just too old :D to write a prototype in my free time. However this had worked a few times in past.</p>
18
2009-08-18T11:47:10Z
1,298,877
<p>You can check-out my <a href="http://www.flickr.com/photos/dibau%5Fnaum%5Fh/3501239850/sizes/o/" rel="nofollow">summary</a> from a talk on this subject by Justin Lilly, in last EuroDjangoCon.</p>
1
2009-08-19T09:57:23Z
[ "php", "python", "django" ]
How to convince my boss to use Django?
1,293,361
<p>I have an unusual problem: I have to convince my superiors to use Django for our new project. Alternative is some PHP framework. I've programmed in PHP for 2 years and then switched to Python and have about 3 years of experience in it. However I'm not too good in business speech. </p> <p>I know all the technical pros and cons but when it comes to discussing business issues things blur a bit.</p> <p>EDIT:</p> <p>Reasons I want to use Python + Django:</p> <ul> <li>experience in Django</li> <li>beauty of pythonic code (and all it's benefits)</li> <li>lots of third party libraries</li> <li>efficiency</li> <li>less code = less bugs</li> </ul> <p>Reasons why my new boss wants to use PHP:</p> <ul> <li>he knows it</li> <li>he can estimate on his own</li> <li>he doesn't know Python</li> </ul> <p>@Vinko Vrsalovic: All requirements for both technologies are met.</p> <ul> <li>we have both our own servers and external Python hosting</li> <li>PHP costs of course less, however the difference is really tiny in comparison to support cost</li> <li>we have suitable resources for both PHP and Python projects</li> </ul> <p>I think problem is with my <a href="http://en.wikipedia.org/wiki/Project%5Fmanager">PM</a>: he is afraid of new technologies. For him it's something new. So quoting the basic question from Robertos answer "why can't we just use the old system?".</p> <p>I think I'm just too old :D to write a prototype in my free time. However this had worked a few times in past.</p>
18
2009-08-18T11:47:10Z
1,310,879
<p>Google uses Django with the <a href="http://en.wikipedia.org/wiki/Google%5FApp%5FEngine" rel="nofollow">App Engine</a>. And nobody ever got fired for choosing Google...</p> <p>Like: "<a href="http://www.barrypopik.com/index.php/new%5Fyork%5Fcity/entry/no%5Fone%5Fever%5Fgot%5Ffired%5Ffor%5Fbuying%5Fibm%5Fmicrosoft%5Fgold/" rel="nofollow">Nobody ever got fired for buying IBM</a>" (1980s) and "<a href="http://www.barrypopik.com/index.php/new%5Fyork%5Fcity/entry/no%5Fone%5Fever%5Fgot%5Ffired%5Ffor%5Fbuying%5Fibm%5Fmicrosoft%5Fgold/" rel="nofollow">No one ever got fired for buying Microsoft</a>" (1990s).</p>
1
2009-08-21T09:12:28Z
[ "php", "python", "django" ]
How to find the sum of a ASCII value in a file to find the max number of ASCII and to print out the name of the highest sum of ASCII value
1,293,404
<p>Here is the code I'm working with</p> <pre><code>def ascii_sum(): x = 0 infile = open("30075165.txt","r") for line in infile: return sum([ord(x) for x in line]) infile.close() </code></pre> <p>This code only prints out the first ASCII value in the file not the max ASCII value</p>
-1
2009-08-18T11:58:13Z
1,293,439
<pre><code>max(open(fname), key=lambda line: sum(ord(i) for i in line)) </code></pre>
1
2009-08-18T12:05:40Z
[ "python" ]