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 |
|---|---|---|---|---|---|---|---|---|---|
Is there a way to reopen a socket? | 1,410,723 | <p>I create many "short-term" sockets in some code that look like that :</p>
<pre><code>nb=1000
for i in range(nb):
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((adr, prt)
sck.send('question %i'%i)
sck.shutdown(SHUT_WR)
answer=sck.recv(4096)
print 'answer %i : %s' % (%i, answer)
sck.close()
</code></pre>
<p>This works fine, as long as <em>nb</em> is "small" enough. </p>
<p>As <em>nb</em> might be quite large though, I'd like to do something like this</p>
<pre><code>sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((adr, prt)
for i in range(nb):
reopen(sck) # ? ? ?
sck.send('question %i'%i)
sck.shutdown(SHUT_WR)
answer=sck.recv(4096)
print 'answer %i : %s' % (%i, answer)
sck.close()
</code></pre>
<p>So the question is :<br />
Is there any way to "reuse" a socket that has been shutdown ?</p>
| 6 | 2009-09-11T13:00:14Z | 1,410,803 | <p>If you keep opening and closing sockets for the same port then it is better to open this socket once and keep it open, then you will have much better performance, since opening and closing will take some time.</p>
<p>If you have many short-term sockets, you may also consider datagram sockets (UDP).
Note that you do not have a guarantee for arrival in this case, also order of the packets is not guaranteed.</p>
| 1 | 2009-09-11T13:16:34Z | [
"python",
"sockets"
] |
Is there a way to reopen a socket? | 1,410,723 | <p>I create many "short-term" sockets in some code that look like that :</p>
<pre><code>nb=1000
for i in range(nb):
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((adr, prt)
sck.send('question %i'%i)
sck.shutdown(SHUT_WR)
answer=sck.recv(4096)
print 'answer %i : %s' % (%i, answer)
sck.close()
</code></pre>
<p>This works fine, as long as <em>nb</em> is "small" enough. </p>
<p>As <em>nb</em> might be quite large though, I'd like to do something like this</p>
<pre><code>sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((adr, prt)
for i in range(nb):
reopen(sck) # ? ? ?
sck.send('question %i'%i)
sck.shutdown(SHUT_WR)
answer=sck.recv(4096)
print 'answer %i : %s' % (%i, answer)
sck.close()
</code></pre>
<p>So the question is :<br />
Is there any way to "reuse" a socket that has been shutdown ?</p>
| 6 | 2009-09-11T13:00:14Z | 1,411,387 | <p>I'm not sure what the extra overhead would be like, but you could fully close and reopen the socket. You need to set SO_REUSEADDR, and bind to a specific port you can reuse.</p>
<pre><code>sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
</code></pre>
| 3 | 2009-09-11T14:54:12Z | [
"python",
"sockets"
] |
Is there a way to reopen a socket? | 1,410,723 | <p>I create many "short-term" sockets in some code that look like that :</p>
<pre><code>nb=1000
for i in range(nb):
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((adr, prt)
sck.send('question %i'%i)
sck.shutdown(SHUT_WR)
answer=sck.recv(4096)
print 'answer %i : %s' % (%i, answer)
sck.close()
</code></pre>
<p>This works fine, as long as <em>nb</em> is "small" enough. </p>
<p>As <em>nb</em> might be quite large though, I'd like to do something like this</p>
<pre><code>sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((adr, prt)
for i in range(nb):
reopen(sck) # ? ? ?
sck.send('question %i'%i)
sck.shutdown(SHUT_WR)
answer=sck.recv(4096)
print 'answer %i : %s' % (%i, answer)
sck.close()
</code></pre>
<p>So the question is :<br />
Is there any way to "reuse" a socket that has been shutdown ?</p>
| 6 | 2009-09-11T13:00:14Z | 1,411,602 | <p>You cannot reuse the socket but it would not help if you could, since you are running out of ports, not sockets. Each port will stay in <a href="http://www.developerweb.net/forum/showthread.php?t=2941" rel="nofollow"><code>TIME_WAIT</code> state</a> for twice the maximum segment lifetime after you initiate the shutdown. It would be best not to require so many ports within such a short period, but if you need to use a large number you may be able to increase the <a href="http://www.ncftp.com/ncftpd/doc/misc/ephemeral%5Fports.html" rel="nofollow">ephemeral port range</a>.</p>
<p>Port numbers are 16 bits and therefore there are only 65536 of them. If you are on Windows or Mac OS X then by default, ephemeral ports are chosen from the range 49152 to 65535. This is the <a href="http://www.iana.org/assignments/port-numbers" rel="nofollow">official range designated by IANA</a>, but on Linux and Solaris (often used for high traffic servers) the default range starts at 32768 to allow for more ports. You may want to make a similar change to your system if it is not already set that way and you are in need of more ephemeral ports.</p>
<p>It is also possible to reduce the maximum segment lifetime on your system, reducing the amount of time that each socket is in <code>TIME_WAIT</code> state, or to use <code>SO_REUSEADDR</code> or <code>SO_LINGER</code> in some cases to reuse ports before the time has expired. However this can at least theoretically cause older connections to be mixed up with newer connections that happen to be using the same port number, if some packets from the older connections are slow to arrive, so is generally not a good idea.</p>
| 0 | 2009-09-11T15:24:41Z | [
"python",
"sockets"
] |
Bypassing buffering of subprocess output with popen in C or Python | 1,410,849 | <p>I have a general question about popen (and all related functions), applicable to all operating systems, when I write a python script or some c code and run the resulting executable from the console (win or linux), i can immediately see the output from the process. However, if I run the same executable as a forked process with its stdout redirected into a pipe, the output buffers somewhere, usually up to 4096 bytes before it is written to the pipe where the parent process can read it.</p>
<p>The following python script will generate output in chunks of 1024 bytes</p>
<pre><code>import os, sys, time
if __name__ == "__main__":
dye = '@'*1024
for i in range (0,8):
print dye
time.sleep(1)
</code></pre>
<p>The following python script will execute the previous script and read the output as soon as it comes to the pipe, byte by byte</p>
<pre><code>import os, sys, subprocess, time, thread
if __name__ == "__main__":
execArgs = ["c:\\python25\\python.exe", "C:\\Scripts\\PythonScratch\\byte_stream.py"]
p = subprocess.Popen(execArgs, bufsize=0, stdout=subprocess.PIPE)
while p.returncode == None:
data = p.stdout.read(1)
sys.stdout.write(data)
p.poll()
</code></pre>
<p>Adjust the path for your operating system. When run in this configuration, the output will not appear in chunks of 1024 but chunks of 4096, despite the buffer size of the popen command being set to 0 (which is the default anyway). Can anyone tell me how to change this behaviour?, is there any way I can force the operating system to treat the output from the forked process in the same way as when it is run from the console?, ie, just feed the data through without buffering?</p>
| 9 | 2009-09-11T13:25:03Z | 1,410,879 | <p>Thats correct, and applies to both Windows and Linux (and possibly other systems), with <code>popen()</code> and <code>fopen()</code>. If you want the output buffer to be dispatched before 4096 bytes, use <code>fflush()</code> (on C) or <code>sys.stdout.flush()</code> (Python).</p>
| 1 | 2009-09-11T13:30:53Z | [
"python",
"c",
"buffer",
"pipe"
] |
Bypassing buffering of subprocess output with popen in C or Python | 1,410,849 | <p>I have a general question about popen (and all related functions), applicable to all operating systems, when I write a python script or some c code and run the resulting executable from the console (win or linux), i can immediately see the output from the process. However, if I run the same executable as a forked process with its stdout redirected into a pipe, the output buffers somewhere, usually up to 4096 bytes before it is written to the pipe where the parent process can read it.</p>
<p>The following python script will generate output in chunks of 1024 bytes</p>
<pre><code>import os, sys, time
if __name__ == "__main__":
dye = '@'*1024
for i in range (0,8):
print dye
time.sleep(1)
</code></pre>
<p>The following python script will execute the previous script and read the output as soon as it comes to the pipe, byte by byte</p>
<pre><code>import os, sys, subprocess, time, thread
if __name__ == "__main__":
execArgs = ["c:\\python25\\python.exe", "C:\\Scripts\\PythonScratch\\byte_stream.py"]
p = subprocess.Popen(execArgs, bufsize=0, stdout=subprocess.PIPE)
while p.returncode == None:
data = p.stdout.read(1)
sys.stdout.write(data)
p.poll()
</code></pre>
<p>Adjust the path for your operating system. When run in this configuration, the output will not appear in chunks of 1024 but chunks of 4096, despite the buffer size of the popen command being set to 0 (which is the default anyway). Can anyone tell me how to change this behaviour?, is there any way I can force the operating system to treat the output from the forked process in the same way as when it is run from the console?, ie, just feed the data through without buffering?</p>
| 9 | 2009-09-11T13:25:03Z | 1,411,112 | <p>In general, the standard C runtime library (that's running on behalf of just about every program on every system, more or less;-) detects whether stdout is a terminal or not; if not, it buffers the output (which can be a huge efficiency win, compared to unbuffered output).</p>
<p>If you're in control of the program that's doing the writing, you can (as another answer suggested) flush stdout continuously, or (more elegantly if feasible) try to force stdout to be unbuffered, e.g. by running Python with the <code>-u</code> commandline flag:</p>
<pre><code>-u : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x)
see man page for details on internal buffering relating to '-u'
</code></pre>
<p>(what the man page adds is a mention of stdin and issues with binary mode[s]).</p>
<p>If you can't or don't want to touch the program that's writing, <code>-u</code> or the like on the program that's just reading is unlikely to help (the buffering that matters most is the one happening on the writer's stdout, not the one on the reader's stdin). The alternative is to trick the writer into believing that it's writing to a terminal (even though in fact it's writing to another program!), via the <code>pty</code> standard library module or the higher-level third party <a href="http://pexpect.sourceforge.net/pexpect.html">pexpect</a> module (or, for Windows, its port <a href="http://code.google.com/p/wexpect/">wexpect</a>).</p>
| 10 | 2009-09-11T14:11:29Z | [
"python",
"c",
"buffer",
"pipe"
] |
Apache vs Twisted | 1,410,967 | <p>I know Twisted is a framework that allows you to do asynchronous non-blocking i/o but I still do not understand how that is different from what Apache server does. If anyone could explain the need for twisted, I would appreciate it..</p>
| 4 | 2009-09-11T13:46:13Z | 1,411,014 | <p>They are two different things, one is a pure WEB server and one is a WEB framework with a builtin event driven servers.</p>
<p>Twisted is good for constructing high-end ad-hoc network services.</p>
| 2 | 2009-09-11T13:56:19Z | [
"python",
"apache",
"twisted"
] |
Apache vs Twisted | 1,410,967 | <p>I know Twisted is a framework that allows you to do asynchronous non-blocking i/o but I still do not understand how that is different from what Apache server does. If anyone could explain the need for twisted, I would appreciate it..</p>
| 4 | 2009-09-11T13:46:13Z | 1,411,038 | <p>Twisted is a platform for developing internet applications, for handling the underlying communications and such. It doesn't "do" anything out of the box--you've got to program it.</p>
<p>Apache is an internet application, of sorts. Upon install, you have a working web server which can serve up static and dynamic web pages. Beyond that, it can be extended to do more than that, if you wish.</p>
| 10 | 2009-09-11T14:01:03Z | [
"python",
"apache",
"twisted"
] |
Apache vs Twisted | 1,410,967 | <p>I know Twisted is a framework that allows you to do asynchronous non-blocking i/o but I still do not understand how that is different from what Apache server does. If anyone could explain the need for twisted, I would appreciate it..</p>
| 4 | 2009-09-11T13:46:13Z | 1,413,874 | <p>FYI, FriendFeed/Facebook just open sourced their custom server and framework: <a href="http://www.tornadoweb.org/" rel="nofollow">Tornado</a>. Matt Heitzenroder of Apparatus has run an initial comparison test and <a href="http://www.apparatusproject.org/blog/" rel="nofollow">looks like Tornado left twisted in the dust</a>.</p>
| 2 | 2009-09-12T00:39:51Z | [
"python",
"apache",
"twisted"
] |
Apache vs Twisted | 1,410,967 | <p>I know Twisted is a framework that allows you to do asynchronous non-blocking i/o but I still do not understand how that is different from what Apache server does. If anyone could explain the need for twisted, I would appreciate it..</p>
| 4 | 2009-09-11T13:46:13Z | 1,456,513 | <p>@alphazero You read that Twisted vs. Tornado benchmark wrong (or you didn't read it at all). Quote from the article: " Lower mean response time is better." Twisted is <em>lower</em>. People want their webservers to respond with lower (faster) times.</p>
<p>Twisted leaves Tornado in the dust... or, in reality, they differ by a nearly trivial constant factor.</p>
| 2 | 2009-09-21T19:57:58Z | [
"python",
"apache",
"twisted"
] |
Equivalent of Bash Backticks in Python | 1,410,976 | <p>What is the equivalent of the backticks found in Ruby and Perl in Python? That is, in Ruby I can do this:</p>
<pre><code>foo = `cat /tmp/baz`
</code></pre>
<p>What does the equivalent statement look like in Python? I've tried <code>os.system("cat /tmp/baz")</code> but that puts the result to standard out and returns to me the error code of that operation.</p>
| 67 | 2009-09-11T13:47:53Z | 1,410,997 | <p>The most flexible way is to use the <a href="http://docs.python.org/library/subprocess.html"><code>subprocess</code></a> module:</p>
<pre><code>import subprocess
proc = subprocess.Popen(["cat", "/tmp/baz"], stdout=subprocess.PIPE)
(out, err) = proc.communicate()
print "program output:", out
</code></pre>
<p>If you want to pass the call through the shell, for example to get file name expansion with <code>*</code>, you can use the <code>shell=True</code> parameter. If you do this, you have to provide the command as a string, quoted/... like you would type it in at a shell prompt:</p>
<pre><code>proc = subprocess.Popen('cat /tmp/ba* "s p a c e.txt"', shell=True, ...)
</code></pre>
| 71 | 2009-09-11T13:52:17Z | [
"python",
"backticks"
] |
Equivalent of Bash Backticks in Python | 1,410,976 | <p>What is the equivalent of the backticks found in Ruby and Perl in Python? That is, in Ruby I can do this:</p>
<pre><code>foo = `cat /tmp/baz`
</code></pre>
<p>What does the equivalent statement look like in Python? I've tried <code>os.system("cat /tmp/baz")</code> but that puts the result to standard out and returns to me the error code of that operation.</p>
| 67 | 2009-09-11T13:47:53Z | 1,411,004 | <pre><code>output = os.popen('cat /tmp/baz').read()
</code></pre>
| 65 | 2009-09-11T13:53:48Z | [
"python",
"backticks"
] |
Equivalent of Bash Backticks in Python | 1,410,976 | <p>What is the equivalent of the backticks found in Ruby and Perl in Python? That is, in Ruby I can do this:</p>
<pre><code>foo = `cat /tmp/baz`
</code></pre>
<p>What does the equivalent statement look like in Python? I've tried <code>os.system("cat /tmp/baz")</code> but that puts the result to standard out and returns to me the error code of that operation.</p>
| 67 | 2009-09-11T13:47:53Z | 1,411,010 | <pre><code>import os
foo = os.popen('cat /tmp/baz', 'r').read()
</code></pre>
| 2 | 2009-09-11T13:55:24Z | [
"python",
"backticks"
] |
Equivalent of Bash Backticks in Python | 1,410,976 | <p>What is the equivalent of the backticks found in Ruby and Perl in Python? That is, in Ruby I can do this:</p>
<pre><code>foo = `cat /tmp/baz`
</code></pre>
<p>What does the equivalent statement look like in Python? I've tried <code>os.system("cat /tmp/baz")</code> but that puts the result to standard out and returns to me the error code of that operation.</p>
| 67 | 2009-09-11T13:47:53Z | 1,411,035 | <p><a href="http://stackoverflow.com/a/1410997/456814">sth is right</a>. You can also use os.popen(), but where available (Python 2.4+) subprocess is generally preferable.</p>
<p>However, unlike some languages that encourage it, it's generally considered bad form to spawn a subprocess where you can do the same job inside the language. It's slower, less reliable and platform-dependent. Your example would be better off as:</p>
<pre><code>foo= open('/tmp/baz').read()
</code></pre>
<p>eta:</p>
<blockquote>
<p>baz is a directory and I'm trying to get the contents of all the files in that directory</p>
</blockquote>
<p>? cat on a directory gets me an error.</p>
<p>If you want a list of files:</p>
<pre><code>import os
foo= os.listdir('/tmp/baz')
</code></pre>
<p>If you want the contents of all files in a directory, something like:</p>
<pre><code>contents= []
for leaf in os.listdir('/tmp/baz'):
path= os.path.join('/tmp/baz', leaf)
if os.path.isfile(path):
contents.append(open(path, 'rb').read())
foo= ''.join(contents)
</code></pre>
<p>or, if you can be sure there are no directories in there, you could fit it in a one-liner:</p>
<pre><code>path= '/tmp/baz'
foo= ''.join(open(os.path.join(path, child), 'rb').read() for child in os.listdir(path))
</code></pre>
| 23 | 2009-09-11T14:00:11Z | [
"python",
"backticks"
] |
Equivalent of Bash Backticks in Python | 1,410,976 | <p>What is the equivalent of the backticks found in Ruby and Perl in Python? That is, in Ruby I can do this:</p>
<pre><code>foo = `cat /tmp/baz`
</code></pre>
<p>What does the equivalent statement look like in Python? I've tried <code>os.system("cat /tmp/baz")</code> but that puts the result to standard out and returns to me the error code of that operation.</p>
| 67 | 2009-09-11T13:47:53Z | 2,626,678 | <p>If you use subprocess.Popen, remember to specify bufsize. The default is 0, which means "unbuffered", not "choose a reasonable default".</p>
| 0 | 2010-04-13T02:55:41Z | [
"python",
"backticks"
] |
Equivalent of Bash Backticks in Python | 1,410,976 | <p>What is the equivalent of the backticks found in Ruby and Perl in Python? That is, in Ruby I can do this:</p>
<pre><code>foo = `cat /tmp/baz`
</code></pre>
<p>What does the equivalent statement look like in Python? I've tried <code>os.system("cat /tmp/baz")</code> but that puts the result to standard out and returns to me the error code of that operation.</p>
| 67 | 2009-09-11T13:47:53Z | 5,279,400 | <p>I'm using</p>
<blockquote>
<p>(6:0)$ python --version
Python 2.7.1</p>
</blockquote>
<p>One of the examples above is:</p>
<pre><code>import subprocess
proc = subprocess.Popen(["cat", "/tmp/baz"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "program output:", out
</code></pre>
<p>For me, this failed to access the directory /tmp. After looking at the doc string for subprocess I replaced </p>
<blockquote>
<p>[ "prog", "arg"]</p>
</blockquote>
<p>with </p>
<blockquote>
<p>"prog arg" </p>
</blockquote>
<p>and got the shell expansion behavior that was desired (a la Perl's `prog arg`)</p>
<blockquote>
<p>print subprocess.Popen("ls -ld /tmp/v*", stdout=subprocess.PIPE, shell=True).communicate()[0]</p>
</blockquote>
<hr>
<p>I quit using python a while back because I was annoyed with the difficulty of of doing the equivalent of perl `cmd ...`. I'm glad to find Python has made this reasonable.</p>
| 1 | 2011-03-11T23:13:34Z | [
"python",
"backticks"
] |
Equivalent of Bash Backticks in Python | 1,410,976 | <p>What is the equivalent of the backticks found in Ruby and Perl in Python? That is, in Ruby I can do this:</p>
<pre><code>foo = `cat /tmp/baz`
</code></pre>
<p>What does the equivalent statement look like in Python? I've tried <code>os.system("cat /tmp/baz")</code> but that puts the result to standard out and returns to me the error code of that operation.</p>
| 67 | 2009-09-11T13:47:53Z | 7,469,168 | <pre><code>foo = subprocess.check_output(["cat", "/tmp/baz"])
</code></pre>
| 13 | 2011-09-19T09:58:22Z | [
"python",
"backticks"
] |
Equivalent of Bash Backticks in Python | 1,410,976 | <p>What is the equivalent of the backticks found in Ruby and Perl in Python? That is, in Ruby I can do this:</p>
<pre><code>foo = `cat /tmp/baz`
</code></pre>
<p>What does the equivalent statement look like in Python? I've tried <code>os.system("cat /tmp/baz")</code> but that puts the result to standard out and returns to me the error code of that operation.</p>
| 67 | 2009-09-11T13:47:53Z | 25,001,160 | <p>Easiest way is to use commands package.</p>
<pre><code>import commands
commands.getoutput("whoami")
</code></pre>
<p>Output:</p>
<blockquote>
<p>'bganesan'</p>
</blockquote>
| 3 | 2014-07-28T17:48:01Z | [
"python",
"backticks"
] |
Equivalent of Bash Backticks in Python | 1,410,976 | <p>What is the equivalent of the backticks found in Ruby and Perl in Python? That is, in Ruby I can do this:</p>
<pre><code>foo = `cat /tmp/baz`
</code></pre>
<p>What does the equivalent statement look like in Python? I've tried <code>os.system("cat /tmp/baz")</code> but that puts the result to standard out and returns to me the error code of that operation.</p>
| 67 | 2009-09-11T13:47:53Z | 29,735,004 | <p>This will not work in python3, but in python2 you can extend <code>str</code> with a custom <code>__repr__</code> method that calls your shell command and returns it like so:</p>
<pre><code>#!/usr/bin/env python
import os
class Command(str):
"""Call system commands"""
def __repr__(cmd):
return os.popen(cmd).read()
</code></pre>
<p>Which you can use like</p>
<pre><code>#!/usr/bin/env python
from command import Command
who_i_am = `Command('whoami')`
# Or predeclare your shell command strings
whoami = Command('whoami')
who_i_am = `whoami`
</code></pre>
| 1 | 2015-04-19T19:48:17Z | [
"python",
"backticks"
] |
Equivalent of Bash Backticks in Python | 1,410,976 | <p>What is the equivalent of the backticks found in Ruby and Perl in Python? That is, in Ruby I can do this:</p>
<pre><code>foo = `cat /tmp/baz`
</code></pre>
<p>What does the equivalent statement look like in Python? I've tried <code>os.system("cat /tmp/baz")</code> but that puts the result to standard out and returns to me the error code of that operation.</p>
| 67 | 2009-09-11T13:47:53Z | 36,160,224 | <p>From Python 3.5 onward, the recommended way is to use <a href="https://docs.python.org/3/library/subprocess.html#subprocess.run" rel="nofollow"><code>subprocess.run</code></a>. To get the same behaviour as you describe, you would use:</p>
<pre><code>output = subprocess.run("ls", shell=True, stdout=subprocess.PIPE).stdout
</code></pre>
<p>This will return a <code>bytes</code> object. You might want to append <code>.decode("ascii")</code> or <code>.decode("utf-8")</code> to the end to get a <code>str</code>.</p>
| 1 | 2016-03-22T16:39:33Z | [
"python",
"backticks"
] |
Python - Windows Shutdown Events | 1,411,186 | <p>When using win32api.setConsoleCtrlHandler(), I'm able to receive shutdown/logoff/etc events from Windows, and cleanly shut down my app.</p>
<p>However, this only works when running the app under python.exe (i.e., it has a console window), but not under pythonw.exe (no console window).</p>
<p>Is there an equivalent way in Windows to receive these events when you have no console and no window to receive them? Or, is there a programmatic way to hide the console window?</p>
<p>To be clear - my goal is to be able to successfully receive Windows shutdown/logoff/etc events, without having any kind of console window showing.</p>
<p><strong>EDIT:</strong>
I've been playing around, and I've gotten quite a bit further. I wrote a piece of test code for this. When I do a "taskkill /im pythonw.exe" - it will receive the message.</p>
<p>However, when I do a shutdown, restart, or logoff on Windows, I do not get any messages.</p>
<p>Here's the whole thing:</p>
<pre><code>""" Testing Windows shutdown events """
import win32con
import win32api
import win32gui
import sys
import time
#import os
def log_info(msg):
""" Prints """
print msg
f = open("c:\\test.log", "a")
f.write(msg + "\n")
f.close()
def wndproc(hwnd, msg, wparam, lparam):
log_info("wndproc: %s" % msg)
if __name__ == "__main__":
log_info("*** STARTING ***")
hinst = win32api.GetModuleHandle(None)
wndclass = win32gui.WNDCLASS()
wndclass.hInstance = hinst
wndclass.lpszClassName = "testWindowClass"
messageMap = { win32con.WM_QUERYENDSESSION : wndproc,
win32con.WM_ENDSESSION : wndproc,
win32con.WM_QUIT : wndproc,
win32con.WM_DESTROY : wndproc,
win32con.WM_CLOSE : wndproc }
wndclass.lpfnWndProc = messageMap
try:
myWindowClass = win32gui.RegisterClass(wndclass)
hwnd = win32gui.CreateWindowEx(win32con.WS_EX_LEFT,
myWindowClass,
"testMsgWindow",
0,
0,
0,
win32con.CW_USEDEFAULT,
win32con.CW_USEDEFAULT,
win32con.HWND_MESSAGE,
0,
hinst,
None)
except Exception, e:
log_info("Exception: %s" % str(e))
if hwnd is None:
log_info("hwnd is none!")
else:
log_info("hwnd: %s" % hwnd)
while True:
win32gui.PumpWaitingMessages()
time.sleep(1)
</code></pre>
<p>I feel like I'm pretty close here, but I'm definitely missing something!</p>
| 7 | 2009-09-11T14:21:59Z | 1,411,322 | <p>If you don't have a console, setting a console handler of course can't work. You can receive system events on a GUI (non-console) program by making another window (doesn't have to be visible), making sure you have a normal "message pump" on it serving, and handling <code>WM_QUERYENDSESSION</code> -- that's the message telling your window about shutdown and logoff events (and your window can try to push back against the end-session by returning 0 for this message). ("Windows Services" are different from normal apps -- if that's what you're writing, see an example <a href="http://mail.python.org/pipermail/python-win32/2004-September/002305.html" rel="nofollow">here</a>).</p>
| 4 | 2009-09-11T14:43:39Z | [
"python",
"windows"
] |
Python - Windows Shutdown Events | 1,411,186 | <p>When using win32api.setConsoleCtrlHandler(), I'm able to receive shutdown/logoff/etc events from Windows, and cleanly shut down my app.</p>
<p>However, this only works when running the app under python.exe (i.e., it has a console window), but not under pythonw.exe (no console window).</p>
<p>Is there an equivalent way in Windows to receive these events when you have no console and no window to receive them? Or, is there a programmatic way to hide the console window?</p>
<p>To be clear - my goal is to be able to successfully receive Windows shutdown/logoff/etc events, without having any kind of console window showing.</p>
<p><strong>EDIT:</strong>
I've been playing around, and I've gotten quite a bit further. I wrote a piece of test code for this. When I do a "taskkill /im pythonw.exe" - it will receive the message.</p>
<p>However, when I do a shutdown, restart, or logoff on Windows, I do not get any messages.</p>
<p>Here's the whole thing:</p>
<pre><code>""" Testing Windows shutdown events """
import win32con
import win32api
import win32gui
import sys
import time
#import os
def log_info(msg):
""" Prints """
print msg
f = open("c:\\test.log", "a")
f.write(msg + "\n")
f.close()
def wndproc(hwnd, msg, wparam, lparam):
log_info("wndproc: %s" % msg)
if __name__ == "__main__":
log_info("*** STARTING ***")
hinst = win32api.GetModuleHandle(None)
wndclass = win32gui.WNDCLASS()
wndclass.hInstance = hinst
wndclass.lpszClassName = "testWindowClass"
messageMap = { win32con.WM_QUERYENDSESSION : wndproc,
win32con.WM_ENDSESSION : wndproc,
win32con.WM_QUIT : wndproc,
win32con.WM_DESTROY : wndproc,
win32con.WM_CLOSE : wndproc }
wndclass.lpfnWndProc = messageMap
try:
myWindowClass = win32gui.RegisterClass(wndclass)
hwnd = win32gui.CreateWindowEx(win32con.WS_EX_LEFT,
myWindowClass,
"testMsgWindow",
0,
0,
0,
win32con.CW_USEDEFAULT,
win32con.CW_USEDEFAULT,
win32con.HWND_MESSAGE,
0,
hinst,
None)
except Exception, e:
log_info("Exception: %s" % str(e))
if hwnd is None:
log_info("hwnd is none!")
else:
log_info("hwnd: %s" % hwnd)
while True:
win32gui.PumpWaitingMessages()
time.sleep(1)
</code></pre>
<p>I feel like I'm pretty close here, but I'm definitely missing something!</p>
| 7 | 2009-09-11T14:21:59Z | 1,429,658 | <p>The problem here was that the HWND_MESSAGE window type doesn't actually receive broadcast messages - like the WM_QUERYENDSESSION and WM_ENDSESSION. </p>
<p>So instead of specifying win32con.HWND_MESSAGE for the "parent window" parameter of CreateWindowEx(), I just specified "0".</p>
<p>Basically, this creates an actual window, but I never show it, so it's effectively the same thing. Now, I can successfully receive those broadcast messages and shut down the app properly.</p>
| 6 | 2009-09-15T21:13:29Z | [
"python",
"windows"
] |
Twisted - listen to multiple ports for multiple processes with one reactor | 1,411,281 | <p>i need to run multiple instances of my server app each on it's own port. It's not a problem if i start these with os.system or subprocess.Popen, but i'd like to have some process communication with multiprocessing. </p>
<p>I'd like to somehow dynamically set up listening to different port from different processes. Just calling reactor.listenTCP doesn't do it, because i getting strange Errno 22 while stopping reactor. I'm also pretty sure it's not the correct way to do it. I looked for examples, but couldn't find anything. Any help is appreciated. </p>
<p>EDIT:
Thanks Tzury, it's kinda what i'd like to get. But i have to dynamicly add ports to listen. For Example </p>
<pre><code>from twisted.internet import reactor
from multiprocessing import Process
def addListener(self, port, site):
''' Called when I have to add new port to listen to.
site - factory handling input, NevowSite in my case'''
p = Process(target=f, args=(port, func))
p.start()
def f(self, port, func):
''' Runs as a new process'''
reactor.listenTCP(port, func)
</code></pre>
<p>I need a way to neatly stop such processes. Just calling reactor.stop() stop a child process doesn't do it.</p>
<p>This is the error i'm gettin when i trying to stop a process</p>
<pre><code> --- <exception caught here> ---
File "/usr/share/exe/twisted/internet/tcp.py", line 755, in doRead
skt, addr = self.socket.accept()
File "/usr/lib/python2.6/socket.py", line 195, in accept
sock, addr = self._sock.accept()
<class 'socket.error'>: [Errno 22] Invalid argument
</code></pre>
<p>Dimitri.</p>
| 3 | 2009-09-11T14:35:53Z | 1,417,980 | <p>I am not sure what error you are getting.
The following is an example from <a href="http://twistedmatrix.com/projects/core/documentation/howto/servers.html">twisted site</a> (modified)
And as you can see, it listen on two ports, and can listen to many more.</p>
<pre><code>from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
class QOTD(Protocol):
def connectionMade(self):
self.transport.write("An apple a day keeps the doctor away\r\n")
self.transport.loseConnection()
# Next lines are magic:
factory = Factory()
factory.protocol = QOTD
# 8007 is the port you want to run under. Choose something >1024
reactor.listenTCP(8007, factory)
reactor.listenTCP(8008, factory)
reactor.run()
</code></pre>
| 9 | 2009-09-13T15:21:31Z | [
"python",
"process",
"twisted"
] |
Locking in sqlalchemy | 1,411,350 | <p>I'm confused about how to concurrently modify a table from several different processes. I've tried using <code>Query.with_lockmode()</code>, but it doesn't seem to be doing what I expect it to do, which would be to prevent two processes from simultaneously querying the same rows. Here's what I've tried:</p>
<pre><code>import time
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import *
engine = create_engine('mysql://...?charset=utf8&use_unicode=0', pool_recycle=3600, echo=False)
Base = declarative_base(bind=engine)
session = scoped_session(sessionmaker(engine))
class Test(Base):
__tablename__ = "TESTXYZ"
id = Column(Integer, primary_key=True)
x = Column(Integer)
def keepUpdating():
test = session.query(Test).filter(Test.id==1).with_lockmode("update").one()
for counter in range(5):
test.x += 10
print test.x
time.sleep(2)
session.commit()
keepUpdating()
</code></pre>
<p>If I run this script twice simultaneously, I get <code>session.query(Test).filter(Test.id==1).one().x</code> equal to 50, rather than 100 (assuming it was 0 to begin with), which was what I was hoping for. How do I get both processes to either simultaneously update the values or have the second one wait until the first is done?</p>
| 3 | 2009-09-11T14:48:09Z | 1,411,497 | <p>Are you by accident using MyISAM tables? This works fine with InnoDB tables, but would have the described behavior (silent failure to respect isolation) with MyISAM.</p>
| 4 | 2009-09-11T15:08:44Z | [
"python",
"sql",
"sqlalchemy",
"locking"
] |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | <p>I can't get wsgi to import my settings file for my project 'mofin'.</p>
<p>The list of errors from the apache error log are as follows</p>
<pre><code>mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
self._import_settings()
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings
self._target = Settings(settings_module)
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'mofin.settings' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings
</code></pre>
<p>I got the "hello world!" wsgi app listed here(<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a>) to work fine. </p>
<p>The settings.py file loads fine with python manage.py (runserver|shell|syncdb|test store)
as does the application.</p>
<p>Here is my wsgi file:</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk')
sys.path.append('/home/django/mofin/trunk/mofin')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>the sys.path as printed in the error log is</p>
<blockquote>
<p>['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0', '/home/django/mofin/trunk', '/home/django/mofin/trunk/mofin']</p>
</blockquote>
<p>if I open an interactive shell with manage.py, sys.path is</p>
<blockquote>
<p>['/home/django/mofin/trunk/mofin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0']</p>
</blockquote>
<p>My django settings file looks like this:
# Django settings for mofin project.</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Dan xxxx', 'xxxx@yyyyyyyyyy.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'mofin' # Or path to database file if using sqlite3.
DATABASE_USER = 'aaaaaa' # Not used with sqlite3.
DATABASE_PASSWORD = 'bbbbbb' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-GB'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/django/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://mofin.mywebsite.co.uk/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'mofin.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mofin.store'
)
</code></pre>
| 62 | 2009-09-11T14:58:37Z | 1,411,515 | <p>Possible problem:</p>
<p>you forgot the __init__.py file, which must be in your project and in all directories which you consider a python module for import.</p>
<p>Other thing you could try is to add the path directly into the manage.py file, like :</p>
<pre><code>import sys
...
...
sys.path.insert(0, '/home/django/mofin/trunk')
</code></pre>
<p>I hope it helps</p>
| 4 | 2009-09-11T15:10:14Z | [
"python",
"django",
"apache",
"wsgi"
] |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | <p>I can't get wsgi to import my settings file for my project 'mofin'.</p>
<p>The list of errors from the apache error log are as follows</p>
<pre><code>mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
self._import_settings()
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings
self._target = Settings(settings_module)
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'mofin.settings' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings
</code></pre>
<p>I got the "hello world!" wsgi app listed here(<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a>) to work fine. </p>
<p>The settings.py file loads fine with python manage.py (runserver|shell|syncdb|test store)
as does the application.</p>
<p>Here is my wsgi file:</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk')
sys.path.append('/home/django/mofin/trunk/mofin')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>the sys.path as printed in the error log is</p>
<blockquote>
<p>['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0', '/home/django/mofin/trunk', '/home/django/mofin/trunk/mofin']</p>
</blockquote>
<p>if I open an interactive shell with manage.py, sys.path is</p>
<blockquote>
<p>['/home/django/mofin/trunk/mofin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0']</p>
</blockquote>
<p>My django settings file looks like this:
# Django settings for mofin project.</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Dan xxxx', 'xxxx@yyyyyyyyyy.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'mofin' # Or path to database file if using sqlite3.
DATABASE_USER = 'aaaaaa' # Not used with sqlite3.
DATABASE_PASSWORD = 'bbbbbb' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-GB'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/django/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://mofin.mywebsite.co.uk/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'mofin.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mofin.store'
)
</code></pre>
| 62 | 2009-09-11T14:58:37Z | 1,412,678 | <p>At first look I'd say the python path is wrong but compared to interactive shell it looks ok.
So maybe try this:</p>
<pre><code>from django.core.management import setup_environ
from mofin import settings
setup_environ(settings)
</code></pre>
| 0 | 2009-09-11T18:51:27Z | [
"python",
"django",
"apache",
"wsgi"
] |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | <p>I can't get wsgi to import my settings file for my project 'mofin'.</p>
<p>The list of errors from the apache error log are as follows</p>
<pre><code>mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
self._import_settings()
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings
self._target = Settings(settings_module)
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'mofin.settings' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings
</code></pre>
<p>I got the "hello world!" wsgi app listed here(<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a>) to work fine. </p>
<p>The settings.py file loads fine with python manage.py (runserver|shell|syncdb|test store)
as does the application.</p>
<p>Here is my wsgi file:</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk')
sys.path.append('/home/django/mofin/trunk/mofin')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>the sys.path as printed in the error log is</p>
<blockquote>
<p>['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0', '/home/django/mofin/trunk', '/home/django/mofin/trunk/mofin']</p>
</blockquote>
<p>if I open an interactive shell with manage.py, sys.path is</p>
<blockquote>
<p>['/home/django/mofin/trunk/mofin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0']</p>
</blockquote>
<p>My django settings file looks like this:
# Django settings for mofin project.</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Dan xxxx', 'xxxx@yyyyyyyyyy.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'mofin' # Or path to database file if using sqlite3.
DATABASE_USER = 'aaaaaa' # Not used with sqlite3.
DATABASE_PASSWORD = 'bbbbbb' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-GB'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/django/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://mofin.mywebsite.co.uk/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'mofin.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mofin.store'
)
</code></pre>
| 62 | 2009-09-11T14:58:37Z | 1,418,284 | <p>I was going to say that you can just insert/append your project directory to your sys.path in your wsgi file but if your settings file is at</p>
<pre><code>/home/django/mofin/trunk/mofin/settings.py
</code></pre>
<p>Then you should be good there.</p>
<pre><code>Is it on sys.path? Does it have syntax errors?
</code></pre>
<p>That pretty much sums up what you are looking for.</p>
<p>Interesting that the error propagates though:</p>
<pre><code>for middleware_path in settings.MIDDLEWARE_CLASSES:
</code></pre>
<p>but you have what appears to be the <a href="http://docs.djangoproject.com/en/dev/topics/http/middleware/" rel="nofollow">exact default</a>.</p>
<p>You might want to check which python interpreter is pointed to by wsgi. Are you intending to use a virtualenv but wsgi is looking at your system install?</p>
<p>You can also set the user and group that wsgi is running under. I use something like:</p>
<p>WSGIDaemonProcess mysite.com user=skyl group=skyl processes=n threads=N python-path=/home/skyl/pinax/pinax-env2/lib/python2.6/site-packages</p>
| 0 | 2009-09-13T17:20:53Z | [
"python",
"django",
"apache",
"wsgi"
] |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | <p>I can't get wsgi to import my settings file for my project 'mofin'.</p>
<p>The list of errors from the apache error log are as follows</p>
<pre><code>mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
self._import_settings()
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings
self._target = Settings(settings_module)
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'mofin.settings' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings
</code></pre>
<p>I got the "hello world!" wsgi app listed here(<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a>) to work fine. </p>
<p>The settings.py file loads fine with python manage.py (runserver|shell|syncdb|test store)
as does the application.</p>
<p>Here is my wsgi file:</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk')
sys.path.append('/home/django/mofin/trunk/mofin')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>the sys.path as printed in the error log is</p>
<blockquote>
<p>['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0', '/home/django/mofin/trunk', '/home/django/mofin/trunk/mofin']</p>
</blockquote>
<p>if I open an interactive shell with manage.py, sys.path is</p>
<blockquote>
<p>['/home/django/mofin/trunk/mofin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0']</p>
</blockquote>
<p>My django settings file looks like this:
# Django settings for mofin project.</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Dan xxxx', 'xxxx@yyyyyyyyyy.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'mofin' # Or path to database file if using sqlite3.
DATABASE_USER = 'aaaaaa' # Not used with sqlite3.
DATABASE_PASSWORD = 'bbbbbb' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-GB'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/django/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://mofin.mywebsite.co.uk/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'mofin.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mofin.store'
)
</code></pre>
| 62 | 2009-09-11T14:58:37Z | 1,438,381 | <p>I found the answer... file permissions. /home/django was set to 700. i.e. only django can view the contents. apache runs as Apache and so can't get past /home/django. </p>
| 8 | 2009-09-17T11:51:54Z | [
"python",
"django",
"apache",
"wsgi"
] |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | <p>I can't get wsgi to import my settings file for my project 'mofin'.</p>
<p>The list of errors from the apache error log are as follows</p>
<pre><code>mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
self._import_settings()
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings
self._target = Settings(settings_module)
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'mofin.settings' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings
</code></pre>
<p>I got the "hello world!" wsgi app listed here(<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a>) to work fine. </p>
<p>The settings.py file loads fine with python manage.py (runserver|shell|syncdb|test store)
as does the application.</p>
<p>Here is my wsgi file:</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk')
sys.path.append('/home/django/mofin/trunk/mofin')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>the sys.path as printed in the error log is</p>
<blockquote>
<p>['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0', '/home/django/mofin/trunk', '/home/django/mofin/trunk/mofin']</p>
</blockquote>
<p>if I open an interactive shell with manage.py, sys.path is</p>
<blockquote>
<p>['/home/django/mofin/trunk/mofin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0']</p>
</blockquote>
<p>My django settings file looks like this:
# Django settings for mofin project.</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Dan xxxx', 'xxxx@yyyyyyyyyy.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'mofin' # Or path to database file if using sqlite3.
DATABASE_USER = 'aaaaaa' # Not used with sqlite3.
DATABASE_PASSWORD = 'bbbbbb' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-GB'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/django/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://mofin.mywebsite.co.uk/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'mofin.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mofin.store'
)
</code></pre>
| 62 | 2009-09-11T14:58:37Z | 4,181,080 | <p>I had a similar permissions problem, and although my settings.py had the right permissions, the .pyc's did not!!! So watch out for this.</p>
| 21 | 2010-11-15T02:59:13Z | [
"python",
"django",
"apache",
"wsgi"
] |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | <p>I can't get wsgi to import my settings file for my project 'mofin'.</p>
<p>The list of errors from the apache error log are as follows</p>
<pre><code>mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
self._import_settings()
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings
self._target = Settings(settings_module)
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'mofin.settings' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings
</code></pre>
<p>I got the "hello world!" wsgi app listed here(<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a>) to work fine. </p>
<p>The settings.py file loads fine with python manage.py (runserver|shell|syncdb|test store)
as does the application.</p>
<p>Here is my wsgi file:</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk')
sys.path.append('/home/django/mofin/trunk/mofin')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>the sys.path as printed in the error log is</p>
<blockquote>
<p>['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0', '/home/django/mofin/trunk', '/home/django/mofin/trunk/mofin']</p>
</blockquote>
<p>if I open an interactive shell with manage.py, sys.path is</p>
<blockquote>
<p>['/home/django/mofin/trunk/mofin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0']</p>
</blockquote>
<p>My django settings file looks like this:
# Django settings for mofin project.</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Dan xxxx', 'xxxx@yyyyyyyyyy.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'mofin' # Or path to database file if using sqlite3.
DATABASE_USER = 'aaaaaa' # Not used with sqlite3.
DATABASE_PASSWORD = 'bbbbbb' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-GB'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/django/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://mofin.mywebsite.co.uk/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'mofin.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mofin.store'
)
</code></pre>
| 62 | 2009-09-11T14:58:37Z | 4,750,766 | <p>Hey, just adding an additional answer to this problem. I had the exact same issue, but it wasn't file permissions. I was appending "path/to/project", but not also appending "path/to". Linked is mod_wsgi's <a href="http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango">Django integration explanation</a> that showed me the answer.</p>
| 18 | 2011-01-20T18:04:09Z | [
"python",
"django",
"apache",
"wsgi"
] |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | <p>I can't get wsgi to import my settings file for my project 'mofin'.</p>
<p>The list of errors from the apache error log are as follows</p>
<pre><code>mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
self._import_settings()
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings
self._target = Settings(settings_module)
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'mofin.settings' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings
</code></pre>
<p>I got the "hello world!" wsgi app listed here(<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a>) to work fine. </p>
<p>The settings.py file loads fine with python manage.py (runserver|shell|syncdb|test store)
as does the application.</p>
<p>Here is my wsgi file:</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk')
sys.path.append('/home/django/mofin/trunk/mofin')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>the sys.path as printed in the error log is</p>
<blockquote>
<p>['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0', '/home/django/mofin/trunk', '/home/django/mofin/trunk/mofin']</p>
</blockquote>
<p>if I open an interactive shell with manage.py, sys.path is</p>
<blockquote>
<p>['/home/django/mofin/trunk/mofin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0']</p>
</blockquote>
<p>My django settings file looks like this:
# Django settings for mofin project.</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Dan xxxx', 'xxxx@yyyyyyyyyy.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'mofin' # Or path to database file if using sqlite3.
DATABASE_USER = 'aaaaaa' # Not used with sqlite3.
DATABASE_PASSWORD = 'bbbbbb' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-GB'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/django/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://mofin.mywebsite.co.uk/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'mofin.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mofin.store'
)
</code></pre>
| 62 | 2009-09-11T14:58:37Z | 6,949,892 | <p>This can also happen if you have an application (subdirectory to the project with an init file in it) named the same thing as the project. Your settings.py file may be in your project folder, but it seems that a part of the django system looks first for a module inside the project by the same name as the project and when it can't find a settings.py in there, it fails with a misleading message.</p>
<pre><code>-uniquename1
---settings.py
---manage.py
---application1
-----file.py
-----file2.py
---uniquename1 (problem, rename this to some other unique name)
-----file.py
-----file2.py
</code></pre>
<p>Just something else to check for anyone else having this problem. Applies to Django 1.3 and probably others.</p>
| 46 | 2011-08-04T23:40:02Z | [
"python",
"django",
"apache",
"wsgi"
] |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | <p>I can't get wsgi to import my settings file for my project 'mofin'.</p>
<p>The list of errors from the apache error log are as follows</p>
<pre><code>mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
self._import_settings()
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings
self._target = Settings(settings_module)
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'mofin.settings' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings
</code></pre>
<p>I got the "hello world!" wsgi app listed here(<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a>) to work fine. </p>
<p>The settings.py file loads fine with python manage.py (runserver|shell|syncdb|test store)
as does the application.</p>
<p>Here is my wsgi file:</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk')
sys.path.append('/home/django/mofin/trunk/mofin')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>the sys.path as printed in the error log is</p>
<blockquote>
<p>['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0', '/home/django/mofin/trunk', '/home/django/mofin/trunk/mofin']</p>
</blockquote>
<p>if I open an interactive shell with manage.py, sys.path is</p>
<blockquote>
<p>['/home/django/mofin/trunk/mofin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0']</p>
</blockquote>
<p>My django settings file looks like this:
# Django settings for mofin project.</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Dan xxxx', 'xxxx@yyyyyyyyyy.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'mofin' # Or path to database file if using sqlite3.
DATABASE_USER = 'aaaaaa' # Not used with sqlite3.
DATABASE_PASSWORD = 'bbbbbb' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-GB'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/django/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://mofin.mywebsite.co.uk/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'mofin.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mofin.store'
)
</code></pre>
| 62 | 2009-09-11T14:58:37Z | 7,254,518 | <p>I had the same problem but another solution :</p>
<p>My project folder was named exactly as one of my application.</p>
<p>I had :</p>
<p>/home/myApp<br>
/home/myApp/settings.py<br>
/home/myApp/manage.py<br>
/home/myApp/rights.py<br>
/home/myApp/static/<br>
/home/myApp/static/<br>
/home/myApp/<strong>myApp</strong>/model.py<br>
/home/myApp/<strong>myApp</strong>/admin.py<br>
/home/myApp/<strong>myApp</strong>/views.py<br></p>
<p>This kind of tree doesn't seems to be possible easily.
I changed the name of my project root folder and the problem was solved!</p>
| 3 | 2011-08-31T08:38:38Z | [
"python",
"django",
"apache",
"wsgi"
] |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | <p>I can't get wsgi to import my settings file for my project 'mofin'.</p>
<p>The list of errors from the apache error log are as follows</p>
<pre><code>mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
self._import_settings()
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings
self._target = Settings(settings_module)
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'mofin.settings' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings
</code></pre>
<p>I got the "hello world!" wsgi app listed here(<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a>) to work fine. </p>
<p>The settings.py file loads fine with python manage.py (runserver|shell|syncdb|test store)
as does the application.</p>
<p>Here is my wsgi file:</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk')
sys.path.append('/home/django/mofin/trunk/mofin')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>the sys.path as printed in the error log is</p>
<blockquote>
<p>['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0', '/home/django/mofin/trunk', '/home/django/mofin/trunk/mofin']</p>
</blockquote>
<p>if I open an interactive shell with manage.py, sys.path is</p>
<blockquote>
<p>['/home/django/mofin/trunk/mofin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0']</p>
</blockquote>
<p>My django settings file looks like this:
# Django settings for mofin project.</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Dan xxxx', 'xxxx@yyyyyyyyyy.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'mofin' # Or path to database file if using sqlite3.
DATABASE_USER = 'aaaaaa' # Not used with sqlite3.
DATABASE_PASSWORD = 'bbbbbb' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-GB'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/django/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://mofin.mywebsite.co.uk/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'mofin.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mofin.store'
)
</code></pre>
| 62 | 2009-09-11T14:58:37Z | 7,347,016 | <p>I think you need to have a trailing forward slash on that its what I have to do in my wsgi script in apache before I load up django.</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk/')
sys.path.append('/home/django/mofin/trunk/mofin/')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>In my case</p>
<pre><code>import os
import sys
if os.uname()[1] == 'vivien':
sys.path.append('/home/www/sitebuilder.blacknight.ie/web/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'gibo.dev_settings'
elif os.uname()[1] == 'thingy':
sys.path.append('/home/www/sitebuilder.blacknight.ie/web/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'gibo.dev_settings'
else:
sys.path.append('/home/www/sitebuilder.blacknight.ie/web/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'gibo.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
| 7 | 2011-09-08T11:02:35Z | [
"python",
"django",
"apache",
"wsgi"
] |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | <p>I can't get wsgi to import my settings file for my project 'mofin'.</p>
<p>The list of errors from the apache error log are as follows</p>
<pre><code>mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
self._import_settings()
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings
self._target = Settings(settings_module)
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'mofin.settings' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings
</code></pre>
<p>I got the "hello world!" wsgi app listed here(<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a>) to work fine. </p>
<p>The settings.py file loads fine with python manage.py (runserver|shell|syncdb|test store)
as does the application.</p>
<p>Here is my wsgi file:</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk')
sys.path.append('/home/django/mofin/trunk/mofin')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>the sys.path as printed in the error log is</p>
<blockquote>
<p>['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0', '/home/django/mofin/trunk', '/home/django/mofin/trunk/mofin']</p>
</blockquote>
<p>if I open an interactive shell with manage.py, sys.path is</p>
<blockquote>
<p>['/home/django/mofin/trunk/mofin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0']</p>
</blockquote>
<p>My django settings file looks like this:
# Django settings for mofin project.</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Dan xxxx', 'xxxx@yyyyyyyyyy.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'mofin' # Or path to database file if using sqlite3.
DATABASE_USER = 'aaaaaa' # Not used with sqlite3.
DATABASE_PASSWORD = 'bbbbbb' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-GB'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/django/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://mofin.mywebsite.co.uk/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'mofin.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mofin.store'
)
</code></pre>
| 62 | 2009-09-11T14:58:37Z | 8,722,325 | <p>(I wrote up this same answer for <a href="http://stackoverflow.com/questions/4462276/django-deployment-problem-in-apache-mod-wsgi-importerror-could-not-import-sett">Django deployment problem in Apache/mod_wsgi. ImportError: Could not import settings 'site.settings'</a> in case someone only finds this question.)</p>
<p>This doesn't appear to be the problem in your case, but I ran smack into the same ImportError when I used the WSGIPythonPath directive (instead of the .wsgi file) to set up <code>sys.path</code>. That worked fine until I switched to running WSGI in daemon mode. Once you do that, you have to use the <code>python-path</code> argument to the WSGIDaemonProcess directive instead.</p>
| 1 | 2012-01-04T05:15:31Z | [
"python",
"django",
"apache",
"wsgi"
] |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | <p>I can't get wsgi to import my settings file for my project 'mofin'.</p>
<p>The list of errors from the apache error log are as follows</p>
<pre><code>mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
self._import_settings()
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings
self._target = Settings(settings_module)
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'mofin.settings' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings
</code></pre>
<p>I got the "hello world!" wsgi app listed here(<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a>) to work fine. </p>
<p>The settings.py file loads fine with python manage.py (runserver|shell|syncdb|test store)
as does the application.</p>
<p>Here is my wsgi file:</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk')
sys.path.append('/home/django/mofin/trunk/mofin')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>the sys.path as printed in the error log is</p>
<blockquote>
<p>['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0', '/home/django/mofin/trunk', '/home/django/mofin/trunk/mofin']</p>
</blockquote>
<p>if I open an interactive shell with manage.py, sys.path is</p>
<blockquote>
<p>['/home/django/mofin/trunk/mofin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0']</p>
</blockquote>
<p>My django settings file looks like this:
# Django settings for mofin project.</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Dan xxxx', 'xxxx@yyyyyyyyyy.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'mofin' # Or path to database file if using sqlite3.
DATABASE_USER = 'aaaaaa' # Not used with sqlite3.
DATABASE_PASSWORD = 'bbbbbb' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-GB'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/django/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://mofin.mywebsite.co.uk/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'mofin.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mofin.store'
)
</code></pre>
| 62 | 2009-09-11T14:58:37Z | 12,176,522 | <p>Another cause of this problem is that you can't name your application the same as another python module. For example I called mine <code>site</code>, little realising that <code>site</code> is already a python module.</p>
<p>You can check this by starting python, and running <code>import site</code>, <code>help(site)</code>, and it will show you it isn't using your module. This of course gives you errors when django tries to import <code>site.settings</code> which doesn't exist.</p>
| 6 | 2012-08-29T11:06:32Z | [
"python",
"django",
"apache",
"wsgi"
] |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | <p>I can't get wsgi to import my settings file for my project 'mofin'.</p>
<p>The list of errors from the apache error log are as follows</p>
<pre><code>mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
self._import_settings()
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings
self._target = Settings(settings_module)
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'mofin.settings' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings
</code></pre>
<p>I got the "hello world!" wsgi app listed here(<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a>) to work fine. </p>
<p>The settings.py file loads fine with python manage.py (runserver|shell|syncdb|test store)
as does the application.</p>
<p>Here is my wsgi file:</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk')
sys.path.append('/home/django/mofin/trunk/mofin')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>the sys.path as printed in the error log is</p>
<blockquote>
<p>['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0', '/home/django/mofin/trunk', '/home/django/mofin/trunk/mofin']</p>
</blockquote>
<p>if I open an interactive shell with manage.py, sys.path is</p>
<blockquote>
<p>['/home/django/mofin/trunk/mofin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0']</p>
</blockquote>
<p>My django settings file looks like this:
# Django settings for mofin project.</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Dan xxxx', 'xxxx@yyyyyyyyyy.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'mofin' # Or path to database file if using sqlite3.
DATABASE_USER = 'aaaaaa' # Not used with sqlite3.
DATABASE_PASSWORD = 'bbbbbb' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-GB'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/django/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://mofin.mywebsite.co.uk/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'mofin.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mofin.store'
)
</code></pre>
| 62 | 2009-09-11T14:58:37Z | 16,637,106 | <p>Add two more lines of code </p>
<pre><code>sys.path.append('/home/django/mofin/mofin')
sys.path.append('/home/django/mofin/trunk/mofin/mofin')
</code></pre>
<p>to your wsgi file under the line:</p>
<pre><code>sys.path.append('/home/django/mofin/trunk/mofin/')
</code></pre>
| 0 | 2013-05-19T16:56:48Z | [
"python",
"django",
"apache",
"wsgi"
] |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | <p>I can't get wsgi to import my settings file for my project 'mofin'.</p>
<p>The list of errors from the apache error log are as follows</p>
<pre><code>mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
self._import_settings()
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings
self._target = Settings(settings_module)
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'mofin.settings' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings
</code></pre>
<p>I got the "hello world!" wsgi app listed here(<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a>) to work fine. </p>
<p>The settings.py file loads fine with python manage.py (runserver|shell|syncdb|test store)
as does the application.</p>
<p>Here is my wsgi file:</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk')
sys.path.append('/home/django/mofin/trunk/mofin')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>the sys.path as printed in the error log is</p>
<blockquote>
<p>['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0', '/home/django/mofin/trunk', '/home/django/mofin/trunk/mofin']</p>
</blockquote>
<p>if I open an interactive shell with manage.py, sys.path is</p>
<blockquote>
<p>['/home/django/mofin/trunk/mofin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0']</p>
</blockquote>
<p>My django settings file looks like this:
# Django settings for mofin project.</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Dan xxxx', 'xxxx@yyyyyyyyyy.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'mofin' # Or path to database file if using sqlite3.
DATABASE_USER = 'aaaaaa' # Not used with sqlite3.
DATABASE_PASSWORD = 'bbbbbb' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-GB'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/django/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://mofin.mywebsite.co.uk/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'mofin.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mofin.store'
)
</code></pre>
| 62 | 2009-09-11T14:58:37Z | 17,467,705 | <p>In my case, I had a <strong>circular import</strong> that was causing this error. From <code>settings.py</code> I was importing one function in another module, and from that module I was importing a settings variable. To fix it, instead of directly importing from settings, I did this:</p>
<pre><code>from django.conf import settings
</code></pre>
| 1 | 2013-07-04T10:15:56Z | [
"python",
"django",
"apache",
"wsgi"
] |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | <p>I can't get wsgi to import my settings file for my project 'mofin'.</p>
<p>The list of errors from the apache error log are as follows</p>
<pre><code>mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
self._import_settings()
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings
self._target = Settings(settings_module)
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'mofin.settings' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings
</code></pre>
<p>I got the "hello world!" wsgi app listed here(<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a>) to work fine. </p>
<p>The settings.py file loads fine with python manage.py (runserver|shell|syncdb|test store)
as does the application.</p>
<p>Here is my wsgi file:</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk')
sys.path.append('/home/django/mofin/trunk/mofin')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>the sys.path as printed in the error log is</p>
<blockquote>
<p>['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0', '/home/django/mofin/trunk', '/home/django/mofin/trunk/mofin']</p>
</blockquote>
<p>if I open an interactive shell with manage.py, sys.path is</p>
<blockquote>
<p>['/home/django/mofin/trunk/mofin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0']</p>
</blockquote>
<p>My django settings file looks like this:
# Django settings for mofin project.</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Dan xxxx', 'xxxx@yyyyyyyyyy.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'mofin' # Or path to database file if using sqlite3.
DATABASE_USER = 'aaaaaa' # Not used with sqlite3.
DATABASE_PASSWORD = 'bbbbbb' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-GB'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/django/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://mofin.mywebsite.co.uk/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'mofin.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mofin.store'
)
</code></pre>
| 62 | 2009-09-11T14:58:37Z | 19,991,779 | <p>I had a similar problem, solved it with the following snippet in my python:</p>
<pre><code>ALLDIRS = ['/var/www/MarkerDB/']
import sys
import site
# Remember original sys.path.
prev_sys_path = list(sys.path)
# Add each new site-packages directory.
for directory in ALLDIRS:
site.addsitedir(directory)
# Reorder sys.path so new directories at the front.
new_sys_path = []
for item in list(sys.path):
if item not in prev_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_pat
</code></pre>
<p>Source: <a href="http://code.google.com/p/modwsgi/wiki/VirtualEnvironments#Application_Environments" rel="nofollow">http://code.google.com/p/modwsgi/wiki/VirtualEnvironments#Application_Environments</a> </p>
| 0 | 2013-11-15T01:19:16Z | [
"python",
"django",
"apache",
"wsgi"
] |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | <p>I can't get wsgi to import my settings file for my project 'mofin'.</p>
<p>The list of errors from the apache error log are as follows</p>
<pre><code>mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
self._import_settings()
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings
self._target = Settings(settings_module)
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'mofin.settings' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings
</code></pre>
<p>I got the "hello world!" wsgi app listed here(<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a>) to work fine. </p>
<p>The settings.py file loads fine with python manage.py (runserver|shell|syncdb|test store)
as does the application.</p>
<p>Here is my wsgi file:</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk')
sys.path.append('/home/django/mofin/trunk/mofin')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>the sys.path as printed in the error log is</p>
<blockquote>
<p>['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0', '/home/django/mofin/trunk', '/home/django/mofin/trunk/mofin']</p>
</blockquote>
<p>if I open an interactive shell with manage.py, sys.path is</p>
<blockquote>
<p>['/home/django/mofin/trunk/mofin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0']</p>
</blockquote>
<p>My django settings file looks like this:
# Django settings for mofin project.</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Dan xxxx', 'xxxx@yyyyyyyyyy.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'mofin' # Or path to database file if using sqlite3.
DATABASE_USER = 'aaaaaa' # Not used with sqlite3.
DATABASE_PASSWORD = 'bbbbbb' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-GB'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/django/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://mofin.mywebsite.co.uk/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'mofin.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mofin.store'
)
</code></pre>
| 62 | 2009-09-11T14:58:37Z | 26,113,843 | <p>Let me add and my experience for that issue. After head banging for few hours and try all from the above answers I found that few lines in settings.py file cause the problem:</p>
<pre><code>from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^dynamicsites.fields.FolderNameField"])
add_introspection_rules([], ["^dynamicsites.fields.SubdomainListField"])
</code></pre>
<p>After that I made copy of the settings.py, named scripts_settings.py whithout that lines, and used that file and everything is ok now.</p>
| 1 | 2014-09-30T06:04:48Z | [
"python",
"django",
"apache",
"wsgi"
] |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | <p>I can't get wsgi to import my settings file for my project 'mofin'.</p>
<p>The list of errors from the apache error log are as follows</p>
<pre><code>mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
self._import_settings()
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings
self._target = Settings(settings_module)
File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'mofin.settings' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings
</code></pre>
<p>I got the "hello world!" wsgi app listed here(<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a>) to work fine. </p>
<p>The settings.py file loads fine with python manage.py (runserver|shell|syncdb|test store)
as does the application.</p>
<p>Here is my wsgi file:</p>
<pre><code>import os
import sys
sys.path.append('/home/django/mofin/trunk')
sys.path.append('/home/django/mofin/trunk/mofin')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'mofin.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>the sys.path as printed in the error log is</p>
<blockquote>
<p>['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0', '/home/django/mofin/trunk', '/home/django/mofin/trunk/mofin']</p>
</blockquote>
<p>if I open an interactive shell with manage.py, sys.path is</p>
<blockquote>
<p>['/home/django/mofin/trunk/mofin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/gtk-2.0']</p>
</blockquote>
<p>My django settings file looks like this:
# Django settings for mofin project.</p>
<pre><code>DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Dan xxxx', 'xxxx@yyyyyyyyyy.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'mofin' # Or path to database file if using sqlite3.
DATABASE_USER = 'aaaaaa' # Not used with sqlite3.
DATABASE_PASSWORD = 'bbbbbb' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-GB'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/home/django/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = 'http://mofin.mywebsite.co.uk/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'mofin.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mofin.store'
)
</code></pre>
| 62 | 2009-09-11T14:58:37Z | 31,500,959 | <p>I just had this error and the solution was to enable my virtual environment via myvenv/source/activate. </p>
| 0 | 2015-07-19T11:59:53Z | [
"python",
"django",
"apache",
"wsgi"
] |
Having problem with IronPython to instantiate a class in IronPython Console | 1,411,442 | <p>I'm trying to learn IronPython. I created an extremely simple class like this one:</p>
<pre><code>class Test:
def testMethod(self):
print "test"
</code></pre>
<p>Next I'm trying to use it in IronPython Console:</p>
<pre><code>>>> import Test
>>> t = Test()
</code></pre>
<p>After the second line I get following error:</p>
<blockquote>
<p>TypeError: Scope is not callable</p>
</blockquote>
<p>What I'm doing wrong?</p>
| 1 | 2009-09-11T15:01:34Z | 1,411,539 | <p>you need to <code>from filename import Test</code> where filename is a basename of file class Test is saved in.</p>
<p>e.g.: class <code>Test</code> is saved in <code>test.py</code></p>
<p>then:</p>
<pre><code>from test import Test
t = Test()
</code></pre>
<p>will run as expected.</p>
| 4 | 2009-09-11T15:13:19Z | [
"python",
"ironpython"
] |
Having problem with IronPython to instantiate a class in IronPython Console | 1,411,442 | <p>I'm trying to learn IronPython. I created an extremely simple class like this one:</p>
<pre><code>class Test:
def testMethod(self):
print "test"
</code></pre>
<p>Next I'm trying to use it in IronPython Console:</p>
<pre><code>>>> import Test
>>> t = Test()
</code></pre>
<p>After the second line I get following error:</p>
<blockquote>
<p>TypeError: Scope is not callable</p>
</blockquote>
<p>What I'm doing wrong?</p>
| 1 | 2009-09-11T15:01:34Z | 1,411,543 | <p><code>import Test</code> loads the module named Test, defined in a file called Test.py(c|d). This module in turn contains your class named Test. You're trying to instantiate the module called Test. To instantiate the class Test in module Test, you need to use:</p>
<p>t = Test.Test()</p>
<p>This concept can be quite tricky, especially if you have a background in other languages. Took me a while to figure out too :)</p>
| 2 | 2009-09-11T15:13:41Z | [
"python",
"ironpython"
] |
Help with basic Python function | 1,411,553 | <p>I have a function to connect to a database. This code works:</p>
<pre><code>def connect():
return MySQLdb.connect("example.com", "username", "password", "database")
</code></pre>
<p>But this doesn't:</p>
<pre><code>def connect():
host = "example.com"
user = "username"
pass = "password"
base = "database"
return MySQLdb.connect(host, user, pass, base)
</code></pre>
<p>Why so?</p>
| 4 | 2009-09-11T15:15:28Z | 1,411,569 | <p><code>pass</code> is a reserved keyword. </p>
<p>Pick different variable names and your code should work fine.<br/>
Maybe something like:</p>
<pre><code>def connect():
_host = "example.com"
_user = "username"
_pass = "password"
_base = "database"
return MySQLdb.connect(_host, _user, _pass, _base)
</code></pre>
| 9 | 2009-09-11T15:17:30Z | [
"python"
] |
How to get '\x01' to 1 | 1,411,658 | <p>I am getting this:</p>
<pre><code>_format_ = "7c7sc"
print struct.unpack(self._format_, data)
</code></pre>
<p>gives</p>
<pre><code>('\x7f', 'E', 'L', 'F', '\x01', '\x01', '\x01', '\x00\x00\x00\x00\x00\x00\x00', '\x00')
</code></pre>
<p>I want to take <code>'\x01'</code> and get 1 from it, i.e., convert to ``int. Any ideas?
Thanks</p>
| 4 | 2009-09-11T15:34:02Z | 1,411,678 | <p><code>ord("\x01")</code> will return 1.</p>
| 13 | 2009-09-11T15:37:28Z | [
"python"
] |
How to get '\x01' to 1 | 1,411,658 | <p>I am getting this:</p>
<pre><code>_format_ = "7c7sc"
print struct.unpack(self._format_, data)
</code></pre>
<p>gives</p>
<pre><code>('\x7f', 'E', 'L', 'F', '\x01', '\x01', '\x01', '\x00\x00\x00\x00\x00\x00\x00', '\x00')
</code></pre>
<p>I want to take <code>'\x01'</code> and get 1 from it, i.e., convert to ``int. Any ideas?
Thanks</p>
| 4 | 2009-09-11T15:34:02Z | 1,411,684 | <p>Perhaps you are thinking of the <code>ord</code> function?</p>
<pre><code>>>> ord("\x01")
1
>>> ord("\x02")
2
>>> ord("\x7f")
127
</code></pre>
| 3 | 2009-09-11T15:38:52Z | [
"python"
] |
What difference it makes when I set python thread as a Deamon | 1,411,860 | <p>What difference it makes when I set python thread as a Deamon, using thread.setDaemon(True) ?</p>
| 7 | 2009-09-11T16:08:29Z | 1,412,230 | <p>A daemon thread will not prevent the application from exiting. The program ends when all non-daemon threads (main thread included) are complete.</p>
<p>So generally, if you're doing something in the background, you might want to set the thread as daemon so you don't have to explicitly have that thread's function return before the app can exit.</p>
<p>For example, if you are writing a GUI application and the user closes the main window, the program should quit. But if you have non-daemon threads hanging around, it won't.</p>
<p>From the docs: <a href="http://docs.python.org/library/threading.html#threading.Thread.daemon">http://docs.python.org/library/threading.html#threading.Thread.daemon</a></p>
<blockquote>
<p>Its initial value is inherited from
the creating thread; the main thread
is not a daemon thread and therefore
all threads created in the main thread
default to daemon = False.</p>
<p>The entire Python program exits when
no alive non-daemon threads are left.</p>
</blockquote>
| 14 | 2009-09-11T17:20:46Z | [
"python",
"multithreading",
"daemon"
] |
Python CGI returning an http status code, such as 403? | 1,411,867 | <p>How can my python cgi return a specific http status code, such as 403 or 418? </p>
<p>I tried the obvious (print "Status:403 Forbidden") but it doesn't work.</p>
| 14 | 2009-09-11T16:09:29Z | 1,411,902 | <p>I guess, you're looking for <a href="http://docs.python.org/library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.send%5Ferror" rel="nofollow"><code>send_error</code></a>. It would be located in <a href="http://docs.python.org/3.1/library/http.server.html#http.server.BaseHTTPRequestHandler.send%5Ferror" rel="nofollow"><code>http.server</code></a> in py3k.</p>
| 1 | 2009-09-11T16:14:22Z | [
"python",
"http",
"cgi",
"http-status-codes"
] |
Python CGI returning an http status code, such as 403? | 1,411,867 | <p>How can my python cgi return a specific http status code, such as 403 or 418? </p>
<p>I tried the obvious (print "Status:403 Forbidden") but it doesn't work.</p>
| 14 | 2009-09-11T16:09:29Z | 1,411,969 | <pre><code>print 'Status: 403 Forbidden'
print
</code></pre>
<p>Works for me. You do need the second print though, as you need a double-newline to end the HTTP response headers. Otherwise your web server may complain you aren't sending it a complete set of headers.</p>
<pre><code>sys.stdout('Status: 403 Forbidden\r\n\r\n')
</code></pre>
<p>may be technically more correct, according to RFC (assuming that your CGI script isn't running in text mode on Windows). However both line endings seem to work everywhere.</p>
| 16 | 2009-09-11T16:27:50Z | [
"python",
"http",
"cgi",
"http-status-codes"
] |
Python: what's the pythonic way to perform this loop? | 1,411,943 | <p>What is the pythonic way to perform this loop. I'm trying to pick a random key that will return a subtree and not the root. Hence: 'parent == None' cannot be true. Nor can 'isRoot==True' be true.</p>
<pre><code>thekey = random.choice(tree.thedict.keys())
while (tree.thedict[thekey].parent == None)or(tree.thedict[thekey].isRoot == True):
thekey = random.choice(tree.thedict.keys())
.......
</code></pre>
<p>edit: it works now</p>
| 1 | 2009-09-11T16:21:11Z | 1,411,970 | <pre><code>thekey = random.choice(tree.thedict.keys())
parent = thedict[thekey].parent
while parent is None or parent.isRoot:
thekey = random.choice(tree.thedict.keys())
parent = thedict[thekey].parent
</code></pre>
| 1 | 2009-09-11T16:27:53Z | [
"python"
] |
Python: what's the pythonic way to perform this loop? | 1,411,943 | <p>What is the pythonic way to perform this loop. I'm trying to pick a random key that will return a subtree and not the root. Hence: 'parent == None' cannot be true. Nor can 'isRoot==True' be true.</p>
<pre><code>thekey = random.choice(tree.thedict.keys())
while (tree.thedict[thekey].parent == None)or(tree.thedict[thekey].isRoot == True):
thekey = random.choice(tree.thedict.keys())
.......
</code></pre>
<p>edit: it works now</p>
| 1 | 2009-09-11T16:21:11Z | 1,411,980 | <blockquote>
<p>get a random subtree that is not the
root</p>
</blockquote>
<pre><code>not_root_nodes = [key, node for key,node in tree.thedict.iteritems() if not ( node.parent is None or node.isRoot)]
item = random.choice( not_root_nodes )
</code></pre>
| 3 | 2009-09-11T16:29:30Z | [
"python"
] |
Python: what's the pythonic way to perform this loop? | 1,411,943 | <p>What is the pythonic way to perform this loop. I'm trying to pick a random key that will return a subtree and not the root. Hence: 'parent == None' cannot be true. Nor can 'isRoot==True' be true.</p>
<pre><code>thekey = random.choice(tree.thedict.keys())
while (tree.thedict[thekey].parent == None)or(tree.thedict[thekey].isRoot == True):
thekey = random.choice(tree.thedict.keys())
.......
</code></pre>
<p>edit: it works now</p>
| 1 | 2009-09-11T16:21:11Z | 1,411,982 | <pre><code>key = random.choice([key for key, subtree in tree.thedict.items()
if subtree.parent and not subtree.isRoot])
</code></pre>
<p>(Corrected after comments and question edition)</p>
| 3 | 2009-09-11T16:29:47Z | [
"python"
] |
Python: what's the pythonic way to perform this loop? | 1,411,943 | <p>What is the pythonic way to perform this loop. I'm trying to pick a random key that will return a subtree and not the root. Hence: 'parent == None' cannot be true. Nor can 'isRoot==True' be true.</p>
<pre><code>thekey = random.choice(tree.thedict.keys())
while (tree.thedict[thekey].parent == None)or(tree.thedict[thekey].isRoot == True):
thekey = random.choice(tree.thedict.keys())
.......
</code></pre>
<p>edit: it works now</p>
| 1 | 2009-09-11T16:21:11Z | 1,411,987 | <p>I think that's a bit better:</p>
<pre><code>theDict = tree.thedict
def getKey():
return random.choice(theDict.keys())
theKey = getKey()
while theDict[thekey].parent in (None, True):
thekey = getKey()
</code></pre>
<p>What do you think?</p>
| 1 | 2009-09-11T16:30:30Z | [
"python"
] |
Python: what's the pythonic way to perform this loop? | 1,411,943 | <p>What is the pythonic way to perform this loop. I'm trying to pick a random key that will return a subtree and not the root. Hence: 'parent == None' cannot be true. Nor can 'isRoot==True' be true.</p>
<pre><code>thekey = random.choice(tree.thedict.keys())
while (tree.thedict[thekey].parent == None)or(tree.thedict[thekey].isRoot == True):
thekey = random.choice(tree.thedict.keys())
.......
</code></pre>
<p>edit: it works now</p>
| 1 | 2009-09-11T16:21:11Z | 1,412,006 | <pre><code>def is_root(v):
assert (v.parent != None) == (v.isRoot)
return v.isRoot
#note how dumb this function looks when you guarantee that assertion
def get_random_nonroot_key():
while True:
thekey = random.choice(tree.thedict.keys())
value = tree.thedict[thekey]
if not is_root(value): return key
</code></pre>
<p>or a refactoring of Roberto Bonvallet's answer</p>
<pre><code>def get_random_nonroot_key():
eligible_keys = [k for k, v in tree.thedict.items() if not is_root(v)]
return random.choice(eligible_keys)
</code></pre>
| 0 | 2009-09-11T16:34:49Z | [
"python"
] |
Python: what's the pythonic way to perform this loop? | 1,411,943 | <p>What is the pythonic way to perform this loop. I'm trying to pick a random key that will return a subtree and not the root. Hence: 'parent == None' cannot be true. Nor can 'isRoot==True' be true.</p>
<pre><code>thekey = random.choice(tree.thedict.keys())
while (tree.thedict[thekey].parent == None)or(tree.thedict[thekey].isRoot == True):
thekey = random.choice(tree.thedict.keys())
.......
</code></pre>
<p>edit: it works now</p>
| 1 | 2009-09-11T16:21:11Z | 1,412,020 | <p>I think your while condition is flawed:</p>
<p>I think you expect this: <strong><code>tree.thedict[thekey].parent == None</code></strong><br />
should be equal to this: <strong><code>tree.thedict[thekey].parent.isRoot == True</code></strong></p>
<p>When in fact, for both to mean "this node is not the root", you should change the second statement to: <strong><code>tree.thedict[thekey].isRoot == True</code></strong></p>
<p>As written, your conditional test says "while this node is the root OR this node's parent is the root". If your tree structure is a single root node with many leaf nodes, you should expect an infinite loop in this case.</p>
<p>Here's a rewrite:</p>
<pre><code>thekey = random.choice(k for k in tree.thedict.keys() if not k.isRoot)
</code></pre>
| 0 | 2009-09-11T16:38:02Z | [
"python"
] |
Python: what's the pythonic way to perform this loop? | 1,411,943 | <p>What is the pythonic way to perform this loop. I'm trying to pick a random key that will return a subtree and not the root. Hence: 'parent == None' cannot be true. Nor can 'isRoot==True' be true.</p>
<pre><code>thekey = random.choice(tree.thedict.keys())
while (tree.thedict[thekey].parent == None)or(tree.thedict[thekey].isRoot == True):
thekey = random.choice(tree.thedict.keys())
.......
</code></pre>
<p>edit: it works now</p>
| 1 | 2009-09-11T16:21:11Z | 1,412,054 | <pre><code>thekey = random.choice(tree.thedict.keys())
parent = tree.thedict[thekey].parent
while parent is None or tree.thedict[thekey].isRoot:
thekey = random.choice(tree.thedict.keys())
parent = thedict[thekey].parent
</code></pre>
| 0 | 2009-09-11T16:47:08Z | [
"python"
] |
Python: what's the pythonic way to perform this loop? | 1,411,943 | <p>What is the pythonic way to perform this loop. I'm trying to pick a random key that will return a subtree and not the root. Hence: 'parent == None' cannot be true. Nor can 'isRoot==True' be true.</p>
<pre><code>thekey = random.choice(tree.thedict.keys())
while (tree.thedict[thekey].parent == None)or(tree.thedict[thekey].isRoot == True):
thekey = random.choice(tree.thedict.keys())
.......
</code></pre>
<p>edit: it works now</p>
| 1 | 2009-09-11T16:21:11Z | 1,412,844 | <p>Personally, I don't like the repetition of initializing thekey before the while loop and then again inside the loop. It's a possible source of bugs; what happens if someone edits one of the two initializations and forgets to edit the other? Even if that never happens, anyone reading the code needs to check carefully to make sure both initializations match perfectly.</p>
<p>I would write it like so:</p>
<pre><code>while True:
thekey = random.choice(tree.thedict.keys())
subtree = tree.thedict[thekey]
if subtree.parent is not None and not subtree.isRoot:
break
</code></pre>
<p>P.S. If you really just want the subtree, and don't care about the key needed to lookup the subtree, you could even do this:</p>
<pre><code>while True:
subtree = random.choice(tree.thedict.values())
if subtree.parent is not None and not subtree.isRoot:
break
</code></pre>
<p>Some people may not like the use of "<code>while True:</code>" but that is the standard Python idiom for "loop forever until something runs <code>break</code>". IMHO this is simple, clear, idiomatic Python.</p>
<p>P.P.S. This code should really be wrapped in an if statement that checks that the tree has more than one node. If the tree only has a root node, this code would loop forever.</p>
| 0 | 2009-09-11T19:27:17Z | [
"python"
] |
Reading XML using Python minidom and iterating over each node | 1,412,004 | <p>I have an XML structure that looks like the following, but on a much larger scale:</p>
<pre><code><root>
<conference name='1'>
<author>
Bob
</author>
<author>
Nigel
</author>
</conference>
<conference name='2'>
<author>
Alice
</author>
<author>
Mary
</author>
</conference>
</root>
</code></pre>
<p>For this, I used the following code:</p>
<pre><code>dom = parse(filepath)
conference=dom.getElementsByTagName('conference')
for node in conference:
conf_name=node.getAttribute('name')
print conf_name
alist=node.getElementsByTagName('author')
for a in alist:
authortext= a.nodeValue
print authortext
</code></pre>
<p>However, the authortext that is printed out is 'None.' I tried messing around with using variations like what is below, but it causes my program to break.</p>
<pre><code>authortext=a[0].nodeValue
</code></pre>
<p>The correct output should be:</p>
<pre><code>1
Bob
Nigel
2
Alice
Mary
</code></pre>
<p>But what I get is:</p>
<pre><code>1
None
None
2
None
None
</code></pre>
<p>Any suggestions on how to tackle this problem?</p>
| 21 | 2009-09-11T16:34:26Z | 1,412,150 | <p>I played around with it a bit, and here's what I got to work:</p>
<pre><code># ...
authortext= a.childNodes[0].nodeValue
print authortext
</code></pre>
<p>leading to output of:</p>
<pre>
C:\temp\py>xml2.py
1
Bob
Nigel
2
Alice
Mary
</pre>
<p>I can't tell you exactly why you have to access the childNode to get the inner text, but at least that's what you were looking for.</p>
| 0 | 2009-09-11T17:05:12Z | [
"python",
"xml",
"parsing",
"minidom"
] |
Reading XML using Python minidom and iterating over each node | 1,412,004 | <p>I have an XML structure that looks like the following, but on a much larger scale:</p>
<pre><code><root>
<conference name='1'>
<author>
Bob
</author>
<author>
Nigel
</author>
</conference>
<conference name='2'>
<author>
Alice
</author>
<author>
Mary
</author>
</conference>
</root>
</code></pre>
<p>For this, I used the following code:</p>
<pre><code>dom = parse(filepath)
conference=dom.getElementsByTagName('conference')
for node in conference:
conf_name=node.getAttribute('name')
print conf_name
alist=node.getElementsByTagName('author')
for a in alist:
authortext= a.nodeValue
print authortext
</code></pre>
<p>However, the authortext that is printed out is 'None.' I tried messing around with using variations like what is below, but it causes my program to break.</p>
<pre><code>authortext=a[0].nodeValue
</code></pre>
<p>The correct output should be:</p>
<pre><code>1
Bob
Nigel
2
Alice
Mary
</code></pre>
<p>But what I get is:</p>
<pre><code>1
None
None
2
None
None
</code></pre>
<p>Any suggestions on how to tackle this problem?</p>
| 21 | 2009-09-11T16:34:26Z | 1,412,170 | <p>your <code>authortext</code> is of type 1 (<code>ELEMENT_NODE</code>), normally you need to have <code>TEXT_NODE</code> to get a string. This will work</p>
<pre><code>a.childNodes[0].nodeValue
</code></pre>
| 21 | 2009-09-11T17:10:00Z | [
"python",
"xml",
"parsing",
"minidom"
] |
Reading XML using Python minidom and iterating over each node | 1,412,004 | <p>I have an XML structure that looks like the following, but on a much larger scale:</p>
<pre><code><root>
<conference name='1'>
<author>
Bob
</author>
<author>
Nigel
</author>
</conference>
<conference name='2'>
<author>
Alice
</author>
<author>
Mary
</author>
</conference>
</root>
</code></pre>
<p>For this, I used the following code:</p>
<pre><code>dom = parse(filepath)
conference=dom.getElementsByTagName('conference')
for node in conference:
conf_name=node.getAttribute('name')
print conf_name
alist=node.getElementsByTagName('author')
for a in alist:
authortext= a.nodeValue
print authortext
</code></pre>
<p>However, the authortext that is printed out is 'None.' I tried messing around with using variations like what is below, but it causes my program to break.</p>
<pre><code>authortext=a[0].nodeValue
</code></pre>
<p>The correct output should be:</p>
<pre><code>1
Bob
Nigel
2
Alice
Mary
</code></pre>
<p>But what I get is:</p>
<pre><code>1
None
None
2
None
None
</code></pre>
<p>Any suggestions on how to tackle this problem?</p>
| 21 | 2009-09-11T16:34:26Z | 1,412,173 | <p>Element nodes don't have a nodeValue. You have to look at the Text nodes inside them. If you know there's always one text node inside you can say <code>element.firstChild.data</code> (data is the same as nodeValue for text nodes).</p>
<p>Be careful: if there is no text content there will be no child Text nodes and <code>element.firstChild</code> will be null, causing the <code>.data</code> access to fail.</p>
<p>Quick way to get the content of direct child text nodes:</p>
<pre><code>text= ''.join(child.data for child in element.childNodes if child.nodeType==child.TEXT_NODE)
</code></pre>
<p>In DOM Level 3 Core you get the <code>textContent</code> property you can use to get text from inside an Element recursively, but minidom doesn't support this (some other Python DOM implementations do).</p>
| 6 | 2009-09-11T17:10:16Z | [
"python",
"xml",
"parsing",
"minidom"
] |
Reading XML using Python minidom and iterating over each node | 1,412,004 | <p>I have an XML structure that looks like the following, but on a much larger scale:</p>
<pre><code><root>
<conference name='1'>
<author>
Bob
</author>
<author>
Nigel
</author>
</conference>
<conference name='2'>
<author>
Alice
</author>
<author>
Mary
</author>
</conference>
</root>
</code></pre>
<p>For this, I used the following code:</p>
<pre><code>dom = parse(filepath)
conference=dom.getElementsByTagName('conference')
for node in conference:
conf_name=node.getAttribute('name')
print conf_name
alist=node.getElementsByTagName('author')
for a in alist:
authortext= a.nodeValue
print authortext
</code></pre>
<p>However, the authortext that is printed out is 'None.' I tried messing around with using variations like what is below, but it causes my program to break.</p>
<pre><code>authortext=a[0].nodeValue
</code></pre>
<p>The correct output should be:</p>
<pre><code>1
Bob
Nigel
2
Alice
Mary
</code></pre>
<p>But what I get is:</p>
<pre><code>1
None
None
2
None
None
</code></pre>
<p>Any suggestions on how to tackle this problem?</p>
| 21 | 2009-09-11T16:34:26Z | 18,661,632 | <p>Quick access:</p>
<pre><code>node.getElementsByTagName('author')[0].childNodes[0].nodeValue
</code></pre>
| 2 | 2013-09-06T15:46:15Z | [
"python",
"xml",
"parsing",
"minidom"
] |
Reading XML using Python minidom and iterating over each node | 1,412,004 | <p>I have an XML structure that looks like the following, but on a much larger scale:</p>
<pre><code><root>
<conference name='1'>
<author>
Bob
</author>
<author>
Nigel
</author>
</conference>
<conference name='2'>
<author>
Alice
</author>
<author>
Mary
</author>
</conference>
</root>
</code></pre>
<p>For this, I used the following code:</p>
<pre><code>dom = parse(filepath)
conference=dom.getElementsByTagName('conference')
for node in conference:
conf_name=node.getAttribute('name')
print conf_name
alist=node.getElementsByTagName('author')
for a in alist:
authortext= a.nodeValue
print authortext
</code></pre>
<p>However, the authortext that is printed out is 'None.' I tried messing around with using variations like what is below, but it causes my program to break.</p>
<pre><code>authortext=a[0].nodeValue
</code></pre>
<p>The correct output should be:</p>
<pre><code>1
Bob
Nigel
2
Alice
Mary
</code></pre>
<p>But what I get is:</p>
<pre><code>1
None
None
2
None
None
</code></pre>
<p>Any suggestions on how to tackle this problem?</p>
| 21 | 2009-09-11T16:34:26Z | 35,292,416 | <p>Since you always have one text data value per author you can use element.firstChild.data</p>
<pre><code>dom = parseString(document)
conferences = dom.getElementsByTagName("conference")
# Each conference here is a node
for conference in conferences:
conference_name = conference.getAttribute("name")
print
print conference_name.upper() + " - "
authors = conference.getElementsByTagName("author")
for author in authors:
print " ", author.firstChild.data
# for
print
</code></pre>
| 0 | 2016-02-09T12:43:14Z | [
"python",
"xml",
"parsing",
"minidom"
] |
Custom QStyledItemDelegate: adding bold items | 1,412,156 | <p>So here's the story:</p>
<p>I have a QListview that uses a QSqlQueryModel to fill it up. Because some items should display in bold based on the value of a hidden column of the model, I decided to make my own custom delegate. I'm using PyQT 4.5.4 and thus inheriting from QStyledItemDelegate is the way to go according to the docs. I got it working but there are some problems with it. </p>
<p>Here's my solution:</p>
<pre><code>class TypeSoortDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
model = index.model()
record = model.record(index.row())
value= record.value(2).toPyObject()
if value:
painter.save()
# change the back- and foreground colors
# if the item is selected
if option.state & QStyle.State_Selected:
painter.setPen(QPen(Qt.NoPen))
painter.setBrush(QApplication.palette().highlight())
painter.drawRect(option.rect)
painter.restore()
painter.save()
font = painter.font
pen = painter.pen()
pen.setColor(QApplication.palette().color(QPalette.HighlightedText))
painter.setPen(pen)
else:
painter.setPen(QPen(Qt.black))
# set text bold
font = painter.font()
font.setWeight(QFont.Bold)
painter.setFont(font)
text = record.value(1).toPyObject()
painter.drawText(option.rect, Qt.AlignLeft, text)
painter.restore()
else:
QStyledItemDelegate.paint(self, painter, option, index)
</code></pre>
<p>The problems I'm facing now:</p>
<ol>
<li>the normal (not bold) items are
slightly indented (a few pixels).
This is probably some default
behaviour. I could indent my item in
bold also, but what happens then
under a different platform? </li>
<li>Normally when I select items there is a small border with a dotted line around it (default Windows thing?). Here also I could draw it, but I want to stay as native as possible. </li>
</ol>
<p>Now the question:</p>
<p>Is there another way to create a custom delegate that only changes the font weight when some condition is met and leaves all the rest untouched?</p>
<p>I also tried:</p>
<pre><code>if value:
font = painter.font()
font.setWeight(QFont.Bold)
painter.setFont(font)
QStyledItemDelegate.paint(self, painter, option, index)
</code></pre>
<p>But that doesn't seem to affect the looks at all. No error, just default behaviour, and no bold items.</p>
<p>All suggestions welcome!</p>
| 4 | 2009-09-11T17:06:36Z | 1,466,123 | <p>I've not tested this, but I think you can do:</p>
<pre><code>class TypeSoortDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
get value...
if value:
option.font.setWeight(QFont.Bold)
QStyledItemDelegate.paint(self, painter, option, index)
</code></pre>
| 3 | 2009-09-23T13:48:35Z | [
"python",
"user-interface",
"pyqt"
] |
Twisted(asynch server) vs Django(or any other framework) | 1,412,169 | <p>I need help understanding what the advantage of using an asynch framework is. Suppose I want to develop a simple chat web app. Why cant I write python code in the Django framework that does long polling where I dont send a response back the server until someone enters a new msg. What does Twisted provide that gives it an advantage for real-time apps like the chat app?</p>
<p>Sorry I am obviously little confused about the need for an asynchronous framework.</p>
| 13 | 2009-09-11T17:09:48Z | 1,412,226 | <p>Asynchronous servers support much larger numbers of simultaneous client connections. More conventional servers come up against thread and process limits when servicing large number of concurrent clients, particularly those with long-lived connections. Async servers can also provide better performance as they avoid the overheads of e.g. thread context switching.</p>
<p>As well as the <code>Twisted</code> framework, there are also asynchronous server building blocks in Python's standard library: previously <code>asyncore</code> and <code>asynchat</code>, but now also <code>asyncio</code>.</p>
| 14 | 2009-09-11T17:20:23Z | [
"python",
"django",
"asynchronous",
"twisted",
"real-time"
] |
Twisted(asynch server) vs Django(or any other framework) | 1,412,169 | <p>I need help understanding what the advantage of using an asynch framework is. Suppose I want to develop a simple chat web app. Why cant I write python code in the Django framework that does long polling where I dont send a response back the server until someone enters a new msg. What does Twisted provide that gives it an advantage for real-time apps like the chat app?</p>
<p>Sorry I am obviously little confused about the need for an asynchronous framework.</p>
| 13 | 2009-09-11T17:09:48Z | 1,412,372 | <p>First off Django is a framework for writing web apps so it provides ORM, html templating, it requires running an http server etc. Twisted helps to write much lower level code than that. You could use twisted to write the http server Django runs on. If you use Django you are limited to http model, with twisted it could be communicating in any protocol you like including push protocols. So for your chat example you get a server that scales better since it can push comments to people who have logged in VS with django every client having to poll repeatedly.</p>
<p>edited to reflect comments by: sos-skyl</p>
| 18 | 2009-09-11T17:50:55Z | [
"python",
"django",
"asynchronous",
"twisted",
"real-time"
] |
Twisted(asynch server) vs Django(or any other framework) | 1,412,169 | <p>I need help understanding what the advantage of using an asynch framework is. Suppose I want to develop a simple chat web app. Why cant I write python code in the Django framework that does long polling where I dont send a response back the server until someone enters a new msg. What does Twisted provide that gives it an advantage for real-time apps like the chat app?</p>
<p>Sorry I am obviously little confused about the need for an asynchronous framework.</p>
| 13 | 2009-09-11T17:09:48Z | 1,413,098 | <p>You could use <a href="http://aaron.oirt.rutgers.edu/myapp/docs/W.intro" rel="nofollow">WHIFF</a> instead of either :). Check out
<a href="http://aaron.oirt.rutgers.edu/myapp/gfChat/nucularChatRoom" rel="nofollow">http://aaron.oirt.rutgers.edu/myapp/gfChat/nucularChatRoom</a>
which uses a javascript polling loop with json to check
for server updates. You could probably do something similar
in Django, but I don't know how because I gave up on Django.</p>
<p>btw: I'm hoping to move this demo onto the google app engine
as a more complete service when
my life calms down a bit.</p>
| 0 | 2009-09-11T20:26:20Z | [
"python",
"django",
"asynchronous",
"twisted",
"real-time"
] |
Twisted(asynch server) vs Django(or any other framework) | 1,412,169 | <p>I need help understanding what the advantage of using an asynch framework is. Suppose I want to develop a simple chat web app. Why cant I write python code in the Django framework that does long polling where I dont send a response back the server until someone enters a new msg. What does Twisted provide that gives it an advantage for real-time apps like the chat app?</p>
<p>Sorry I am obviously little confused about the need for an asynchronous framework.</p>
| 13 | 2009-09-11T17:09:48Z | 1,413,820 | <p>If you'd like to look at some source for integrating Twisted and Django, have a look at <a href="http://zork.net/motd/nick/django/introducing-yardbird.html" rel="nofollow">Yardbird</a>.</p>
| 0 | 2009-09-12T00:12:24Z | [
"python",
"django",
"asynchronous",
"twisted",
"real-time"
] |
Twisted(asynch server) vs Django(or any other framework) | 1,412,169 | <p>I need help understanding what the advantage of using an asynch framework is. Suppose I want to develop a simple chat web app. Why cant I write python code in the Django framework that does long polling where I dont send a response back the server until someone enters a new msg. What does Twisted provide that gives it an advantage for real-time apps like the chat app?</p>
<p>Sorry I am obviously little confused about the need for an asynchronous framework.</p>
| 13 | 2009-09-11T17:09:48Z | 1,417,358 | <p>In twisted you can implement protocols of your own. Django certainly can't do this.</p>
| 2 | 2009-09-13T10:07:24Z | [
"python",
"django",
"asynchronous",
"twisted",
"real-time"
] |
Twisted(asynch server) vs Django(or any other framework) | 1,412,169 | <p>I need help understanding what the advantage of using an asynch framework is. Suppose I want to develop a simple chat web app. Why cant I write python code in the Django framework that does long polling where I dont send a response back the server until someone enters a new msg. What does Twisted provide that gives it an advantage for real-time apps like the chat app?</p>
<p>Sorry I am obviously little confused about the need for an asynchronous framework.</p>
| 13 | 2009-09-11T17:09:48Z | 1,468,718 | <p>The biggest advantage for me is that Twisted gives me an application that has state, and can communicate with many different clients using many protocols. For more information, see my blog entry on <a href="http://blog.gridspy.co.nz/2009/09/database-meet-realtime-data-logging.html">Why I choose twisted over using a database as the core of my power monitoring system</a>.</p>
<p>For me, my Twisted server communicates with a number of sensors installed in houses and businesses that monitor power usage. It stores the data and keeps recent data and state in handy-dandy python classes in memory. Requests via xmlrpc from django get this state and can present recent data to the user. My Gridspy stuff is still in development so the actual site at your.gridspy.co.nz is a bit pre-alpha.</p>
<p>The best part is that you need surprisingly little code to make an effective server. An amazing amount of the work is done for you.</p>
| 5 | 2009-09-23T21:53:32Z | [
"python",
"django",
"asynchronous",
"twisted",
"real-time"
] |
Python decorate a class to change parent object type | 1,412,210 | <p>Suppose you have two classes X & Y. You want to decorate those classes by adding attributes to the class to produce new classes X1 and Y1.</p>
<p>For example:</p>
<pre><code>class X1(X):
new_attribute = 'something'
class Y1(Y):
new_attribute = 'something'
</code></pre>
<p>*new_attribute* will always be the same for both X1 and Y1. X & Y are not related in any meaningful way, except that multiple inheritance is not possible. There are a set of other attributes as well, but this is degenerate to illustrate.</p>
<p>I feel like I'm overcomplicating this, but I had thought to use a decorator, somewhat likeso:</p>
<pre><code>def _xywrap(cls):
class _xy(cls):
new_attribute = 'something'
return _xy
@_xywrap(X)
class X1():
pass
@_xywrap(Y)
class Y1():
pass
</code></pre>
<p>It feels like I'm missing a fairly common pattern, and I'd be much obliged for thoughts, input and feedback.</p>
<p>Thank you for reading.</p>
<p>Brian</p>
<p><strong>EDIT:</strong> Example:</p>
<p>Here is a relevant extract that may illuminate. The common classes are as follows:</p>
<pre><code>from google.appengine.ext import db
# I'm including PermittedUserProperty because it may have pertinent side-effects
# (albeit unlikely), which is documented here: [How can you limit access to a
# GAE instance to the current user][1].
class _AccessBase:
users_permitted = PermittedUserProperty()
owner = db.ReferenceProperty(User)
class AccessModel(db.Model, _AccessBase):
pass
class AccessExpando(db.Expando, _AccessBase):
pass
# the order of _AccessBase/db.* doesn't seem to resolve the issue
class AccessPolyModel(_AccessBase, polymodel.PolyModel):
pass
</code></pre>
<p>Here's a sub-document:</p>
<pre><code> class Thing(AccessExpando):
it = db.StringProperty()
</code></pre>
<p>Sometimes Thing will have the following properties:</p>
<pre><code> Thing { it: ... }
</code></pre>
<p>And other times:</p>
<pre><code> Thing { it: ..., users_permitted:..., owner:... }
</code></pre>
<p>I've been unable to figure out why Thing would sometimes have its _AccessParent properties, and other times not.</p>
| 3 | 2009-09-11T17:18:05Z | 1,412,335 | <p>Why can't you use <a href="http://docs.python.org/tutorial/classes.html#multiple-inheritance" rel="nofollow">multiple inheritance</a>?</p>
<pre><code>class Origin:
new_attribute = 'something'
class X:
pass
class Y:
pass
class X1(Origin, X):
pass
class Y1(Origin, Y):
pass
</code></pre>
| 2 | 2009-09-11T17:43:37Z | [
"python",
"decorator",
"multiple-inheritance"
] |
Python decorate a class to change parent object type | 1,412,210 | <p>Suppose you have two classes X & Y. You want to decorate those classes by adding attributes to the class to produce new classes X1 and Y1.</p>
<p>For example:</p>
<pre><code>class X1(X):
new_attribute = 'something'
class Y1(Y):
new_attribute = 'something'
</code></pre>
<p>*new_attribute* will always be the same for both X1 and Y1. X & Y are not related in any meaningful way, except that multiple inheritance is not possible. There are a set of other attributes as well, but this is degenerate to illustrate.</p>
<p>I feel like I'm overcomplicating this, but I had thought to use a decorator, somewhat likeso:</p>
<pre><code>def _xywrap(cls):
class _xy(cls):
new_attribute = 'something'
return _xy
@_xywrap(X)
class X1():
pass
@_xywrap(Y)
class Y1():
pass
</code></pre>
<p>It feels like I'm missing a fairly common pattern, and I'd be much obliged for thoughts, input and feedback.</p>
<p>Thank you for reading.</p>
<p>Brian</p>
<p><strong>EDIT:</strong> Example:</p>
<p>Here is a relevant extract that may illuminate. The common classes are as follows:</p>
<pre><code>from google.appengine.ext import db
# I'm including PermittedUserProperty because it may have pertinent side-effects
# (albeit unlikely), which is documented here: [How can you limit access to a
# GAE instance to the current user][1].
class _AccessBase:
users_permitted = PermittedUserProperty()
owner = db.ReferenceProperty(User)
class AccessModel(db.Model, _AccessBase):
pass
class AccessExpando(db.Expando, _AccessBase):
pass
# the order of _AccessBase/db.* doesn't seem to resolve the issue
class AccessPolyModel(_AccessBase, polymodel.PolyModel):
pass
</code></pre>
<p>Here's a sub-document:</p>
<pre><code> class Thing(AccessExpando):
it = db.StringProperty()
</code></pre>
<p>Sometimes Thing will have the following properties:</p>
<pre><code> Thing { it: ... }
</code></pre>
<p>And other times:</p>
<pre><code> Thing { it: ..., users_permitted:..., owner:... }
</code></pre>
<p>I've been unable to figure out why Thing would sometimes have its _AccessParent properties, and other times not.</p>
| 3 | 2009-09-11T17:18:05Z | 1,412,866 | <p>Responding to your comments on <a href="http://stackoverflow.com/questions/1412210/python-decorate-a-class-to-change-parent-object-type/1412335#1412335">voyager's answer</a>:</p>
<pre><code>from google.appengine.ext import db
class Mixin(object):
"""Mix in attributes shared by different types of models."""
foo = 1
bar = 2
baz = 3
class Person(db.Model, Mixin):
name = db.StringProperty()
class Dinosaur(db.polymodel.PolyModel, Mixin):
height = db.IntegerProperty()
p = Person(name='Buck Armstrong, Dinosaur Hunter')
d = Dinosaur(height=5000)
print p.name, p.foo, p.bar, p.baz
print d.height, d.foo, d.bar, d.baz
</code></pre>
<p>Running that results in</p>
<pre><code>Buck Armstrong, Dinosaur Hunter 1 2 3
5000 1 2 3
</code></pre>
<p>Is that not what you had in mind?</p>
| 3 | 2009-09-11T19:33:21Z | [
"python",
"decorator",
"multiple-inheritance"
] |
Python decorate a class to change parent object type | 1,412,210 | <p>Suppose you have two classes X & Y. You want to decorate those classes by adding attributes to the class to produce new classes X1 and Y1.</p>
<p>For example:</p>
<pre><code>class X1(X):
new_attribute = 'something'
class Y1(Y):
new_attribute = 'something'
</code></pre>
<p>*new_attribute* will always be the same for both X1 and Y1. X & Y are not related in any meaningful way, except that multiple inheritance is not possible. There are a set of other attributes as well, but this is degenerate to illustrate.</p>
<p>I feel like I'm overcomplicating this, but I had thought to use a decorator, somewhat likeso:</p>
<pre><code>def _xywrap(cls):
class _xy(cls):
new_attribute = 'something'
return _xy
@_xywrap(X)
class X1():
pass
@_xywrap(Y)
class Y1():
pass
</code></pre>
<p>It feels like I'm missing a fairly common pattern, and I'd be much obliged for thoughts, input and feedback.</p>
<p>Thank you for reading.</p>
<p>Brian</p>
<p><strong>EDIT:</strong> Example:</p>
<p>Here is a relevant extract that may illuminate. The common classes are as follows:</p>
<pre><code>from google.appengine.ext import db
# I'm including PermittedUserProperty because it may have pertinent side-effects
# (albeit unlikely), which is documented here: [How can you limit access to a
# GAE instance to the current user][1].
class _AccessBase:
users_permitted = PermittedUserProperty()
owner = db.ReferenceProperty(User)
class AccessModel(db.Model, _AccessBase):
pass
class AccessExpando(db.Expando, _AccessBase):
pass
# the order of _AccessBase/db.* doesn't seem to resolve the issue
class AccessPolyModel(_AccessBase, polymodel.PolyModel):
pass
</code></pre>
<p>Here's a sub-document:</p>
<pre><code> class Thing(AccessExpando):
it = db.StringProperty()
</code></pre>
<p>Sometimes Thing will have the following properties:</p>
<pre><code> Thing { it: ... }
</code></pre>
<p>And other times:</p>
<pre><code> Thing { it: ..., users_permitted:..., owner:... }
</code></pre>
<p>I've been unable to figure out why Thing would sometimes have its _AccessParent properties, and other times not.</p>
| 3 | 2009-09-11T17:18:05Z | 1,413,902 | <p>Use 3-arguments <a href="http://docs.python.org/library/functions.html?#type" rel="nofollow">type</a>:</p>
<pre><code>def makeSomeNicelyDecoratedSubclass(someclass):
return type('MyNiceName', (someclass,), {'new_attribute':'something'})
</code></pre>
<p>This is indeed, as you surmised, a reasonably popular idiom.</p>
<p><strong>Edit</strong>: in the general case if someclass has a custom metaclass you may need to extract and use it (with a 1-argument <code>type</code>) in lieu of <code>type</code> itself, to preserve it (this may be the case for your Django and App Engine models):</p>
<pre><code>def makeSomeNicelyDecoratedSubclass(someclass):
mcl = type(someclass)
return mcl('MyNiceName', (someclass,), {'new_attribute':'something'})
</code></pre>
<p>This also works where the simpler version above does (since in simple cases w/no custom metaclasses <code>type(someclass) is type</code>).</p>
| 5 | 2009-09-12T00:58:23Z | [
"python",
"decorator",
"multiple-inheritance"
] |
Modifying a GUI started with Glade | 1,412,350 | <p>I am just starting to learn Glade with pyGTK. Since Glade makes XML files instead of actual python code, is there a good way to start a project with Glade and then hand code more or tweak it? </p>
<p>Are there times or reasons it would be preferrable to hand code all of it instead of starting with glade?</p>
| 2 | 2009-09-11T17:46:41Z | 1,413,921 | <p>How much do you know about glade and pygtk? Glade creates xml files but you load these using gtk.Builder in python. You can easily tweak any widgets you created with glade in python. Read these <a href="http://live.gnome.org/Glade/Tutorials" rel="nofollow">tutorials</a> to understand how to do it better. You just need to learn more about pygtk and glade and it will be obvious.</p>
| 2 | 2009-09-12T01:08:05Z | [
"python",
"gtk",
"pygtk",
"glade"
] |
Modifying a GUI started with Glade | 1,412,350 | <p>I am just starting to learn Glade with pyGTK. Since Glade makes XML files instead of actual python code, is there a good way to start a project with Glade and then hand code more or tweak it? </p>
<p>Are there times or reasons it would be preferrable to hand code all of it instead of starting with glade?</p>
| 2 | 2009-09-11T17:46:41Z | 1,448,130 | <p>GUI's created with glade are accessible in the code in two way: libglade or gtkbuilder. I cannot comment much on the differences between the two, other than that gtkbuilder is newer; there are a lot of pages on google that show how to migrate from libglade to gtkbuilder.</p>
<p>Using gtkbuilder, you can create your GUI object by retrieving it from the the XML file using gtkbuilder. This creates the object with all of the settings you set in glade. You now have an GUI object which you can manipulate via it's regular interface.</p>
<pre><code>builder = gtk.Builder()
builder.add_from_file(glade_path)
builder.connect_signals(self)
main_window = builder.get_object("main_window")
main_window.show()
text_box1 = builder.get_object("textbox1")
text_box1.set_text("enter your name")
</code></pre>
<p>Line 3 shows how signal handlers are attached when loaded from glade. Essentially, it looks for the function you specified for the signal in the glade interface and attached to it; if the function isn't provided, you'll see a warning on the command line.</p>
| 4 | 2009-09-19T08:18:04Z | [
"python",
"gtk",
"pygtk",
"glade"
] |
Python Triple Quote / Multi-line indentation | 1,412,374 | <p>I have a python editor where the user is entering a script or code, which is then put into a main method behind the scenes, while also having every line indented. The problem is that if a user has a multi line string, the indentation made to the whole script affects the string, by inserting a tab in every space. A problem script would be something so simple as:</p>
<pre><code>"""foo
bar
foo2"""
</code></pre>
<p>So when in the main method it would look like:</p>
<pre><code>def main():
"""foo
bar
foo2"""
</code></pre>
<p>and the string would now have an extra tab at the beginning of every line. </p>
<p>I'm stumped on how to fix this. Any ideas would be appreciated!</p>
<p>Thanks</p>
| 20 | 2009-09-11T17:51:05Z | 1,412,441 | <p>The only way i see - is to strip first n tabs for each line starting with second, where n is known identation of main method. </p>
<p>If that identation is not known beforehand - you can add trailing newline before inserting it and strip number of tabs from the last line...</p>
<p>The third solution is to parse data and find beginning of multiline quote and do not add your identation to every line after until it will be closed.</p>
<p>Think there is a better solution..</p>
| 1 | 2009-09-11T18:06:21Z | [
"python",
"quotes",
"multiline"
] |
Python Triple Quote / Multi-line indentation | 1,412,374 | <p>I have a python editor where the user is entering a script or code, which is then put into a main method behind the scenes, while also having every line indented. The problem is that if a user has a multi line string, the indentation made to the whole script affects the string, by inserting a tab in every space. A problem script would be something so simple as:</p>
<pre><code>"""foo
bar
foo2"""
</code></pre>
<p>So when in the main method it would look like:</p>
<pre><code>def main():
"""foo
bar
foo2"""
</code></pre>
<p>and the string would now have an extra tab at the beginning of every line. </p>
<p>I'm stumped on how to fix this. Any ideas would be appreciated!</p>
<p>Thanks</p>
| 20 | 2009-09-11T17:51:05Z | 1,412,480 | <p>What follows the first line of a multiline string is part of the string, and not treated as indentation by the parser. you may freely write:</p>
<pre><code>def main():
"""foo
bar
foo2"""
pass
</code></pre>
<p>and it will do the right thing.</p>
<p>On the other hand, that's not readable, and python knows it. So if a docstring contains whitespace in it's <em>second</em> line, that amount of whitespace is stripped off when you use <code>help()</code> to view the docstring. Thus, <code>help(main)</code> and the below <code>help(main2)</code> produce the same help info.</p>
<pre><code>def main2():
"""foo
bar
foo2"""
pass
</code></pre>
| 13 | 2009-09-11T18:12:23Z | [
"python",
"quotes",
"multiline"
] |
Python Triple Quote / Multi-line indentation | 1,412,374 | <p>I have a python editor where the user is entering a script or code, which is then put into a main method behind the scenes, while also having every line indented. The problem is that if a user has a multi line string, the indentation made to the whole script affects the string, by inserting a tab in every space. A problem script would be something so simple as:</p>
<pre><code>"""foo
bar
foo2"""
</code></pre>
<p>So when in the main method it would look like:</p>
<pre><code>def main():
"""foo
bar
foo2"""
</code></pre>
<p>and the string would now have an extra tab at the beginning of every line. </p>
<p>I'm stumped on how to fix this. Any ideas would be appreciated!</p>
<p>Thanks</p>
| 20 | 2009-09-11T17:51:05Z | 1,412,603 | <p>So if I get it correctly, you take whatever the user inputs, indent it properly and add it to the rest of your program (and then run that whole program).</p>
<p>So after you put the user input into your program, you could run a regex, that basically takes that forced indentation back. Something like: Within three quotes, replace all "new line markers" followed by four spaces (or a tab) with only a "new line marker".</p>
| 1 | 2009-09-11T18:35:43Z | [
"python",
"quotes",
"multiline"
] |
Python Triple Quote / Multi-line indentation | 1,412,374 | <p>I have a python editor where the user is entering a script or code, which is then put into a main method behind the scenes, while also having every line indented. The problem is that if a user has a multi line string, the indentation made to the whole script affects the string, by inserting a tab in every space. A problem script would be something so simple as:</p>
<pre><code>"""foo
bar
foo2"""
</code></pre>
<p>So when in the main method it would look like:</p>
<pre><code>def main():
"""foo
bar
foo2"""
</code></pre>
<p>and the string would now have an extra tab at the beginning of every line. </p>
<p>I'm stumped on how to fix this. Any ideas would be appreciated!</p>
<p>Thanks</p>
| 20 | 2009-09-11T17:51:05Z | 1,412,728 | <p><a href="http://docs.python.org/library/textwrap.html#textwrap.dedent">textwrap.dedent</a> from the standard library is there to automatically undo the wacky indentation. </p>
| 49 | 2009-09-11T19:02:18Z | [
"python",
"quotes",
"multiline"
] |
Django extends template | 1,412,476 | <p>i have simple django/python app and i got 1 page - create.html. So i want to extend this page to use index.html. Everything work (no errors) and when the page is loaded all data from create.html and all text from index.html present but no formating is available - images and css that must be loaded from index.html is not loaded. When i load index.html in browser looks ok. Can someone help me?</p>
<p>Thanks!</p>
<p>here is the code of templates:</p>
<p><strong>create.html</strong></p>
<pre><code> {% extends "index.html" %}
{% block title %}Projects{% endblock %}
{% block content %}
{% if projects %}
<table border="1">
<tr>
<td align="center">Name</td>
<td align="center">Description</td>
<td align="center">Priority</td>
<td align="center">X</td>
</tr>
{% for p in projects %}
<tr>
<td> <a href="/tasks/{{p.id}}/">{{p.Name}}</a> </td>
<td>{{p.Description}} </td>
<td> {{p.Priority.Name}} </td>
<td> <a href="/editproject/{{p.id}}/">Edit</a> <a href="/deleteproject/{{p.id}}/">Delete</a> </td>
<tr>
{% endfor %}
</table>
{% else %}
<p>No active projects.</p>
{% endif %}
{% endblock %}
</code></pre>
<p><strong>and index.html:</strong></p>
<pre><code> <html>
<head>
{% block title %}{% endblock %}
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<body>
{% block content %}{% endblock %}
<div class="PostContent">
<img class="article" src="images/spectacles.gif" alt="an image" style="float: left" />
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
<p>Lorem ipsum dolor sit amet,
<a href="#" title="link">link</a>, <a class="visited" href="#" title="visited link">visited link</a>,
<a class="hover" href="#" title="hovered link">hovered link</a> consectetuer
adipiscing elit. Quisque sed felis. Aliquam sit amet felis. Mauris semper,
velit semper laoreet dictum, quam diam dictum urna, nec placerat elit nisl
in quam. Etiam augue pede, molestie eget, rhoncus at, convallis ut, eros.</p>
....
</body>
</html>
</code></pre>
| 0 | 2009-09-11T18:11:19Z | 1,412,627 | <p>It looks like you are extending base.html and not index.html.</p>
| 1 | 2009-09-11T18:41:33Z | [
"python",
"django",
"extends"
] |
Django extends template | 1,412,476 | <p>i have simple django/python app and i got 1 page - create.html. So i want to extend this page to use index.html. Everything work (no errors) and when the page is loaded all data from create.html and all text from index.html present but no formating is available - images and css that must be loaded from index.html is not loaded. When i load index.html in browser looks ok. Can someone help me?</p>
<p>Thanks!</p>
<p>here is the code of templates:</p>
<p><strong>create.html</strong></p>
<pre><code> {% extends "index.html" %}
{% block title %}Projects{% endblock %}
{% block content %}
{% if projects %}
<table border="1">
<tr>
<td align="center">Name</td>
<td align="center">Description</td>
<td align="center">Priority</td>
<td align="center">X</td>
</tr>
{% for p in projects %}
<tr>
<td> <a href="/tasks/{{p.id}}/">{{p.Name}}</a> </td>
<td>{{p.Description}} </td>
<td> {{p.Priority.Name}} </td>
<td> <a href="/editproject/{{p.id}}/">Edit</a> <a href="/deleteproject/{{p.id}}/">Delete</a> </td>
<tr>
{% endfor %}
</table>
{% else %}
<p>No active projects.</p>
{% endif %}
{% endblock %}
</code></pre>
<p><strong>and index.html:</strong></p>
<pre><code> <html>
<head>
{% block title %}{% endblock %}
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<body>
{% block content %}{% endblock %}
<div class="PostContent">
<img class="article" src="images/spectacles.gif" alt="an image" style="float: left" />
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
<p>Lorem ipsum dolor sit amet,
<a href="#" title="link">link</a>, <a class="visited" href="#" title="visited link">visited link</a>,
<a class="hover" href="#" title="hovered link">hovered link</a> consectetuer
adipiscing elit. Quisque sed felis. Aliquam sit amet felis. Mauris semper,
velit semper laoreet dictum, quam diam dictum urna, nec placerat elit nisl
in quam. Etiam augue pede, molestie eget, rhoncus at, convallis ut, eros.</p>
....
</body>
</html>
</code></pre>
| 0 | 2009-09-11T18:11:19Z | 1,412,673 | <p>More specifically, look at the first line of your content.html:</p>
<pre><code> {% extends "base.html" %}
</code></pre>
<p>Change this to</p>
<pre><code> {% extends "index.html" %}
</code></pre>
<p>(or rename index.html to be base.html)</p>
| 1 | 2009-09-11T18:50:36Z | [
"python",
"django",
"extends"
] |
Django extends template | 1,412,476 | <p>i have simple django/python app and i got 1 page - create.html. So i want to extend this page to use index.html. Everything work (no errors) and when the page is loaded all data from create.html and all text from index.html present but no formating is available - images and css that must be loaded from index.html is not loaded. When i load index.html in browser looks ok. Can someone help me?</p>
<p>Thanks!</p>
<p>here is the code of templates:</p>
<p><strong>create.html</strong></p>
<pre><code> {% extends "index.html" %}
{% block title %}Projects{% endblock %}
{% block content %}
{% if projects %}
<table border="1">
<tr>
<td align="center">Name</td>
<td align="center">Description</td>
<td align="center">Priority</td>
<td align="center">X</td>
</tr>
{% for p in projects %}
<tr>
<td> <a href="/tasks/{{p.id}}/">{{p.Name}}</a> </td>
<td>{{p.Description}} </td>
<td> {{p.Priority.Name}} </td>
<td> <a href="/editproject/{{p.id}}/">Edit</a> <a href="/deleteproject/{{p.id}}/">Delete</a> </td>
<tr>
{% endfor %}
</table>
{% else %}
<p>No active projects.</p>
{% endif %}
{% endblock %}
</code></pre>
<p><strong>and index.html:</strong></p>
<pre><code> <html>
<head>
{% block title %}{% endblock %}
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<body>
{% block content %}{% endblock %}
<div class="PostContent">
<img class="article" src="images/spectacles.gif" alt="an image" style="float: left" />
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
<p>Lorem ipsum dolor sit amet,
<a href="#" title="link">link</a>, <a class="visited" href="#" title="visited link">visited link</a>,
<a class="hover" href="#" title="hovered link">hovered link</a> consectetuer
adipiscing elit. Quisque sed felis. Aliquam sit amet felis. Mauris semper,
velit semper laoreet dictum, quam diam dictum urna, nec placerat elit nisl
in quam. Etiam augue pede, molestie eget, rhoncus at, convallis ut, eros.</p>
....
</body>
</html>
</code></pre>
| 0 | 2009-09-11T18:11:19Z | 1,413,255 | <p>Ahaa find where is the problem!
MEDIA_ROOT and MEDIA_URL was not set up :-( after edit them everything work ok.</p>
<p><a href="http://stackoverflow.com/questions/1075753/django-template-cant-see-css-files">http://stackoverflow.com/questions/1075753/django-template-cant-see-css-files</a></p>
| 1 | 2009-09-11T21:02:06Z | [
"python",
"django",
"extends"
] |
How do I programmatically check whether a GIF image is animated? | 1,412,529 | <p>Here is a link to <a href="http://stackoverflow.com/questions/1401527/how-do-i-programmatically-check-whether-an-image-png-jpeg-or-gif-is-corrupted">another question</a> I asked concerning the same project I am working on. I think that bit of background will be helpful. </p>
<p>For those that are too lazy to open a new tab to that question, I'll summarize what I'm trying to do here: I've downloaded about 250,000 images from 4scrape and I want to go through the GIFs and find which ones are animated or not. I need to do this programmatically, because I really don't feel my soul (or my relationship with my girlfriend) could use looking at a couple thousand GIFs from 4chan to see if they are animated or not. If you know the nature of 4chan, then you know the nature of the images (i.e. "tits or GTFO").</p>
<p>I know PHP and Python, but would be willing to explore other solutions. A stand-alone piece of software that works on Windows would also work.</p>
<p>Thanks a lot!</p>
| 8 | 2009-09-11T18:21:18Z | 1,412,587 | <p>Read the GIF89A specification and extract the information.
<a href="http://www.w3.org/Graphics/GIF/spec-gif89a.txt" rel="nofollow">http://www.w3.org/Graphics/GIF/spec-gif89a.txt</a></p>
<p>Or easy and lazy and ready for a hack use the intergif program which can extract the single images out of an animated gif. Extract into a temp directory and look how many files you get.
<a href="http://utter.chaos.org.uk/~pdh/software/intergif/download.htm" rel="nofollow">http://utter.chaos.org.uk/~pdh/software/intergif/download.htm</a></p>
| 2 | 2009-09-11T18:33:14Z | [
"php",
"python",
"image"
] |
How do I programmatically check whether a GIF image is animated? | 1,412,529 | <p>Here is a link to <a href="http://stackoverflow.com/questions/1401527/how-do-i-programmatically-check-whether-an-image-png-jpeg-or-gif-is-corrupted">another question</a> I asked concerning the same project I am working on. I think that bit of background will be helpful. </p>
<p>For those that are too lazy to open a new tab to that question, I'll summarize what I'm trying to do here: I've downloaded about 250,000 images from 4scrape and I want to go through the GIFs and find which ones are animated or not. I need to do this programmatically, because I really don't feel my soul (or my relationship with my girlfriend) could use looking at a couple thousand GIFs from 4chan to see if they are animated or not. If you know the nature of 4chan, then you know the nature of the images (i.e. "tits or GTFO").</p>
<p>I know PHP and Python, but would be willing to explore other solutions. A stand-alone piece of software that works on Windows would also work.</p>
<p>Thanks a lot!</p>
| 8 | 2009-09-11T18:21:18Z | 1,412,594 | <p>A few solutions are given on the <a href="http://php.net/manual/en/function.imagecreatefromgif.php#88005" rel="nofollow">PHP docs</a> page for the <code>imagecreatefromgif</code> function.</p>
<p>From the solutions I've read, this one seems the best due to its tighter memory requirements.</p>
<pre><code><?php
function is_ani($filename) {
if(!($fh = @fopen($filename, 'rb')))
return false;
$count = 0;
//an animated gif contains multiple "frames", with each frame having a
//header made up of:
// * a static 4-byte sequence (\x00\x21\xF9\x04)
// * 4 variable bytes
// * a static 2-byte sequence (\x00\x2C)
// We read through the file til we reach the end of the file, or we've found
// at least 2 frame headers
while(!feof($fh) && $count < 2) {
$chunk = fread($fh, 1024 * 100); //read 100kb at a time
$count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches);
}
fclose($fh);
return $count > 1;
}
?>
</code></pre>
| 3 | 2009-09-11T18:34:31Z | [
"php",
"python",
"image"
] |
How do I programmatically check whether a GIF image is animated? | 1,412,529 | <p>Here is a link to <a href="http://stackoverflow.com/questions/1401527/how-do-i-programmatically-check-whether-an-image-png-jpeg-or-gif-is-corrupted">another question</a> I asked concerning the same project I am working on. I think that bit of background will be helpful. </p>
<p>For those that are too lazy to open a new tab to that question, I'll summarize what I'm trying to do here: I've downloaded about 250,000 images from 4scrape and I want to go through the GIFs and find which ones are animated or not. I need to do this programmatically, because I really don't feel my soul (or my relationship with my girlfriend) could use looking at a couple thousand GIFs from 4chan to see if they are animated or not. If you know the nature of 4chan, then you know the nature of the images (i.e. "tits or GTFO").</p>
<p>I know PHP and Python, but would be willing to explore other solutions. A stand-alone piece of software that works on Windows would also work.</p>
<p>Thanks a lot!</p>
| 8 | 2009-09-11T18:21:18Z | 1,412,644 | <p>I've never seen a program that will tell you this. But GIF is a block structured format and you can check if the block indicating animated GIF is present in your files. </p>
<p>From wikipedia article noted below: at offset 0x30D an Application Extension (ie: 3 byte magic number 21 FF 0B) block in the GIF file, followed by magic number 4E 45 54 53 43 41 50 45 32 9at offset 0x310 indicates that the rest of the file contains multiple images, and they should be animated.</p>
<p>Really the Wikipedia article explains it better and the format docs noted below expand on the Wiki article. </p>
<p>So you can parse the GIFs using a program written in Python (I parsed GIFs using C many years ago, it was mainly an exercise in moving the file pointer around and reading bytes). Determine if the AE is present with the correct 3 byte ID, and followed by the 9 byte magic number.</p>
<p>See <a href="http://en.wikipedia.org/wiki/Graphics%5FInterchange%5FFormat#Animated%5F.gif">http://en.wikipedia.org/wiki/Graphics%5FInterchange%5FFormat#Animated%5F.gif</a></p>
<p>Also see <a href="http://www.martinreddy.net/gfx/2d/GIF87a.txt">http://www.martinreddy.net/gfx/2d/GIF87a.txt</a></p>
<p>Also see <a href="http://www.martinreddy.net/gfx/2d/GIF89a.txt">http://www.martinreddy.net/gfx/2d/GIF89a.txt</a></p>
<p>Sorry, best I can do for you.</p>
| 6 | 2009-09-11T18:45:06Z | [
"php",
"python",
"image"
] |
How do I programmatically check whether a GIF image is animated? | 1,412,529 | <p>Here is a link to <a href="http://stackoverflow.com/questions/1401527/how-do-i-programmatically-check-whether-an-image-png-jpeg-or-gif-is-corrupted">another question</a> I asked concerning the same project I am working on. I think that bit of background will be helpful. </p>
<p>For those that are too lazy to open a new tab to that question, I'll summarize what I'm trying to do here: I've downloaded about 250,000 images from 4scrape and I want to go through the GIFs and find which ones are animated or not. I need to do this programmatically, because I really don't feel my soul (or my relationship with my girlfriend) could use looking at a couple thousand GIFs from 4chan to see if they are animated or not. If you know the nature of 4chan, then you know the nature of the images (i.e. "tits or GTFO").</p>
<p>I know PHP and Python, but would be willing to explore other solutions. A stand-alone piece of software that works on Windows would also work.</p>
<p>Thanks a lot!</p>
| 8 | 2009-09-11T18:21:18Z | 1,412,711 | <p>I'm no GIF file format expert, but this is an interesting problem to me so I looked into it a bit. This would work only if it's always true that animated gifs have the value NETSCAPE2.0 at position 0x310 (edit)AND static gifs do not,(/edit) which was the case in my test files. This is C#, if you want I could compile it to a console app that takes a directory as an argument and you could run some test on your very large gif collection to see if it produces reliable results.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string ani = @"C:\path\to\ani.gif";
string sta = @"C:\path\to\static.gif";
Console.WriteLine(isAnimated(ani));
Console.WriteLine(isAnimated(sta));
}
static bool isAnimated(string path)
{
byte[] bytes = File.ReadAllBytes(path);
byte[] netscape = bytes.Skip(0x310).Take(11).ToArray();
StringBuilder sb = new StringBuilder();
foreach (var item in netscape)
{
sb.Append((char)item);
}
return sb.ToString() == "NETSCAPE2.0";
}
}
}
</code></pre>
| 1 | 2009-09-11T18:58:57Z | [
"php",
"python",
"image"
] |
How do I programmatically check whether a GIF image is animated? | 1,412,529 | <p>Here is a link to <a href="http://stackoverflow.com/questions/1401527/how-do-i-programmatically-check-whether-an-image-png-jpeg-or-gif-is-corrupted">another question</a> I asked concerning the same project I am working on. I think that bit of background will be helpful. </p>
<p>For those that are too lazy to open a new tab to that question, I'll summarize what I'm trying to do here: I've downloaded about 250,000 images from 4scrape and I want to go through the GIFs and find which ones are animated or not. I need to do this programmatically, because I really don't feel my soul (or my relationship with my girlfriend) could use looking at a couple thousand GIFs from 4chan to see if they are animated or not. If you know the nature of 4chan, then you know the nature of the images (i.e. "tits or GTFO").</p>
<p>I know PHP and Python, but would be willing to explore other solutions. A stand-alone piece of software that works on Windows would also work.</p>
<p>Thanks a lot!</p>
| 8 | 2009-09-11T18:21:18Z | 1,413,234 | <p>If you're on Linux (or any system with <a href="http://www.imagemagick.org/">ImageMagick</a>) you can use a one-liner shell script and <code>identify</code> program:</p>
<pre><code>identify *.gif | fgrep '.gif[1] '
</code></pre>
<p>I know you said you prefer PHP and Python, but you also said you are willing to explore other solutions. :)</p>
| 11 | 2009-09-11T20:56:52Z | [
"php",
"python",
"image"
] |
How do I programmatically check whether a GIF image is animated? | 1,412,529 | <p>Here is a link to <a href="http://stackoverflow.com/questions/1401527/how-do-i-programmatically-check-whether-an-image-png-jpeg-or-gif-is-corrupted">another question</a> I asked concerning the same project I am working on. I think that bit of background will be helpful. </p>
<p>For those that are too lazy to open a new tab to that question, I'll summarize what I'm trying to do here: I've downloaded about 250,000 images from 4scrape and I want to go through the GIFs and find which ones are animated or not. I need to do this programmatically, because I really don't feel my soul (or my relationship with my girlfriend) could use looking at a couple thousand GIFs from 4chan to see if they are animated or not. If you know the nature of 4chan, then you know the nature of the images (i.e. "tits or GTFO").</p>
<p>I know PHP and Python, but would be willing to explore other solutions. A stand-alone piece of software that works on Windows would also work.</p>
<p>Thanks a lot!</p>
| 8 | 2009-09-11T18:21:18Z | 1,413,365 | <p>With Python and <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a>:</p>
<pre><code>from PIL import Image
gif = Image.open('path.gif')
try:
gif.seek(1)
except EOFError:
isanimated = False
else:
isanimated = True
</code></pre>
| 13 | 2009-09-11T21:26:07Z | [
"php",
"python",
"image"
] |
How do I programmatically check whether a GIF image is animated? | 1,412,529 | <p>Here is a link to <a href="http://stackoverflow.com/questions/1401527/how-do-i-programmatically-check-whether-an-image-png-jpeg-or-gif-is-corrupted">another question</a> I asked concerning the same project I am working on. I think that bit of background will be helpful. </p>
<p>For those that are too lazy to open a new tab to that question, I'll summarize what I'm trying to do here: I've downloaded about 250,000 images from 4scrape and I want to go through the GIFs and find which ones are animated or not. I need to do this programmatically, because I really don't feel my soul (or my relationship with my girlfriend) could use looking at a couple thousand GIFs from 4chan to see if they are animated or not. If you know the nature of 4chan, then you know the nature of the images (i.e. "tits or GTFO").</p>
<p>I know PHP and Python, but would be willing to explore other solutions. A stand-alone piece of software that works on Windows would also work.</p>
<p>Thanks a lot!</p>
| 8 | 2009-09-11T18:21:18Z | 1,414,046 | <p>try this</p>
<pre><code>import Image
def checkAnimate():
im = Image.open('image.gif')
if not im.info['version'].__contains__('GIF'):
print "It's not a GIF file"
else:
if im.info.has_key('duration'):
if im.info['duration'] > 0:
return True
else:
return False
else:
return False
</code></pre>
| 0 | 2009-09-12T02:23:34Z | [
"php",
"python",
"image"
] |
How do I programmatically check whether a GIF image is animated? | 1,412,529 | <p>Here is a link to <a href="http://stackoverflow.com/questions/1401527/how-do-i-programmatically-check-whether-an-image-png-jpeg-or-gif-is-corrupted">another question</a> I asked concerning the same project I am working on. I think that bit of background will be helpful. </p>
<p>For those that are too lazy to open a new tab to that question, I'll summarize what I'm trying to do here: I've downloaded about 250,000 images from 4scrape and I want to go through the GIFs and find which ones are animated or not. I need to do this programmatically, because I really don't feel my soul (or my relationship with my girlfriend) could use looking at a couple thousand GIFs from 4chan to see if they are animated or not. If you know the nature of 4chan, then you know the nature of the images (i.e. "tits or GTFO").</p>
<p>I know PHP and Python, but would be willing to explore other solutions. A stand-alone piece of software that works on Windows would also work.</p>
<p>Thanks a lot!</p>
| 8 | 2009-09-11T18:21:18Z | 2,965,831 | <p>see if there is more than one LocalDescriptor are there in the GIF file.</p>
| 1 | 2010-06-03T12:23:38Z | [
"php",
"python",
"image"
] |
How do I programmatically check whether a GIF image is animated? | 1,412,529 | <p>Here is a link to <a href="http://stackoverflow.com/questions/1401527/how-do-i-programmatically-check-whether-an-image-png-jpeg-or-gif-is-corrupted">another question</a> I asked concerning the same project I am working on. I think that bit of background will be helpful. </p>
<p>For those that are too lazy to open a new tab to that question, I'll summarize what I'm trying to do here: I've downloaded about 250,000 images from 4scrape and I want to go through the GIFs and find which ones are animated or not. I need to do this programmatically, because I really don't feel my soul (or my relationship with my girlfriend) could use looking at a couple thousand GIFs from 4chan to see if they are animated or not. If you know the nature of 4chan, then you know the nature of the images (i.e. "tits or GTFO").</p>
<p>I know PHP and Python, but would be willing to explore other solutions. A stand-alone piece of software that works on Windows would also work.</p>
<p>Thanks a lot!</p>
| 8 | 2009-09-11T18:21:18Z | 36,888,169 | <pre><code>from PIL import Image
fp = open('1.gif', 'rb')
im = Image.open(fp)
is_gif = bool(im.format and im.format.upper() == 'GIF')
</code></pre>
| 0 | 2016-04-27T11:15:01Z | [
"php",
"python",
"image"
] |
Python Warning control | 1,412,575 | <p>I would like some kind of warning to be raisen as errors, but only the first occurrence. How to do that?</p>
<p>I read <a href="http://docs.python.org/library/warnings.html" rel="nofollow">http://docs.python.org/library/warnings.html</a> and I dont know how to combine this two types of behaviour.</p>
| 3 | 2009-09-11T18:31:45Z | 1,412,615 | <p>Looking at the code to warnings.py, you can't assign more than one filter action to a warning, and you can't (easily) define your own actions, like 'raise_once'.</p>
<p>However, if you want to raise a warning as an exception, but just once, that means that you are catching the exception. Why not put a line in your except clause that sets an 'ignore' action on that particular warning?</p>
<pre><code>#!/usr/bin/python
import warnings
warnings.filterwarnings('error','Test')
for i in range(2):
try:
warnings.warn('Test');
except UserWarning, e:
print "Error caught"
warnings.filterwarnings('ignore','Test')
</code></pre>
| 6 | 2009-09-11T18:39:24Z | [
"python",
"warnings"
] |
iTunes COM - How to acess Lyrics | 1,412,689 | <p>I have been messing around with iTunes COM from python.</p>
<p>However, I haven't been able to access the Lyrics of any track.</p>
<p>I have been using python for this. Here is the code:</p>
<pre><code>>>> import win32com.client
>>> itunes = win32com.client.Dispatch("iTunes.Application")
>>> lib = itunes.LibraryPlaylist
>>> tracks = lib.Tracks
>>> tracks
<win32com.gen_py.iTunes 1.12 Type Library.IITTrackCollection instance at 0x16726176>
>>> tracks[1]
<win32com.gen_py.iTunes 1.12 Type Library.IITTrack instance at 0x16746256>
>>> tracks[1].Lyrics
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "D:\Programas\Python26\lib\site-packages\win32com\client\__init__.py", line 462, in __getattr__
raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
AttributeError: '<win32com.gen_py.iTunes 1.12 Type Library.IITTrack instance at 0x16780824>' object has no attribute 'Lyrics'
</code></pre>
<p>tracks[1] has no attribute 'Lyrics' because it is of type 'IITTrack'. Only 'IITFileOrCDTrack', which is a sub-type of 'IITTrack' has this attribute. My question is how to access the 'IITFileOrCDTrack's? Or how to convert a 'IITTrack' to a 'IITFileOrCDTrack'? </p>
<p>Any help on this is greatly appreciated. Thanks.</p>
<p>P.S: Info on how to download documentation of iTunes COM interface <a href="http://www.paraesthesia.com/archive/2009/05/20/itunes-com-for-windows-sdk-now-in-adc.aspx" rel="nofollow">here</a>.</p>
| 1 | 2009-09-11T18:54:31Z | 1,412,881 | <p>Try to convert it like this (not tested):</p>
<pre><code>track_converted = win32com.client.CastTo(tracks[1], "IITFileOrCDTrack")
</code></pre>
| 3 | 2009-09-11T19:38:09Z | [
"python",
"com",
"itunes"
] |
PicklingError: Can't pickle <class 'decimal.Decimal'>: it's not the same object as decimal.Decimal | 1,412,787 | <p>This is the error I got today at filmaster.com:</p>
<blockquote>
<p>PicklingError: Can't pickle : it's not the same
object as decimal.Decimal</p>
</blockquote>
<p>What does that exactly mean? It does not seem to be making a lot of sense...
It seems to be connected with django caching. You can see the whole traceback here: </p>
<blockquote>
<p>Traceback (most recent call last):</p>
<p>File
"/home/filmaster/django-trunk/django/core/handlers/base.py",
line 92, in get_response response =
callback(request, *callback_args,
**callback_kwargs)</p>
<p>File
"/home/filmaster/film20/film20/core/film_views.py",
line 193, in show_film<br />
workflow.set_data_for_authenticated_user()</p>
<p>File
"/home/filmaster/film20/film20/core/film_views.py",
line 518, in
set_data_for_authenticated_user<br />
object_id = self.the_film.parent.id)</p>
<p>File
"/home/filmaster/film20/film20/core/film_helper.py",
line 179, in get_others_ratings<br />
set_cache(CACHE_OTHERS_RATINGS,
str(object_id) + "_" + str(user_id),
userratings)</p>
<p>File
"/home/filmaster/film20/film20/utils/cache_helper.py",
line 80, in set_cache return
cache.set(CACHE_MIDDLEWARE_KEY_PREFIX
+ full_path, result, get_time(cache_string))</p>
<p>File
"/home/filmaster/django-trunk/django/core/cache/backends/memcached.py",
line 37, in set<br />
self._cache.set(smart_str(key), value,
timeout or self.default_timeout)</p>
<p>File
"/usr/lib/python2.5/site-packages/cmemcache.py",
line 128, in set val, flags =
self._convert(val)</p>
<p>File
"/usr/lib/python2.5/site-packages/cmemcache.py",
line 112, in _convert val =
pickle.dumps(val, 2)</p>
<p>PicklingError: Can't pickle : it's not the same
object as decimal.Decimal</p>
</blockquote>
<p>And the source code for Filmaster can be downloaded from here: <a href="http://bitbucket.org/filmaster/filmaster-test/">bitbucket.org/filmaster/filmaster-test</a></p>
<p>Any help will be greatly appreciated.</p>
| 6 | 2009-09-11T19:13:23Z | 1,413,299 | <p>One oddity of Pickle is that the way you import a class before you pickle one of it's instances can subtly change the pickled object. Pickle requires you to have imported the object identically both before you pickle it and before you unpickle it. </p>
<p>So for example:</p>
<pre><code>from a.b import c
C = c()
pickler.dump(C)
</code></pre>
<p>will make a subtly different object (sometimes) to:</p>
<pre><code>from a import b
C = b.c()
pickler.dump(C)
</code></pre>
<p>Try fiddling with your imports, it might correct the problem.</p>
| 8 | 2009-09-11T21:12:22Z | [
"python",
"django",
"pickle"
] |
PicklingError: Can't pickle <class 'decimal.Decimal'>: it's not the same object as decimal.Decimal | 1,412,787 | <p>This is the error I got today at filmaster.com:</p>
<blockquote>
<p>PicklingError: Can't pickle : it's not the same
object as decimal.Decimal</p>
</blockquote>
<p>What does that exactly mean? It does not seem to be making a lot of sense...
It seems to be connected with django caching. You can see the whole traceback here: </p>
<blockquote>
<p>Traceback (most recent call last):</p>
<p>File
"/home/filmaster/django-trunk/django/core/handlers/base.py",
line 92, in get_response response =
callback(request, *callback_args,
**callback_kwargs)</p>
<p>File
"/home/filmaster/film20/film20/core/film_views.py",
line 193, in show_film<br />
workflow.set_data_for_authenticated_user()</p>
<p>File
"/home/filmaster/film20/film20/core/film_views.py",
line 518, in
set_data_for_authenticated_user<br />
object_id = self.the_film.parent.id)</p>
<p>File
"/home/filmaster/film20/film20/core/film_helper.py",
line 179, in get_others_ratings<br />
set_cache(CACHE_OTHERS_RATINGS,
str(object_id) + "_" + str(user_id),
userratings)</p>
<p>File
"/home/filmaster/film20/film20/utils/cache_helper.py",
line 80, in set_cache return
cache.set(CACHE_MIDDLEWARE_KEY_PREFIX
+ full_path, result, get_time(cache_string))</p>
<p>File
"/home/filmaster/django-trunk/django/core/cache/backends/memcached.py",
line 37, in set<br />
self._cache.set(smart_str(key), value,
timeout or self.default_timeout)</p>
<p>File
"/usr/lib/python2.5/site-packages/cmemcache.py",
line 128, in set val, flags =
self._convert(val)</p>
<p>File
"/usr/lib/python2.5/site-packages/cmemcache.py",
line 112, in _convert val =
pickle.dumps(val, 2)</p>
<p>PicklingError: Can't pickle : it's not the same
object as decimal.Decimal</p>
</blockquote>
<p>And the source code for Filmaster can be downloaded from here: <a href="http://bitbucket.org/filmaster/filmaster-test/">bitbucket.org/filmaster/filmaster-test</a></p>
<p>Any help will be greatly appreciated.</p>
| 6 | 2009-09-11T19:13:23Z | 1,964,942 | <p>Did you somehow <code>reload(decimal)</code>, or monkeypatch the decimal module to change the Decimal class? These are the two things most likely to produce such a problem.</p>
| 2 | 2009-12-27T01:57:05Z | [
"python",
"django",
"pickle"
] |
PicklingError: Can't pickle <class 'decimal.Decimal'>: it's not the same object as decimal.Decimal | 1,412,787 | <p>This is the error I got today at filmaster.com:</p>
<blockquote>
<p>PicklingError: Can't pickle : it's not the same
object as decimal.Decimal</p>
</blockquote>
<p>What does that exactly mean? It does not seem to be making a lot of sense...
It seems to be connected with django caching. You can see the whole traceback here: </p>
<blockquote>
<p>Traceback (most recent call last):</p>
<p>File
"/home/filmaster/django-trunk/django/core/handlers/base.py",
line 92, in get_response response =
callback(request, *callback_args,
**callback_kwargs)</p>
<p>File
"/home/filmaster/film20/film20/core/film_views.py",
line 193, in show_film<br />
workflow.set_data_for_authenticated_user()</p>
<p>File
"/home/filmaster/film20/film20/core/film_views.py",
line 518, in
set_data_for_authenticated_user<br />
object_id = self.the_film.parent.id)</p>
<p>File
"/home/filmaster/film20/film20/core/film_helper.py",
line 179, in get_others_ratings<br />
set_cache(CACHE_OTHERS_RATINGS,
str(object_id) + "_" + str(user_id),
userratings)</p>
<p>File
"/home/filmaster/film20/film20/utils/cache_helper.py",
line 80, in set_cache return
cache.set(CACHE_MIDDLEWARE_KEY_PREFIX
+ full_path, result, get_time(cache_string))</p>
<p>File
"/home/filmaster/django-trunk/django/core/cache/backends/memcached.py",
line 37, in set<br />
self._cache.set(smart_str(key), value,
timeout or self.default_timeout)</p>
<p>File
"/usr/lib/python2.5/site-packages/cmemcache.py",
line 128, in set val, flags =
self._convert(val)</p>
<p>File
"/usr/lib/python2.5/site-packages/cmemcache.py",
line 112, in _convert val =
pickle.dumps(val, 2)</p>
<p>PicklingError: Can't pickle : it's not the same
object as decimal.Decimal</p>
</blockquote>
<p>And the source code for Filmaster can be downloaded from here: <a href="http://bitbucket.org/filmaster/filmaster-test/">bitbucket.org/filmaster/filmaster-test</a></p>
<p>Any help will be greatly appreciated.</p>
| 6 | 2009-09-11T19:13:23Z | 38,551,656 | <p>I got this error when running in an jupyter notebook. I think the problem was that I was using <code>%load_ext autoreload</code> <code>autoreload 2</code>. Restarting my kernel and rerunning solved the problem.</p>
| 1 | 2016-07-24T11:46:51Z | [
"python",
"django",
"pickle"
] |
PicklingError: Can't pickle <class 'decimal.Decimal'>: it's not the same object as decimal.Decimal | 1,412,787 | <p>This is the error I got today at filmaster.com:</p>
<blockquote>
<p>PicklingError: Can't pickle : it's not the same
object as decimal.Decimal</p>
</blockquote>
<p>What does that exactly mean? It does not seem to be making a lot of sense...
It seems to be connected with django caching. You can see the whole traceback here: </p>
<blockquote>
<p>Traceback (most recent call last):</p>
<p>File
"/home/filmaster/django-trunk/django/core/handlers/base.py",
line 92, in get_response response =
callback(request, *callback_args,
**callback_kwargs)</p>
<p>File
"/home/filmaster/film20/film20/core/film_views.py",
line 193, in show_film<br />
workflow.set_data_for_authenticated_user()</p>
<p>File
"/home/filmaster/film20/film20/core/film_views.py",
line 518, in
set_data_for_authenticated_user<br />
object_id = self.the_film.parent.id)</p>
<p>File
"/home/filmaster/film20/film20/core/film_helper.py",
line 179, in get_others_ratings<br />
set_cache(CACHE_OTHERS_RATINGS,
str(object_id) + "_" + str(user_id),
userratings)</p>
<p>File
"/home/filmaster/film20/film20/utils/cache_helper.py",
line 80, in set_cache return
cache.set(CACHE_MIDDLEWARE_KEY_PREFIX
+ full_path, result, get_time(cache_string))</p>
<p>File
"/home/filmaster/django-trunk/django/core/cache/backends/memcached.py",
line 37, in set<br />
self._cache.set(smart_str(key), value,
timeout or self.default_timeout)</p>
<p>File
"/usr/lib/python2.5/site-packages/cmemcache.py",
line 128, in set val, flags =
self._convert(val)</p>
<p>File
"/usr/lib/python2.5/site-packages/cmemcache.py",
line 112, in _convert val =
pickle.dumps(val, 2)</p>
<p>PicklingError: Can't pickle : it's not the same
object as decimal.Decimal</p>
</blockquote>
<p>And the source code for Filmaster can be downloaded from here: <a href="http://bitbucket.org/filmaster/filmaster-test/">bitbucket.org/filmaster/filmaster-test</a></p>
<p>Any help will be greatly appreciated.</p>
| 6 | 2009-09-11T19:13:23Z | 39,812,728 | <p>There can be issues starting a process with <code>multiprocessing</code> by calling <code>__init__</code>. Here's a demo:</p>
<pre><code>import multiprocessing as mp
class SubProcClass:
def __init__(self, pipe, startloop=False):
self.pipe = pipe
if startloop:
self.do_loop()
def do_loop(self):
while True:
req = self.pipe.recv()
self.pipe.send(req * req)
class ProcessInitTest:
def __init__(self, spawn=False):
if spawn:
mp.set_start_method('spawn')
(self.msg_pipe_child, self.msg_pipe_parent) = mp.Pipe(duplex=True)
def start_process(self):
subproc = SubProcClass(self.msg_pipe_child)
self.trig_proc = mp.Process(target=subproc.do_loop, args=())
self.trig_proc.daemon = True
self.trig_proc.start()
def start_process_fail(self):
self.trig_proc = mp.Process(target=SubProcClass.__init__, args=(self.msg_pipe_child,))
self.trig_proc.daemon = True
self.trig_proc.start()
def do_square(self, num):
# Note: this is an synchronous usage of mp,
# which doesn't make sense. But this is just for demo
self.msg_pipe_parent.send(num)
msg = self.msg_pipe_parent.recv()
print('{}^2 = {}'.format(num, msg))
</code></pre>
<p>Now, with the above code, if we run this:</p>
<pre><code>if __name__ == '__main__':
t = ProcessInitTest(spawn=True)
t.start_process_fail()
for i in range(1000):
t.do_square(i)
</code></pre>
<p>We get this error:</p>
<pre><code>Traceback (most recent call last):
File "start_class_process1.py", line 40, in <module>
t.start_process_fail()
File "start_class_process1.py", line 29, in start_process_fail
self.trig_proc.start()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/process.py", line 105, in start
self._popen = self._Popen(self)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/context.py", line 212, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/context.py", line 274, in _Popen
return Popen(process_obj)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/popen_spawn_posix.py", line 33, in __init__
super().__init__(process_obj)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/popen_fork.py", line 21, in __init__
self._launch(process_obj)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/popen_spawn_posix.py", line 48, in _launch
reduction.dump(process_obj, fp)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/reduction.py", line 59, in dump
ForkingPickler(file, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <function SubProcClass.__init__ at 0x10073e510>: it's not the same object as __main__.__init__
</code></pre>
<p>And if we change it to use <code>fork</code> instead of <code>spawn</code>:</p>
<pre><code>if __name__ == '__main__':
t = ProcessInitTest(spawn=False)
t.start_process_fail()
for i in range(1000):
t.do_square(i)
</code></pre>
<p>We get this error:</p>
<pre><code>Process Process-1:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/process.py", line 254, in _bootstrap
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
TypeError: __init__() missing 1 required positional argument: 'pipe'
</code></pre>
<p>But if we call the <code>start_process</code> method, which doesn't call <code>__init__</code> in the <code>mp.Process</code> target, like this:</p>
<pre><code>if __name__ == '__main__':
t = ProcessInitTest(spawn=False)
t.start_process()
for i in range(1000):
t.do_square(i)
</code></pre>
<p>It works as expected (whether we use <code>spawn</code> or <code>fork</code>).</p>
| 0 | 2016-10-02T00:19:12Z | [
"python",
"django",
"pickle"
] |
python mysql fetch query | 1,413,057 | <pre><code>def dispcar ( self, reg ):
print ("The car information for '%s' is: "), (reg)
numrows = int(self.dbc.rowcount) #get the count of total rows
self.dbc.execute("select * from car where reg='%s'") %(reg)
for x in range(0, numrows):
car_info = self.dbc.fetchone()
print row[0], "-->", row[1]
</code></pre>
<p>the above code gives this error:</p>
<pre><code>self.dbc.execute("select * from car where reg='%s' " %(reg)
TypeError: unsupported operand type(s) for %: 'long' and 'str'
</code></pre>
<p>can anyone please help me understand why am i getting this error?</p>
<p>FYI: reg is a raw_input var i input from user in the function getitem and pass the reg var as an argument to this function.</p>
| 2 | 2009-09-11T20:20:39Z | 1,413,100 | <p>I think this line simply has the parens in the wrong place:</p>
<pre><code>self.dbc.execute("select * from car where reg='%s'") %(reg)
</code></pre>
<p>You are using % on the result of execute(), and reg.</p>
<p>Change it to:</p>
<pre><code>self.dbc.execute("select * from car where reg='%s'" % reg)
</code></pre>
<p>or</p>
<pre><code>self.dbc.execute("select * from car where reg='%s'", reg)
</code></pre>
<p>depending on whether it will do the param substitution for you.</p>
| 3 | 2009-09-11T20:26:48Z | [
"python",
"mysql"
] |
python mysql fetch query | 1,413,057 | <pre><code>def dispcar ( self, reg ):
print ("The car information for '%s' is: "), (reg)
numrows = int(self.dbc.rowcount) #get the count of total rows
self.dbc.execute("select * from car where reg='%s'") %(reg)
for x in range(0, numrows):
car_info = self.dbc.fetchone()
print row[0], "-->", row[1]
</code></pre>
<p>the above code gives this error:</p>
<pre><code>self.dbc.execute("select * from car where reg='%s' " %(reg)
TypeError: unsupported operand type(s) for %: 'long' and 'str'
</code></pre>
<p>can anyone please help me understand why am i getting this error?</p>
<p>FYI: reg is a raw_input var i input from user in the function getitem and pass the reg var as an argument to this function.</p>
| 2 | 2009-09-11T20:20:39Z | 1,413,103 | <p>You got the brackets wrong:</p>
<pre><code>self.dbc.execute("select * from car where reg=%s" , (reg,))
</code></pre>
<p>Any particular reason you are looping using fetchone (in this ugly loop with a range based on a rowcount which will probably be zero as you get it before you execute the query)?</p>
<p>Just do</p>
<pre><code>for car_info in self.dbc.fetchall():
....
</code></pre>
| 2 | 2009-09-11T20:27:58Z | [
"python",
"mysql"
] |
python mysql fetch query | 1,413,057 | <pre><code>def dispcar ( self, reg ):
print ("The car information for '%s' is: "), (reg)
numrows = int(self.dbc.rowcount) #get the count of total rows
self.dbc.execute("select * from car where reg='%s'") %(reg)
for x in range(0, numrows):
car_info = self.dbc.fetchone()
print row[0], "-->", row[1]
</code></pre>
<p>the above code gives this error:</p>
<pre><code>self.dbc.execute("select * from car where reg='%s' " %(reg)
TypeError: unsupported operand type(s) for %: 'long' and 'str'
</code></pre>
<p>can anyone please help me understand why am i getting this error?</p>
<p>FYI: reg is a raw_input var i input from user in the function getitem and pass the reg var as an argument to this function.</p>
| 2 | 2009-09-11T20:20:39Z | 1,413,449 | <p>This confuses just about everyone who works with MySQLDB. You are passing arguments to the execute function, not doing python string substitution. The %s in the query string is used more like a prepared statement than a python string substitution. This also prevents SQL injection as MySQLDB will do the escaping for you. As you had it before (using % and string substitution), you are vulnerable to injection.</p>
<ol>
<li>Don't use quotes. MySQLDB will put them there (if needed).</li>
<li><p>Use a , instead of a %. Again, you are passing a tuple as an argument to the execute function.</p>
<p>self.dbc.execute("select * from car where reg=%s" , (reg,))</p></li>
</ol>
| 3 | 2009-09-11T21:49:12Z | [
"python",
"mysql"
] |
Sorting by a field of another table referenced by a foreign key in SQLObject | 1,413,101 | <p>Is it possible to sort results returned by SQLObject by a value of another table?</p>
<p>I have two tables:</p>
<pre><code> class Foo(SQLObject):
bar = ForeignKey('Bar')
class Bar(SQLObject):
name = StringCol()
foos = MultipleJoin('Foo')
</code></pre>
<p>I'd like to get <code>foo</code>s sorted by the <code>name</code> of a <code>bar</code> they are related to.</p>
<p>Doing:</p>
<pre><code> foos = Foo.select().orderBy(Foo.q.bar)
</code></pre>
<p>...would sort the output by <code>bar</code>'s ids, but how do I sort them by <code>bar</code>'s name?</p>
| 1 | 2009-09-11T20:27:08Z | 1,437,840 | <p>Below is the answer of a SQLObject maintainer (he has trouble posting it himself because captcha is not displayed):</p>
<p>Do an explicit join:</p>
<pre><code>foos = Foo.select(Foo.q.barID==Bar.q.id, orderBy=Bar.q.name)
</code></pre>
<p>This generates a query:</p>
<pre><code>SELECT foo.id, foo.bar_id FROM foo, bar WHERE ((foo.bar_id) = (bar.id)) ORDER BY bar.name
</code></pre>
<p>PS. I am the current maintainer of SQLObject. I don't visit stackoverflow.com; a friend of mine pointed me to the question. If you have more questions about SQLObject I invite you to the <a href="http://sqlobject.org/community.html" rel="nofollow">SQLObject mailing list</a> .</p>
| 3 | 2009-09-17T10:02:25Z | [
"python",
"sorting",
"sqlobject"
] |
Showing an image from console in Python | 1,413,540 | <p>What is the easiest way to show a <code>.jpg</code> or <code>.gif</code> image from Python console?</p>
<p>I've got a Python console program that is checking a data set which contains links to images stored locally. How should I write the script so that it would display images pop-up graphical windows?</p>
| 13 | 2009-09-11T22:22:50Z | 1,413,561 | <p>You cannot display images in a console window.
You need a graphical toolkit such as Tkinter, PyGTK, PyQt, PyKDE, wxPython, PyObjC or PyFLTK.
There are plenty of tutorial how to create siomple windows and loading images iun python.</p>
| 4 | 2009-09-11T22:31:58Z | [
"python",
"image"
] |
Showing an image from console in Python | 1,413,540 | <p>What is the easiest way to show a <code>.jpg</code> or <code>.gif</code> image from Python console?</p>
<p>I've got a Python console program that is checking a data set which contains links to images stored locally. How should I write the script so that it would display images pop-up graphical windows?</p>
| 13 | 2009-09-11T22:22:50Z | 1,413,567 | <p>Using the awesome <a href="https://pypi.python.org/pypi/Pillow/2.7.0">Pillow</a> library:</p>
<pre><code>>>> from PIL import Image
>>> img = Image.open('test.png')
>>> img.show()
</code></pre>
<p>This will open the image in your default image viewer.</p>
| 22 | 2009-09-11T22:34:22Z | [
"python",
"image"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.