title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How to redirect the output of .exe to a file in python?
880,918
<p>In a script , I want to run a .exe with some command line parameters as "-a",and then</p> <p>redirect the standard output of the program to a file?</p> <p>How can I implement that?</p>
12
2009-05-19T04:03:32Z
880,929
<p>Easiest is <code>os.system("the.exe -a &gt;thefile.txt")</code>, but there are many other ways, for example with the <code>subprocess</code> module in the standard library.</p>
7
2009-05-19T04:07:35Z
[ "python", "redirect", "io" ]
How to redirect the output of .exe to a file in python?
880,918
<p>In a script , I want to run a .exe with some command line parameters as "-a",and then</p> <p>redirect the standard output of the program to a file?</p> <p>How can I implement that?</p>
12
2009-05-19T04:03:32Z
881,501
<p>You can do something like this e.g. to read output of ls -l (or any other command)</p> <pre><code>p = subprocess.Popen(["ls","-l"],stdout=subprocess.PIPE) print p.stdout.read() # or put it in a file </code></pre> <p>you can do similar thing for stderr/stdin</p> <p>but as Alex mentioned if you just want it in a file, just redirect the cmd output to a file</p>
3
2009-05-19T08:05:29Z
[ "python", "redirect", "io" ]
How to redirect the output of .exe to a file in python?
880,918
<p>In a script , I want to run a .exe with some command line parameters as "-a",and then</p> <p>redirect the standard output of the program to a file?</p> <p>How can I implement that?</p>
12
2009-05-19T04:03:32Z
881,552
<p>If you just want to run the executable and wait for the results, Anurag's solution is probably the best. I needed to respond to each line of output as it arrived, and found the following worked:</p> <p>1) Create an object with a write(text) method. Redirect stdout to it (sys.stdout = obj). In your write method, deal with the output as it arrives.</p> <p>2) Run a method in a seperate thread with something like the following code:</p> <pre><code> p = subprocess.Popen('Text/to/execute with-arg', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) while p.poll() is None: print p.stdout.readline().strip() </code></pre> <p>Because you've redirected stdout, PIPE will send the output to your write method line by line. If you're not certain you're going to get line breaks, read(amount) works too, I believe.</p> <p>3) Remember to redirect stdout back to the default: sys.stdout = <code>__sys.stdout__</code></p>
0
2009-05-19T08:21:20Z
[ "python", "redirect", "io" ]
How to redirect the output of .exe to a file in python?
880,918
<p>In a script , I want to run a .exe with some command line parameters as "-a",and then</p> <p>redirect the standard output of the program to a file?</p> <p>How can I implement that?</p>
12
2009-05-19T04:03:32Z
881,686
<p>You can redirect directly to a file using subprocess.</p> <pre><code>import subprocess with open('output.txt', 'w') as output_f: p = subprocess.Popen('Text/to/execute with-arg', stdout=output_f, stderr=output_f) </code></pre>
21
2009-05-19T09:02:05Z
[ "python", "redirect", "io" ]
How to redirect the output of .exe to a file in python?
880,918
<p>In a script , I want to run a .exe with some command line parameters as "-a",and then</p> <p>redirect the standard output of the program to a file?</p> <p>How can I implement that?</p>
12
2009-05-19T04:03:32Z
14,994,325
<p>Although the title (.exe) sounds like it's a problem on Windows. I had to share that the accepted answer (subprocess.Popen() with stdout/stderr arguments) didn't work for me on Mac OS X (10.8) with python 2.7.</p> <p>I had to use subprocess.check_output() (python 2.7 and above) to make it work. Example:</p> <pre><code>import subprocess cmd = 'ls -l' out = subprocess.check_output(cmd, shell=True) with open('my.log', 'w') as f: f.writelines(out) f.close() </code></pre> <p>Note that this solution writes all the accumulated output out when the program finishes. If you want to monitor the log file during the run. You may want to try something else. In my own case, I only cared about the end result.</p>
0
2013-02-21T04:02:35Z
[ "python", "redirect", "io" ]
Pythonic URL Parsing
880,988
<p>There are a number of questions about how to parse a URL in Python, this question is about the best or most Pythonic way to do it. </p> <p>In my parsing I need 4 parts: the network location, the first part of the URL, the path and the filename and querystring parts.</p> <p><a href="http://www.somesite.com/base/first/second/third/fourth/foo.html?abc=123" rel="nofollow">http://www.somesite.com/base/first/second/third/fourth/foo.html?abc=123</a> </p> <p>should parse into:</p> <pre><code>netloc = 'www.somesite.com' baseURL = 'base' path = '/first/second/third/fourth/' file = 'foo.html?abc=123' </code></pre> <p>The code below produces the correct result, but is there are better way to do this in Python?</p> <pre><code>url = "http://www.somesite.com/base/first/second/third/fourth/foo.html?abc=123" file= url.rpartition('/')[2] netloc = urlparse(url)[1] pathParts = path.split('/') baseURL = pathParts[1] partCount = len(pathParts) - 1 path = "/" for i in range(2, partCount): path += pathParts[i] + "/" print 'baseURL= ' + baseURL print 'path= ' + path print 'file= ' + file print 'netloc= ' + netloc </code></pre>
0
2009-05-19T04:36:31Z
880,995
<p>Since your requirements on what parts you want are different from what urlparse gives you, that's as good as it's going to get. You could, however, replace this:</p> <pre><code>partCount = len(pathParts) - 1 path = "/" for i in range(2, partCount): path += pathParts[i] + "/" </code></pre> <p>With this:</p> <pre><code>path = '/'.join(pathParts[2:-1]) </code></pre>
6
2009-05-19T04:44:12Z
[ "url", "python" ]
Pythonic URL Parsing
880,988
<p>There are a number of questions about how to parse a URL in Python, this question is about the best or most Pythonic way to do it. </p> <p>In my parsing I need 4 parts: the network location, the first part of the URL, the path and the filename and querystring parts.</p> <p><a href="http://www.somesite.com/base/first/second/third/fourth/foo.html?abc=123" rel="nofollow">http://www.somesite.com/base/first/second/third/fourth/foo.html?abc=123</a> </p> <p>should parse into:</p> <pre><code>netloc = 'www.somesite.com' baseURL = 'base' path = '/first/second/third/fourth/' file = 'foo.html?abc=123' </code></pre> <p>The code below produces the correct result, but is there are better way to do this in Python?</p> <pre><code>url = "http://www.somesite.com/base/first/second/third/fourth/foo.html?abc=123" file= url.rpartition('/')[2] netloc = urlparse(url)[1] pathParts = path.split('/') baseURL = pathParts[1] partCount = len(pathParts) - 1 path = "/" for i in range(2, partCount): path += pathParts[i] + "/" print 'baseURL= ' + baseURL print 'path= ' + path print 'file= ' + file print 'netloc= ' + netloc </code></pre>
0
2009-05-19T04:36:31Z
881,314
<p>I'd be inclined to start out with <code>urlparse</code>. Also, you can use <code>rsplit</code>, and the <code>maxsplit</code> parameter of <code>split</code> and <code>rsplit</code> to simplify things a bit:</p> <pre><code>_, netloc, path, _, q, _ = urlparse(url) _, base, path = path.split('/', 2) # 1st component will always be empty path, file = path.rsplit('/', 1) if q: file += '?' + q </code></pre>
2
2009-05-19T06:55:31Z
[ "url", "python" ]
Error when trying to migrate django application with south
880,989
<p>I am getting this error when running "./manage.py migrate app_name"</p> <pre><code>While loading migration 'whatever.0001_initial': Traceback (most recent call last): File "manage.py", line 14, in &lt;module&gt; execute_manager(settings) ...tons of other stuff.. raise KeyError("The model '%s' from the app '%s' is not available in this migration." % (model, app)) KeyError: "The model 'appuser' from the app 'whatever' is not available in this migration." </code></pre> <p>I am sure that model "appuser" is both in application models.py and in 0001_initial.py</p> <p>AppUser model from models.py:</p> <pre><code>class AppUser(models.Model): person = models.OneToOneField('Person') user = models.ForeignKey(User, unique=True) class Meta: permissions = ( ('is_one', 'one'), ('is_two', 'two') ) def __unicode__(self): return self.person.__unicode__() </code></pre> <p>AppUser model from 0001_initial.py:</p> <pre><code> # Adding model 'AppUser' db.create_table('app_appuser', ( ('person', models.OneToOneField(orm.Person)), ('id', models.AutoField(primary_key=True)), ('user', models.ForeignKey(orm['auth.User'], unique=True)), )) db.send_create_signal('app', ['AppUser']) ... 'app.appuser': { 'Meta': {'permissions': "(('is_one','one'),('is_two','two'))"}, 'id': ('models.AutoField', [], {'primary_key': 'True'}), 'person': ('models.OneToOneField', ["'Person'"], {}), 'user': ('models.ForeignKey', ['User'], {'unique': 'True'}) }, </code></pre> <p>I am trying to run it on empty database (ie. no "app_*" tables) like that:</p> <pre><code>manage.py migrate app </code></pre> <p>This seem to be happening only on python 2.5 on Mac OS, no probs with Ubuntu/python 2.6</p> <p>Question - how to fix?</p> <p>Thanks!</p>
0
2009-05-19T04:36:40Z
885,716
<p>The problem seemed to be with the order of models in the 0001_initial.py file. There was a class which derived from AppUser. When I re-created the migration on Mac OS with</p> <pre><code>manage.py startmigration app --initial </code></pre> <p>and compared that to one generated on Ubuntu the order of models was different. So when I changed the order to match the one on Mac OS, everything worked fine.</p> <p>This problem seems to exist only in 0.5 version of south and is supposedly fixed on trunk.</p>
2
2009-05-20T00:53:37Z
[ "python", "database", "django", "migration" ]
Apple Event Handler Failure (Python/AppScript)
881,041
<p>I have written the following really simple python script to change the desktop wallpaper on my mac (based on this <a href="http://stackoverflow.com/questions/431205/how-can-i-programatically-change-the-background-in-mac-os-x">thread</a>):</p> <pre><code>from appscript import app, mactypes import sys fileName = sys.argv[1:] app('Finder').desktop_picture.set(mactypes.File(fileName)) </code></pre> <p>However when I run it I get the following output:</p> <blockquote> <p>Traceback (most recent call last):<br /> File "../Source/SetWallPaper2.py", line 6, in app('Finder').desktop_picture.set(mactypes.File(fileName)) File "/Library/Python/2.5/site-packages/appscript-0.19.0-py2.5-macosx-10.5-i386.egg/appscript/reference.py", line 513, in <strong>call</strong> appscript.reference.CommandError: Command failed: OSERROR: -10000 MESSAGE: Apple event handler failed. COMMAND: app(u'/System/Library/CoreServices/Finder.app').desktop_picture.set(mactypes.File(u"/Users/Daniel/Pictures/['test.jpg']"))</p> </blockquote> <p>I've done some web searching but I can't find anything to help me figure out what OSERROR -10000 means or how to resolve the issue.</p>
1
2009-05-19T05:06:55Z
881,328
<p>fileName = sys.argv[1] instead of fileName = sys.argv[1:]</p> <p>mactypes.File(u"/Users/Daniel/Pictures/['test.jpg']") See the square brackets and quotes around the filename?</p>
2
2009-05-19T06:59:03Z
[ "python", "debugging", "osx", "appscript" ]
Apple Event Handler Failure (Python/AppScript)
881,041
<p>I have written the following really simple python script to change the desktop wallpaper on my mac (based on this <a href="http://stackoverflow.com/questions/431205/how-can-i-programatically-change-the-background-in-mac-os-x">thread</a>):</p> <pre><code>from appscript import app, mactypes import sys fileName = sys.argv[1:] app('Finder').desktop_picture.set(mactypes.File(fileName)) </code></pre> <p>However when I run it I get the following output:</p> <blockquote> <p>Traceback (most recent call last):<br /> File "../Source/SetWallPaper2.py", line 6, in app('Finder').desktop_picture.set(mactypes.File(fileName)) File "/Library/Python/2.5/site-packages/appscript-0.19.0-py2.5-macosx-10.5-i386.egg/appscript/reference.py", line 513, in <strong>call</strong> appscript.reference.CommandError: Command failed: OSERROR: -10000 MESSAGE: Apple event handler failed. COMMAND: app(u'/System/Library/CoreServices/Finder.app').desktop_picture.set(mactypes.File(u"/Users/Daniel/Pictures/['test.jpg']"))</p> </blockquote> <p>I've done some web searching but I can't find anything to help me figure out what OSERROR -10000 means or how to resolve the issue.</p>
1
2009-05-19T05:06:55Z
2,568,439
<p>In the above, what would be the format for copying one file to another folder?</p> <p>IS it something like app('Finder').copy (mactypes.File(u"/Users/Daniel/Pictures/['test.jpg']")) to_folder (mactypes.File(u"/Users/Daniel/OLD_PIX/))</p> <p>Thanks for the help, Frank</p>
0
2010-04-02T18:35:42Z
[ "python", "debugging", "osx", "appscript" ]
Google App Engine self.redirect post
881,086
<p>I have a form that POSTs information to one of my handlers. My handler verifies the information and then needs to POST this information to a third party AND redirect the user to that page.</p> <p>Example of the </p> <pre><code> class ExampleHandler(BaseRequestHandler): """DocString here... """ def post(self): day = int(self.request.get('day')) checked_day = CheckDay(day) if checked_day: #Here is where I would like to redirect the user to the 3rd party -- but via a post as I will be submitting a form based on data in checked_day on their behalf. else: # Otherwise no post redirect is needed -- just a simple self.redirect. self.redirect('/example') </code></pre> <p>Do you have any advice on how I can redirect the user to the page where I have submitted a form?</p> <p>I would ideally like a self.redirect() that allowed POSTs to 3rd party sites but I don't believe this is an option.</p> <p>My goal is to check the data provided before sending them along to the 3rd party. Are their other options I am missing?</p>
2
2009-05-19T05:24:40Z
881,171
<p>You can POST the form and redirect the user to a page, but they'll have to be separate operations.</p> <p>The <code>urlfetch.fetch()</code> method lets you set the method to POST like so:</p> <pre><code>import urllib form_fields = { "first_name": "Albert", "last_name": "Johnson", "email_address": "Albert.Johnson@example.com" } form_data = urllib.urlencode(form_fields) headers = {'Content-Type': 'application/x-www-form-urlencoded'} result = urlfetch.fetch(url=url, payload=form_data, method=urlfetch.POST, headers=headers) </code></pre> <p>The above example is from the <a href="http://code.google.com/appengine/docs/python/urlfetch/overview.html" rel="nofollow">URL Fetch Python API Overview</a>.</p>
1
2009-05-19T06:03:42Z
[ "python", "google-app-engine" ]
How to suppress the carriage return in python 2?
881,160
<pre><code> myfile = open("wrsu"+str(i)+'_'+str(j)+'_'+str(TimesToExec)+".txt",'w') sys.stdout = myfile p1 = subprocess.Popen([pathname,"r", "s","u",str(i),str(j),str(runTime)],stdout=subprocess.PIPE) output = p1.communicate()[0] print output, </code></pre> <p>When I use this to redirect the output of a exe to my own file, it always</p> <p>a carriage return after each line, How to suppress it?</p>
2
2009-05-19T05:59:39Z
881,182
<p>Here's how I removed the carriage return:</p> <pre><code> p = Popen([vmrun_cmd, list_arg], stdout=PIPE).communicate()[0] for line in p.splitlines(): if line.strip(): print line </code></pre>
2
2009-05-19T06:08:30Z
[ "python", "io" ]
How to suppress the carriage return in python 2?
881,160
<pre><code> myfile = open("wrsu"+str(i)+'_'+str(j)+'_'+str(TimesToExec)+".txt",'w') sys.stdout = myfile p1 = subprocess.Popen([pathname,"r", "s","u",str(i),str(j),str(runTime)],stdout=subprocess.PIPE) output = p1.communicate()[0] print output, </code></pre> <p>When I use this to redirect the output of a exe to my own file, it always</p> <p>a carriage return after each line, How to suppress it?</p>
2
2009-05-19T05:59:39Z
881,231
<pre><code>def Popenstrip(self): p = Popen([vmrun_cmd, list_arg], stdout=PIPE).communicate()[0] return (line for line in p.splitlines() if line.strip()) </code></pre>
1
2009-05-19T06:25:12Z
[ "python", "io" ]
How to suppress the carriage return in python 2?
881,160
<pre><code> myfile = open("wrsu"+str(i)+'_'+str(j)+'_'+str(TimesToExec)+".txt",'w') sys.stdout = myfile p1 = subprocess.Popen([pathname,"r", "s","u",str(i),str(j),str(runTime)],stdout=subprocess.PIPE) output = p1.communicate()[0] print output, </code></pre> <p>When I use this to redirect the output of a exe to my own file, it always</p> <p>a carriage return after each line, How to suppress it?</p>
2
2009-05-19T05:59:39Z
9,459,105
<pre><code>print line.rstrip('\r\n') </code></pre> <p>will do fine.</p>
0
2012-02-27T01:44:35Z
[ "python", "io" ]
how to send email in python
881,184
<pre><code>import smtplib SERVER = "localhost" FROM = "sender@example.com" TO = ["user@example.com"] SUBJECT = "Hello!" TEXT = "This message was sent with Python's smtplib." server = smtplib.SMTP(SERVER) server.sendmail(FROM, TO, message) server.quit() </code></pre> <p>This is giving the error:</p> <pre><code>'**The debugged program raised the exception unhandled AttributeError "'module' object has no attribute 'SMTP'" File: /home/an/Desktop/email.py, Line: 13**' </code></pre>
2
2009-05-19T06:08:51Z
881,200
<p>Rename your file to something other than email.py. Also get rid of any email.pyc file left over. Problem solved.</p>
12
2009-05-19T06:14:45Z
[ "python" ]
how to send email in python
881,184
<pre><code>import smtplib SERVER = "localhost" FROM = "sender@example.com" TO = ["user@example.com"] SUBJECT = "Hello!" TEXT = "This message was sent with Python's smtplib." server = smtplib.SMTP(SERVER) server.sendmail(FROM, TO, message) server.quit() </code></pre> <p>This is giving the error:</p> <pre><code>'**The debugged program raised the exception unhandled AttributeError "'module' object has no attribute 'SMTP'" File: /home/an/Desktop/email.py, Line: 13**' </code></pre>
2
2009-05-19T06:08:51Z
881,318
<p>This happens because email is a <a href="http://docs.python.org/library/email" rel="nofollow">built-in library</a> that comes standard with python. If you rename your program to something else (as suggested above), that should do the trick.</p>
5
2009-05-19T06:56:17Z
[ "python" ]
Error occurs when I connect with socket in Python
881,332
<p>Nice to meet you. A socket makes a program in Python by Linux (the transmission of a message) ⇒ Windows (the reception), b ut the following errors occur and cannot connect now. Linux, Windows are network connection together, and there is the authority to cut.</p> <p>socket.error: (111, 'Connection refused')</p> <p>Could you help me!?</p>
0
2009-05-19T07:00:35Z
881,349
<p>111 means the listener is down/not accepting connections - restart the Windows app that should be listening for connections, or disconnect any already-bound clients.</p>
2
2009-05-19T07:06:03Z
[ "python", "sockets" ]
What is the reason for performing a double fork when creating a daemon?
881,388
<p>I'm trying to create a daemon in python. I've found the <a href="http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python">following question</a>, which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found plenty of resources declaring that one is necessary, but not why.</p> <p>Some mention that it is to prevent the daemon from acquiring a controlling terminal. How would it do this without the second fork? What are the repercussions?</p>
109
2009-05-19T07:25:18Z
881,408
<p>Taken from <a href="http://blog.charcoalphile.com/2008/05/03/python-tips-for-writing-daemons/">Bad CTK</a>:</p> <p>"On some flavors of Unix, you are forced to do a double-fork on startup, in order to go into daemon mode. This is because single forking isn’t guaranteed to detach from the controlling terminal."</p>
11
2009-05-19T07:32:26Z
[ "python", "unix" ]
What is the reason for performing a double fork when creating a daemon?
881,388
<p>I'm trying to create a daemon in python. I've found the <a href="http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python">following question</a>, which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found plenty of resources declaring that one is necessary, but not why.</p> <p>Some mention that it is to prevent the daemon from acquiring a controlling terminal. How would it do this without the second fork? What are the repercussions?</p>
109
2009-05-19T07:25:18Z
881,412
<p>The daemon() call has the parent call _exit() if it succeeds. The original motivation may have been to allow the parent to do some extra work while the child is daemonizing.</p> <p>It may also be based on a mistaken belief that it's necessary in order to ensure the daemon has no parent process and is reparented to init - but this will happen anyway once the parent dies in the single fork case.</p> <p>So I suppose it all just boils down to tradition in the end - a single fork is sufficient as long as the parent dies in short order anyway.</p>
2
2009-05-19T07:33:16Z
[ "python", "unix" ]
What is the reason for performing a double fork when creating a daemon?
881,388
<p>I'm trying to create a daemon in python. I've found the <a href="http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python">following question</a>, which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found plenty of resources declaring that one is necessary, but not why.</p> <p>Some mention that it is to prevent the daemon from acquiring a controlling terminal. How would it do this without the second fork? What are the repercussions?</p>
109
2009-05-19T07:25:18Z
881,415
<p>According to "Advanced Programming in the Unix Environment", by Stephens and Rago, the second fork is more a recommendation, and it is done to guarantee that the daemon does not acquire a controlling terminal on System V-based systems. </p>
8
2009-05-19T07:33:54Z
[ "python", "unix" ]
What is the reason for performing a double fork when creating a daemon?
881,388
<p>I'm trying to create a daemon in python. I've found the <a href="http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python">following question</a>, which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found plenty of resources declaring that one is necessary, but not why.</p> <p>Some mention that it is to prevent the daemon from acquiring a controlling terminal. How would it do this without the second fork? What are the repercussions?</p>
109
2009-05-19T07:25:18Z
881,434
<p>Looking at the code referenced in the question, the justification is:</p> <pre><code># Fork a second child and exit immediately to prevent zombies. This # causes the second child process to be orphaned, making the init # process responsible for its cleanup. And, since the first child is # a session leader without a controlling terminal, it's possible for # it to acquire one by opening a terminal in the future (System V- # based systems). This second fork guarantees that the child is no # longer a session leader, preventing the daemon from ever acquiring # a controlling terminal. </code></pre> <p>So it is to ensure that the daemon is re-parented onto init (just in case the process kicking off the daemon is long lived), and removes any chance of the daemon reacquiring a controlling tty. So if neither of these cases apply, then one fork should be sufficient. "<a href="http://rads.stackoverflow.com/amzn/click/0201433079">Unix Network Programming - Stevens</a>" has a good section on this.</p>
75
2009-05-19T07:42:54Z
[ "python", "unix" ]
What is the reason for performing a double fork when creating a daemon?
881,388
<p>I'm trying to create a daemon in python. I've found the <a href="http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python">following question</a>, which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found plenty of resources declaring that one is necessary, but not why.</p> <p>Some mention that it is to prevent the daemon from acquiring a controlling terminal. How would it do this without the second fork? What are the repercussions?</p>
109
2009-05-19T07:25:18Z
881,435
<p>One reason is that the parent process can immediately wait_pid() for the child, and then forget about it. When then grand-child dies, it's parent is init, and it will wait() for it - and taking it out of the zombie state. </p> <p>The result is that the parent process doesn't need to be aware of the forked children, and it also makes it possible to fork long running processes from libs etc.</p>
3
2009-05-19T07:43:39Z
[ "python", "unix" ]
What is the reason for performing a double fork when creating a daemon?
881,388
<p>I'm trying to create a daemon in python. I've found the <a href="http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python">following question</a>, which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found plenty of resources declaring that one is necessary, but not why.</p> <p>Some mention that it is to prevent the daemon from acquiring a controlling terminal. How would it do this without the second fork? What are the repercussions?</p>
109
2009-05-19T07:25:18Z
881,470
<p>A decent discussion of it appear to be at <a href="http://www.developerweb.net/forum/showthread.php?t=3025" rel="nofollow">http://www.developerweb.net/forum/showthread.php?t=3025</a></p> <p>Quoting mlampkin from there:</p> <blockquote> <p>...think of the setsid( ) call as the "new" way to do thing (disassociate from the terminal) and the [second] fork( ) call after it as redundancy to deal with the SVr4...</p> </blockquote>
2
2009-05-19T07:56:23Z
[ "python", "unix" ]
What is the reason for performing a double fork when creating a daemon?
881,388
<p>I'm trying to create a daemon in python. I've found the <a href="http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python">following question</a>, which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found plenty of resources declaring that one is necessary, but not why.</p> <p>Some mention that it is to prevent the daemon from acquiring a controlling terminal. How would it do this without the second fork? What are the repercussions?</p>
109
2009-05-19T07:25:18Z
5,386,753
<p>I was trying to understand the double fork and stumbled upon this question here. After a lot of research this is what I figured out. Hopefully it will help clarify things better for anyone who has the same question.</p> <p>In Unix every process belongs to a group which in turn belongs to a session. Here is the hierarchy…</p> <p>Session (SID) → Process Group (PGID) → Process (PID)</p> <p>The first process in the process group becomes the process group leader and the first process in the session becomes the session leader. Every session can have one TTY associated with it. Only a session leader can take control of a TTY. For a process to be truly daemonized (ran in the background) we should ensure that the session leader is killed so that there is no possibility of the session ever taking control of the TTY. </p> <p>I ran Sander Marechal's python example daemon program from <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">this site</a> on my Ubuntu. Here are the results with my comments. </p> <pre class="lang-none prettyprint-override"><code>1. `Parent` = PID: 28084, PGID: 28084, SID: 28046 2. `Fork#1` = PID: 28085, PGID: 28084, SID: 28046 3. `Decouple#1`= PID: 28085, PGID: 28085, SID: 28085 4. `Fork#2` = PID: 28086, PGID: 28085, SID: 28085 </code></pre> <p>Note that the process is the session leader after <code>Decouple#1</code>, because it's <code>PID = SID</code>. It could still take control of a TTY.</p> <p>Note that <code>Fork#2</code> is no longer the session leader <code>PID != SID</code>. This process can never take control of a TTY. <em>Truly daemonized.</em></p> <p>I personally find terminology fork-twice to be confusing. A better idiom might be fork-decouple-fork.</p> <p>Additional links of interest:</p> <ul> <li>Unix processes - <a href="http://www.win.tue.nl/~aeb/linux/lk/lk-10.html">http://www.win.tue.nl/~aeb/linux/lk/lk-10.html</a></li> </ul>
111
2011-03-22T04:19:44Z
[ "python", "unix" ]
What is the reason for performing a double fork when creating a daemon?
881,388
<p>I'm trying to create a daemon in python. I've found the <a href="http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python">following question</a>, which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found plenty of resources declaring that one is necessary, but not why.</p> <p>Some mention that it is to prevent the daemon from acquiring a controlling terminal. How would it do this without the second fork? What are the repercussions?</p>
109
2009-05-19T07:25:18Z
16,317,668
<p>Strictly speaking, the double-fork has nothing to do with re-parenting the daemon as a child of <code>init</code>. All that is necessary to re-parent the child is that the parent must exit. This can be done with only a single fork. Also, doing a double-fork by itself doesn't re-parent the daemon process to <code>init</code>; the daemon's parent <em>must</em> exit. In other words, the parent always exits when forking a proper daemon so that the daemon process is re-parented to <code>init</code>.</p> <p>So why the double fork? POSIX.1-2008 Sec. 11.2.3, "The Controlling Terminal", has the answer (emphasis added):</p> <blockquote> <p>The controlling terminal for a session is <strong>allocated by the session leader</strong> in an implementation-defined manner. If a session leader has no controlling terminal, and opens a terminal device file that is not already associated with a session without using the O_NOCTTY option (see open()), it is implementation-defined whether the terminal becomes the controlling terminal of the session leader. If a process which is <strong>not a session leader</strong> opens a terminal file, or the O_NOCTTY option is used on open(), <strong>then that terminal shall not become the controlling terminal of the calling process</strong>.</p> </blockquote> <p>This tells us that if a daemon process does something like this ...</p> <pre><code>int fd = open("/dev/console", O_RDWR); </code></pre> <p>... then the daemon process <em>might</em> acquire <code>/dev/console</code> as its controlling terminal, depending on whether the daemon process is a session leader, and depending on the system implementation. The program can <em>guarantee</em> that the above call will not acquire a controlling terminal if the program first ensures that it is not a session leader. </p> <p>Normally, when launching a daemon, <code>setsid</code> is called (from the child process after calling <code>fork</code>) to dissociate the daemon from its controlling terminal. However, calling <code>setsid</code> also means that the calling process will be the session leader of the new session, which leaves open the possibility that the daemon could reacquire a controlling terminal. The double-fork technique ensures that the daemon process is not the session leader, which then guarantees that a call to <code>open</code>, as in the example above, will not result in the daemon process reacquiring a controlling terminal.</p> <p>The double-fork technique is a bit paranoid. It may not be necessary if you <em>know</em> that the daemon will never open a terminal device file. Also, on some systems it may not be necessary even if the daemon does open a terminal device file, since that behavior is implementation-defined. However, one thing that is not implementation-defined is that only a session leader can allocate the controlling terminal. <strong>If a process isn't a session leader, it can't allocate a controlling terminal.</strong> Therefore, if you want to be paranoid and be certain that the daemon process cannot inadvertently acquire a controlling terminal, regardless of any implementation-defined specifics, then the double-fork technique is essential.</p>
65
2013-05-01T11:54:52Z
[ "python", "unix" ]
SQLAlchemy - Database hits on every request?
881,517
<p>I'm currently working with a web application written in Python (and using SQLAlchemy). In order to handle authentication, the app first checks for a user ID in the session, and providing it exists, pulls that whole user record out of the database and stores it for the rest of that request. Another query is also run to check the permissions of the user it has stored.</p> <p>I'm fairly new to the web application development world, but from my understanding, hitting the database for something like this on <em>every</em> request isn't efficient. Or is this considered a normal thing to do?</p> <p>The only thing I've thought of so far is pulling up this data once, and storing what's relevant (most of the data isn't even required on every request). However, this brings up the problem of what's supposed to happen if this user record happens to be removed in the interim. Any ideas on how best to manage this?</p>
0
2009-05-19T08:11:21Z
881,535
<p>It's a Database, so often it's fairly common to "hit" the Database to pull the required data. You can reduce single queries if you build up Joins or Stored Procedures.</p>
1
2009-05-19T08:17:02Z
[ "python", "sqlalchemy" ]
SQLAlchemy - Database hits on every request?
881,517
<p>I'm currently working with a web application written in Python (and using SQLAlchemy). In order to handle authentication, the app first checks for a user ID in the session, and providing it exists, pulls that whole user record out of the database and stores it for the rest of that request. Another query is also run to check the permissions of the user it has stored.</p> <p>I'm fairly new to the web application development world, but from my understanding, hitting the database for something like this on <em>every</em> request isn't efficient. Or is this considered a normal thing to do?</p> <p>The only thing I've thought of so far is pulling up this data once, and storing what's relevant (most of the data isn't even required on every request). However, this brings up the problem of what's supposed to happen if this user record happens to be removed in the interim. Any ideas on how best to manage this?</p>
0
2009-05-19T08:11:21Z
882,021
<p>"hitting the database for something like this on every request isn't efficient."</p> <p>False. And, you've assumed that there's no caching, which is also false.</p> <p>Most ORM layers are perfectly capable of caching rows, saving some DB queries.</p> <p>Most RDBMS's have extensive caching, resulting in remarkably fast responses to common queries.</p> <p>All ORM layers will use consistent SQL, further aiding the database in optimizing the repetitive operations. (Specifically, the SQL statement is cached, saving parsing and planning time.)</p> <p>" Or is this considered a normal thing to do?"</p> <p>True.</p> <p>Until you can prove that your queries are the slowest part of your application, don't worry. Build something that actually works. Then optimize the part that you can prove is the bottleneck.</p>
3
2009-05-19T10:44:05Z
[ "python", "sqlalchemy" ]
SQLAlchemy - Database hits on every request?
881,517
<p>I'm currently working with a web application written in Python (and using SQLAlchemy). In order to handle authentication, the app first checks for a user ID in the session, and providing it exists, pulls that whole user record out of the database and stores it for the rest of that request. Another query is also run to check the permissions of the user it has stored.</p> <p>I'm fairly new to the web application development world, but from my understanding, hitting the database for something like this on <em>every</em> request isn't efficient. Or is this considered a normal thing to do?</p> <p>The only thing I've thought of so far is pulling up this data once, and storing what's relevant (most of the data isn't even required on every request). However, this brings up the problem of what's supposed to happen if this user record happens to be removed in the interim. Any ideas on how best to manage this?</p>
0
2009-05-19T08:11:21Z
882,171
<p>You are basically talking about caching data as a performance optimization. As always, premature optimization is a bad idea. It's hard to know where the bottlenecks are beforehand, even more so if the application domain is new to you. Optimization adds complexity and if you optimize the wrong things, you not only have wasted the effort, but have made the necessary optimizations harder.</p> <p>Requesting user data usually is usually a pretty trivial query. You can build yourself a simple benchmark to see what kind of overhead it will introduce. If it isn't a significant percentage of your time-budget, just leave it be.</p> <p>If you still want to cache the data on the application server then you have to come up with a cache invalidation scheme.</p> <p>Possible schemes are to check for changes from the database. If you don't have a lot of data to cache, this really isn't significantly more efficient than just reloading it.</p> <p>Another option is to just time out cached data. This is a good option if instant visibility of changes isn't important.</p> <p>Another option is to actively invalidate caches on changes. This depends on whether you only modify the database through your application and if you have a single application server or a clustered solution.</p>
2
2009-05-19T11:25:43Z
[ "python", "sqlalchemy" ]
SQLAlchemy - Database hits on every request?
881,517
<p>I'm currently working with a web application written in Python (and using SQLAlchemy). In order to handle authentication, the app first checks for a user ID in the session, and providing it exists, pulls that whole user record out of the database and stores it for the rest of that request. Another query is also run to check the permissions of the user it has stored.</p> <p>I'm fairly new to the web application development world, but from my understanding, hitting the database for something like this on <em>every</em> request isn't efficient. Or is this considered a normal thing to do?</p> <p>The only thing I've thought of so far is pulling up this data once, and storing what's relevant (most of the data isn't even required on every request). However, this brings up the problem of what's supposed to happen if this user record happens to be removed in the interim. Any ideas on how best to manage this?</p>
0
2009-05-19T08:11:21Z
890,202
<p>For a user login and basic permission tokens in a <em>simple</em> web application I will definitely store that in a cookie-based session. It's true that a few SELECTs per request is not a big deal at all, but then again if you can get some/all of your web requests to execute from cached data with no DB hits at all, that just adds that much more scalability to an app which is planning on receiving a lot of load. </p> <p>The issue of the user token being changed on the database is handled in two ways. One is, ignore it - for a lot of use cases its not that big a deal for the user to log out and log back in again to get at new permissions that have been granted elsewhere (witness unix as an example). The other is that all mutations of the user row are filtered through a method that also resets the state within the cookie-based session, but this is only effective if the user him/herself is the one initiating the changes through the browser interface.</p> <p>If OTOH neither of the above use cases apply to you, then you probably need to stick with a little bit of database access built into every request.</p>
3
2009-05-20T20:53:57Z
[ "python", "sqlalchemy" ]
Auto-tab between fields on Django admin site
881,536
<p>I have an inline on a model with data with a fixed length, that has to be entered very fast, so I was thinking about a way of "tabbing" through fields automatically when the field is filled...</p> <p>Could that be possible?</p>
0
2009-05-19T08:17:10Z
881,692
<p>Sure it's possible, but it will need some javascript. You'd want to bind an event to the keypress event on each field, and when it fires test the length of the text entered so far - if it matches, move the focus onto the next field.</p>
1
2009-05-19T09:04:29Z
[ "python", "django", "django-admin", "field" ]
Auto-tab between fields on Django admin site
881,536
<p>I have an inline on a model with data with a fixed length, that has to be entered very fast, so I was thinking about a way of "tabbing" through fields automatically when the field is filled...</p> <p>Could that be possible?</p>
0
2009-05-19T08:17:10Z
1,283,042
<p>I can recommend the following links:</p> <ul> <li><a href="http://www.lousyllama.com/sandbox/jquery-autotab" rel="nofollow">JQuery AutoTab</a></li> </ul>
1
2009-08-15T22:41:02Z
[ "python", "django", "django-admin", "field" ]
In print statements, what determines whether python shell prints null character or waits for input
881,564
<p>Recently I was trying some practice programs in python and I came across this small problem.</p> <p>when I typed</p> <pre><code>print "" </code></pre> <p>in IDLE, the python shell printed a null character.</p> <p>If I typed </p> <pre><code>print """""" </code></pre> <p>in IDLE, the python shell printed a null character.</p> <p>but the python shell waits for input if I type</p> <pre><code>print """" </code></pre> <p>Why is this behaviour observed. As far as my knowledge goes, it should print null character for this <code>print """"</code> also.</p>
2
2009-05-19T08:24:55Z
881,576
<p>In python you can have strings enclosed with either 1 or 3 quotes.</p> <pre><code>print "a" print """a""" </code></pre> <p>In your case, the interpreter is waiting for the last triple quote.</p>
11
2009-05-19T08:26:58Z
[ "python" ]
In print statements, what determines whether python shell prints null character or waits for input
881,564
<p>Recently I was trying some practice programs in python and I came across this small problem.</p> <p>when I typed</p> <pre><code>print "" </code></pre> <p>in IDLE, the python shell printed a null character.</p> <p>If I typed </p> <pre><code>print """""" </code></pre> <p>in IDLE, the python shell printed a null character.</p> <p>but the python shell waits for input if I type</p> <pre><code>print """" </code></pre> <p>Why is this behaviour observed. As far as my knowledge goes, it should print null character for this <code>print """"</code> also.</p>
2
2009-05-19T08:24:55Z
881,591
<p>I suspect you mean that python printed an empty line -- this is not the same as a null character.</p> <p>When you <code>print """"""</code>, python finds an empty, triple-quoted string.</p> <p>When you <code>print """"</code>, python finds the start of a triple-quoted string, and waits for you to input the rest (ending with <code>"""</code>).</p> <p>A triple-qouted string can include other qoutes, linebreaks, etc.</p>
4
2009-05-19T08:30:52Z
[ "python" ]
Python imports: importing a module without .py extension?
881,639
<p>In a Python system for which I develop, we usually have this module structure.</p> <pre><code>mymodule/ mymodule/mymodule/feature.py mymodule/test/feature.py </code></pre> <p>This allows our little testing framework to easily import test/feature.py and run unit tests. However, we now have the need for some shell scripts (which are written in Python):</p> <pre><code>mymodule/ mymodule/scripts/yetanotherfeature.py mymodule/test/yetanotherfeature.py </code></pre> <p>yetanotherfeature.py is installed by the module Debian package into /usr/bin. But we obviously don't want the .py extension there. So, in order for the test framework to still be able to import the module I have to do this symbolic link thingie:</p> <pre><code>mymodule/ mymodule/scripts/yetanotherfeature mymodule/scripts/yetanotherfeature.py @ -&gt; mymodule/scripts/yetanotherfeature mymodule/test/yetanotherfeature.py </code></pre> <p>Is it possible to import a module by filename in Python, or can you think of a more elegant solution for this?</p>
3
2009-05-19T08:50:15Z
881,647
<p>Check out imp module:</p> <p><a href="http://docs.python.org/library/imp.html" rel="nofollow">http://docs.python.org/library/imp.html</a></p> <p>This will allow you to load a module by filename. But I think your symbolic link is a more elegant solution.</p>
1
2009-05-19T08:53:46Z
[ "python", "debian" ]
Python imports: importing a module without .py extension?
881,639
<p>In a Python system for which I develop, we usually have this module structure.</p> <pre><code>mymodule/ mymodule/mymodule/feature.py mymodule/test/feature.py </code></pre> <p>This allows our little testing framework to easily import test/feature.py and run unit tests. However, we now have the need for some shell scripts (which are written in Python):</p> <pre><code>mymodule/ mymodule/scripts/yetanotherfeature.py mymodule/test/yetanotherfeature.py </code></pre> <p>yetanotherfeature.py is installed by the module Debian package into /usr/bin. But we obviously don't want the .py extension there. So, in order for the test framework to still be able to import the module I have to do this symbolic link thingie:</p> <pre><code>mymodule/ mymodule/scripts/yetanotherfeature mymodule/scripts/yetanotherfeature.py @ -&gt; mymodule/scripts/yetanotherfeature mymodule/test/yetanotherfeature.py </code></pre> <p>Is it possible to import a module by filename in Python, or can you think of a more elegant solution for this?</p>
3
2009-05-19T08:50:15Z
881,658
<p>The <a href="http://docs.python.org/library/imp.html">imp module</a> is used for this: </p> <pre><code>daniel@purplehaze:/tmp/test$ cat mymodule print "woho!" daniel@purplehaze:/tmp/test$ cat test.py import imp imp.load_source("apanapansson", "mymodule") daniel@purplehaze:/tmp/test$ python test.py woho! daniel@purplehaze:/tmp/test$ </code></pre>
8
2009-05-19T08:55:32Z
[ "python", "debian" ]
Python imports: importing a module without .py extension?
881,639
<p>In a Python system for which I develop, we usually have this module structure.</p> <pre><code>mymodule/ mymodule/mymodule/feature.py mymodule/test/feature.py </code></pre> <p>This allows our little testing framework to easily import test/feature.py and run unit tests. However, we now have the need for some shell scripts (which are written in Python):</p> <pre><code>mymodule/ mymodule/scripts/yetanotherfeature.py mymodule/test/yetanotherfeature.py </code></pre> <p>yetanotherfeature.py is installed by the module Debian package into /usr/bin. But we obviously don't want the .py extension there. So, in order for the test framework to still be able to import the module I have to do this symbolic link thingie:</p> <pre><code>mymodule/ mymodule/scripts/yetanotherfeature mymodule/scripts/yetanotherfeature.py @ -&gt; mymodule/scripts/yetanotherfeature mymodule/test/yetanotherfeature.py </code></pre> <p>Is it possible to import a module by filename in Python, or can you think of a more elegant solution for this?</p>
3
2009-05-19T08:50:15Z
881,669
<p>You could most likely use some tricker by using import <a href="http://www.python.org/dev/peps/pep-0302/" rel="nofollow">hooks</a>, I wouldn't recommend it though. On the other hand I would also probably do it the other way around , have your .py scripts somewhere, and make '.py'less symbolic links to the .py files. So your library could be anywhere and you can run the test from within by importing it normall (since it has the py extension), and then /usr/bin/yetanotherfeature points to it, so you can run it without the py.</p> <p>Edit: Nevermind this (at least the hooks part), the import imp solution looks very good to me :)</p>
1
2009-05-19T08:59:37Z
[ "python", "debian" ]
Python imports: importing a module without .py extension?
881,639
<p>In a Python system for which I develop, we usually have this module structure.</p> <pre><code>mymodule/ mymodule/mymodule/feature.py mymodule/test/feature.py </code></pre> <p>This allows our little testing framework to easily import test/feature.py and run unit tests. However, we now have the need for some shell scripts (which are written in Python):</p> <pre><code>mymodule/ mymodule/scripts/yetanotherfeature.py mymodule/test/yetanotherfeature.py </code></pre> <p>yetanotherfeature.py is installed by the module Debian package into /usr/bin. But we obviously don't want the .py extension there. So, in order for the test framework to still be able to import the module I have to do this symbolic link thingie:</p> <pre><code>mymodule/ mymodule/scripts/yetanotherfeature mymodule/scripts/yetanotherfeature.py @ -&gt; mymodule/scripts/yetanotherfeature mymodule/test/yetanotherfeature.py </code></pre> <p>Is it possible to import a module by filename in Python, or can you think of a more elegant solution for this?</p>
3
2009-05-19T08:50:15Z
24,603,569
<p>Another option would be to use setuptools:</p> <blockquote> <p>"...there’s no easy way to have a script’s filename match local conventions on both Windows and POSIX platforms. For another, you often have to create a separate file just for the “main” script, when your actual “main” is a function in a module somewhere... setuptools fixes all of these problems by automatically generating scripts for you with the correct extension, and on Windows it will even create an .exe file..."</p> </blockquote> <p><a href="https://pythonhosted.org/setuptools/setuptools.html#automatic-script-creation" rel="nofollow">https://pythonhosted.org/setuptools/setuptools.html#automatic-script-creation</a></p>
0
2014-07-07T05:30:10Z
[ "python", "debian" ]
How to tell if a class is descended from another class
881,676
<p>I have a function that accepts a class (not an instance) and, depending on whether or not it's a specific class <em>or a subclass of that</em>, I need to pass it in to one of two other (third-party) factory functions.</p> <p>(To forestall any objections, I'm aware this is not very Pythonic, but I'm dependent on what the third-party library accepts.)</p> <p><code>issubclass</code> only works for instances, not class objects themselves. I suppose I could instantiate the class, do <code>issubclass</code> and throw away the instance, but that seems a bit wasteful.</p> <p>Here's what I'm doing at the moment, relying on the built-in <strong>mro</strong> attribute to tell if a certain class is in the list of ancestors of my class. Is this safe, and is there any better way of doing it?</p> <pre><code>if GenericClass in myclass.__mro__: result = generic_factory(myclass) else: result = other_factory(myclass) </code></pre>
11
2009-05-19T09:00:23Z
881,689
<blockquote> <p>issubclass only works for instances, not class objects themselves.</p> </blockquote> <p>It works fine for me:</p> <pre><code>&gt;&gt;&gt; class test(object):pass ... &gt;&gt;&gt; issubclass(test,object) True </code></pre>
27
2009-05-19T09:03:33Z
[ "python" ]
How to use dynamic foreignkey in Django?
881,792
<p>I want to connect a single <code>ForeignKey</code> to two different models.</p> <p>For example:</p> <p>I have two models named <code>Casts</code> and <code>Articles</code>, and a third model, <code>Faves</code>, for favoriting either of the other models. How can I make the <code>ForeignKey</code> dynamic?</p> <pre><code>class Articles(models.Model): title = models.CharField(max_length=100) body = models.TextField() class Casts(models.Model): title = models.CharField(max_length=100) body = models.TextField() class Faves(models.Model): post = models.ForeignKey(**---CASTS-OR-ARTICLES---**) user = models.ForeignKey(User,unique=True) </code></pre> <p>Is this possible?</p>
22
2009-05-19T09:27:30Z
881,874
<p>Here is how I do it:</p> <pre><code>from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import fields class Photo(models.Model): picture = models.ImageField(null=True, upload_to='./images/') caption = models.CharField(_("Optional caption"),max_length=100,null=True, blank=True) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = fields.GenericForeignKey('content_type', 'object_id') class Article(models.Model): .... images = fields.GenericRelation(Photo) </code></pre> <p>You would add something like </p> <pre><code> content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = fields.GenericForeignKey('content_type', 'object_id') </code></pre> <p>to Faves and </p> <pre><code> fields.GenericRelation(Faves) </code></pre> <p>to Article and Cast</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/" rel="nofollow">contenttypes docs</a></p>
33
2009-05-19T09:59:09Z
[ "python", "django", "foreign-keys" ]
How to use dynamic foreignkey in Django?
881,792
<p>I want to connect a single <code>ForeignKey</code> to two different models.</p> <p>For example:</p> <p>I have two models named <code>Casts</code> and <code>Articles</code>, and a third model, <code>Faves</code>, for favoriting either of the other models. How can I make the <code>ForeignKey</code> dynamic?</p> <pre><code>class Articles(models.Model): title = models.CharField(max_length=100) body = models.TextField() class Casts(models.Model): title = models.CharField(max_length=100) body = models.TextField() class Faves(models.Model): post = models.ForeignKey(**---CASTS-OR-ARTICLES---**) user = models.ForeignKey(User,unique=True) </code></pre> <p>Is this possible?</p>
22
2009-05-19T09:27:30Z
881,912
<p>Here's an approach. (Note that the models are singular, Django automatically pluralizes for you.)</p> <pre><code>class Article(models.Model): title = models.CharField(max_length=100) body = models.TextField() class Cast(models.Model): title = models.CharField(max_length=100) body = models.TextField() FAVE_CHOICES = ( ('A','Article'), ('C','Cast'), ) class Fave(models.Model): type_of_fave = models.CharField( max_length=1, choices=FAVE_CHOICES ) cast = models.ForeignKey(Casts,null=True) article= models.ForeigKey(Articles,null=True) user = models.ForeignKey(User,unique=True) </code></pre> <p>This rarely presents profound problems. It may require some clever class methods, depending on your use cases.</p>
12
2009-05-19T10:11:44Z
[ "python", "django", "foreign-keys" ]
Rendering JSON objects using a Django template after an Ajax call
882,215
<p>I've been trying to understand what's the optimal way to do <a href="http://en.wikipedia.org/wiki/Ajax%5F%28programming%29">Ajax</a> in <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. By reading stuff here and there I gathered that the common process is: </p> <ol> <li><p>formulate your Ajax call using some <a href="http://en.wikipedia.org/wiki/JavaScript">JavaScript</a> library (e.g., <a href="http://en.wikipedia.org/wiki/JQuery">jQuery</a>), set up a URL pattern in Django that catches the call and passes it to a view function</p></li> <li><p>in the <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> view function retrieve the objects you are interested in and send them back to the client in JSON format or similar (by using the built in serializer module, or <a href="http://code.google.com/p/simplejson/">simplejson</a>)</p></li> <li><p>define a callback function in JavaScript that receives the JSON data and parses them, so to create whatever HTML is needed to be displayed. Finally, the JavaScript script puts the HTML wherever it should stay.</p></li> </ol> <p>Now, what I still don't get is <em>how are Django templates related to all of this?</em> Apparently, we're not making use of the power of templates at all. Ideally, I thought it'd be nice to pass back a JSON object and a template name, so that the data could be iterated over and an HTML block is created. But maybe I'm totally wrong here...</p> <p>The only resource I found that goes in this direction is <a href="http://www.djangosnippets.org/snippets/769/">this snippet (769)</a> but I haven't tried it yet. Obviously, what's going to happen in this case is that all the resulting HTML is created on the server side, then passed to the client. The JavaScript-callback function only has to display it in the right place.</p> <p>Does this cause performance problems? If not, even without using the snippet above, why not formatting the HTML directly in the backend using Python instead of the front-end?</p> <p>Many thanks! </p> <p><strong>UPDATE: please use <a href="http://www.djangosnippets.org/snippets/942/">snippet 942</a> because it is an enhanced version of the one above!</strong> I found that the inheritance support works much better this way..</p>
58
2009-05-19T11:36:21Z
882,245
<p>When you are doing Ajax I don't think you have any use for templates. Template is there so that you can generate dynamic HTML on the server side easily and hence it provides few programming hooks inside HTML.</p> <p>In case of Ajax you are passing JSON data and you can format it as you want in Python. and HTML/document elements will be generated on client side using the JSON by some JavaScript library e.g. jQuery on client side.</p> <p>Maybe if you have a very specific case of replacing some inner HTML from server side HTML then maybe you can use templates but in that case why you would need JSON? You can just query the HTML page via Ajax and change inner or outer or whatever HTML.</p>
6
2009-05-19T11:43:22Z
[ "python", "ajax", "django", "json", "templates" ]
Rendering JSON objects using a Django template after an Ajax call
882,215
<p>I've been trying to understand what's the optimal way to do <a href="http://en.wikipedia.org/wiki/Ajax%5F%28programming%29">Ajax</a> in <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. By reading stuff here and there I gathered that the common process is: </p> <ol> <li><p>formulate your Ajax call using some <a href="http://en.wikipedia.org/wiki/JavaScript">JavaScript</a> library (e.g., <a href="http://en.wikipedia.org/wiki/JQuery">jQuery</a>), set up a URL pattern in Django that catches the call and passes it to a view function</p></li> <li><p>in the <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> view function retrieve the objects you are interested in and send them back to the client in JSON format or similar (by using the built in serializer module, or <a href="http://code.google.com/p/simplejson/">simplejson</a>)</p></li> <li><p>define a callback function in JavaScript that receives the JSON data and parses them, so to create whatever HTML is needed to be displayed. Finally, the JavaScript script puts the HTML wherever it should stay.</p></li> </ol> <p>Now, what I still don't get is <em>how are Django templates related to all of this?</em> Apparently, we're not making use of the power of templates at all. Ideally, I thought it'd be nice to pass back a JSON object and a template name, so that the data could be iterated over and an HTML block is created. But maybe I'm totally wrong here...</p> <p>The only resource I found that goes in this direction is <a href="http://www.djangosnippets.org/snippets/769/">this snippet (769)</a> but I haven't tried it yet. Obviously, what's going to happen in this case is that all the resulting HTML is created on the server side, then passed to the client. The JavaScript-callback function only has to display it in the right place.</p> <p>Does this cause performance problems? If not, even without using the snippet above, why not formatting the HTML directly in the backend using Python instead of the front-end?</p> <p>Many thanks! </p> <p><strong>UPDATE: please use <a href="http://www.djangosnippets.org/snippets/942/">snippet 942</a> because it is an enhanced version of the one above!</strong> I found that the inheritance support works much better this way..</p>
58
2009-05-19T11:36:21Z
882,254
<p>Templates are for the purpose of <em>presentation</em>. Responding with data in format X (JSON, <a href="http://en.wikipedia.org/wiki/JSON#JSONP" rel="nofollow">JSONP</a>, XML, <a href="http://en.wikipedia.org/wiki/YAML" rel="nofollow">YAML</a>, *ml, etc.) is not presentation, so you don't need templates. Just serialize your data into format X and return it in an HttpResponse.</p>
3
2009-05-19T11:47:12Z
[ "python", "ajax", "django", "json", "templates" ]
Rendering JSON objects using a Django template after an Ajax call
882,215
<p>I've been trying to understand what's the optimal way to do <a href="http://en.wikipedia.org/wiki/Ajax%5F%28programming%29">Ajax</a> in <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. By reading stuff here and there I gathered that the common process is: </p> <ol> <li><p>formulate your Ajax call using some <a href="http://en.wikipedia.org/wiki/JavaScript">JavaScript</a> library (e.g., <a href="http://en.wikipedia.org/wiki/JQuery">jQuery</a>), set up a URL pattern in Django that catches the call and passes it to a view function</p></li> <li><p>in the <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> view function retrieve the objects you are interested in and send them back to the client in JSON format or similar (by using the built in serializer module, or <a href="http://code.google.com/p/simplejson/">simplejson</a>)</p></li> <li><p>define a callback function in JavaScript that receives the JSON data and parses them, so to create whatever HTML is needed to be displayed. Finally, the JavaScript script puts the HTML wherever it should stay.</p></li> </ol> <p>Now, what I still don't get is <em>how are Django templates related to all of this?</em> Apparently, we're not making use of the power of templates at all. Ideally, I thought it'd be nice to pass back a JSON object and a template name, so that the data could be iterated over and an HTML block is created. But maybe I'm totally wrong here...</p> <p>The only resource I found that goes in this direction is <a href="http://www.djangosnippets.org/snippets/769/">this snippet (769)</a> but I haven't tried it yet. Obviously, what's going to happen in this case is that all the resulting HTML is created on the server side, then passed to the client. The JavaScript-callback function only has to display it in the right place.</p> <p>Does this cause performance problems? If not, even without using the snippet above, why not formatting the HTML directly in the backend using Python instead of the front-end?</p> <p>Many thanks! </p> <p><strong>UPDATE: please use <a href="http://www.djangosnippets.org/snippets/942/">snippet 942</a> because it is an enhanced version of the one above!</strong> I found that the inheritance support works much better this way..</p>
58
2009-05-19T11:36:21Z
882,648
<p>There's no reason you can't return a rendered bit of HTML using Ajax, and insert that into the existing page at the point you want. Obviously you can use Django's templates to render this HTML, if you want.</p>
8
2009-05-19T13:06:40Z
[ "python", "ajax", "django", "json", "templates" ]
Rendering JSON objects using a Django template after an Ajax call
882,215
<p>I've been trying to understand what's the optimal way to do <a href="http://en.wikipedia.org/wiki/Ajax%5F%28programming%29">Ajax</a> in <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. By reading stuff here and there I gathered that the common process is: </p> <ol> <li><p>formulate your Ajax call using some <a href="http://en.wikipedia.org/wiki/JavaScript">JavaScript</a> library (e.g., <a href="http://en.wikipedia.org/wiki/JQuery">jQuery</a>), set up a URL pattern in Django that catches the call and passes it to a view function</p></li> <li><p>in the <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> view function retrieve the objects you are interested in and send them back to the client in JSON format or similar (by using the built in serializer module, or <a href="http://code.google.com/p/simplejson/">simplejson</a>)</p></li> <li><p>define a callback function in JavaScript that receives the JSON data and parses them, so to create whatever HTML is needed to be displayed. Finally, the JavaScript script puts the HTML wherever it should stay.</p></li> </ol> <p>Now, what I still don't get is <em>how are Django templates related to all of this?</em> Apparently, we're not making use of the power of templates at all. Ideally, I thought it'd be nice to pass back a JSON object and a template name, so that the data could be iterated over and an HTML block is created. But maybe I'm totally wrong here...</p> <p>The only resource I found that goes in this direction is <a href="http://www.djangosnippets.org/snippets/769/">this snippet (769)</a> but I haven't tried it yet. Obviously, what's going to happen in this case is that all the resulting HTML is created on the server side, then passed to the client. The JavaScript-callback function only has to display it in the right place.</p> <p>Does this cause performance problems? If not, even without using the snippet above, why not formatting the HTML directly in the backend using Python instead of the front-end?</p> <p>Many thanks! </p> <p><strong>UPDATE: please use <a href="http://www.djangosnippets.org/snippets/942/">snippet 942</a> because it is an enhanced version of the one above!</strong> I found that the inheritance support works much better this way..</p>
58
2009-05-19T11:36:21Z
883,743
<p>Here is how I use the same template for traditional rendering and Ajax-response rendering.</p> <p>Template:</p> <pre><code>&lt;div id="sortable"&gt; {% include "admin/app/model/subtemplate.html" %} &lt;/div&gt; </code></pre> <p>Included template (aka: subtemplate):</p> <pre><code>&lt;div id="results_listing"&gt; {% if results %} {% for c in results %} ..... {% endfor %} {% else %} </code></pre> <p>The Ajax-view:</p> <pre><code>@login_required @render_to('admin/app/model/subtemplate.html')#annoying-decorator def ajax_view(request): ..... return { "results":Model.objects.all(), } </code></pre> <p>Of course you can use render_to_response. But I like those annoying decorators :D</p>
13
2009-05-19T16:19:13Z
[ "python", "ajax", "django", "json", "templates" ]
Rendering JSON objects using a Django template after an Ajax call
882,215
<p>I've been trying to understand what's the optimal way to do <a href="http://en.wikipedia.org/wiki/Ajax%5F%28programming%29">Ajax</a> in <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. By reading stuff here and there I gathered that the common process is: </p> <ol> <li><p>formulate your Ajax call using some <a href="http://en.wikipedia.org/wiki/JavaScript">JavaScript</a> library (e.g., <a href="http://en.wikipedia.org/wiki/JQuery">jQuery</a>), set up a URL pattern in Django that catches the call and passes it to a view function</p></li> <li><p>in the <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> view function retrieve the objects you are interested in and send them back to the client in JSON format or similar (by using the built in serializer module, or <a href="http://code.google.com/p/simplejson/">simplejson</a>)</p></li> <li><p>define a callback function in JavaScript that receives the JSON data and parses them, so to create whatever HTML is needed to be displayed. Finally, the JavaScript script puts the HTML wherever it should stay.</p></li> </ol> <p>Now, what I still don't get is <em>how are Django templates related to all of this?</em> Apparently, we're not making use of the power of templates at all. Ideally, I thought it'd be nice to pass back a JSON object and a template name, so that the data could be iterated over and an HTML block is created. But maybe I'm totally wrong here...</p> <p>The only resource I found that goes in this direction is <a href="http://www.djangosnippets.org/snippets/769/">this snippet (769)</a> but I haven't tried it yet. Obviously, what's going to happen in this case is that all the resulting HTML is created on the server side, then passed to the client. The JavaScript-callback function only has to display it in the right place.</p> <p>Does this cause performance problems? If not, even without using the snippet above, why not formatting the HTML directly in the backend using Python instead of the front-end?</p> <p>Many thanks! </p> <p><strong>UPDATE: please use <a href="http://www.djangosnippets.org/snippets/942/">snippet 942</a> because it is an enhanced version of the one above!</strong> I found that the inheritance support works much better this way..</p>
58
2009-05-19T11:36:21Z
884,339
<p>Hey thanks vikingosegundo! </p> <p>I like using decorators too :-). But in the meanwhile I've been following the approach suggested by the snippet I was mentioning above. Only thing, use instead <a href="http://www.djangosnippets.org/snippets/942/">the snippet n. 942</a> cause it's an improved version of the original one. Here's how it works:</p> <p>Imagine you have a template (e.g., 'subtemplate.html') of whatever size that contains a useful block you can reuse:</p> <pre><code> ........ &lt;div id="results"&gt; {% block results %} {% for el in items %} &lt;li&gt;{{el|capfirst}}&lt;/li&gt; {% endfor %} {% endblock %} &lt;/div&gt;&lt;br /&gt; ........ </code></pre> <p>By importing in your view file the snippet above you can easily reference to any block in your templates. A cool feature is that the inheritance relations among templates are taken into consideration, so if you reference to a block that includes another block and so on, everything should work just fine. So, the ajax-view looks like this: </p> <pre><code>from django.template import loader # downloaded from djangosnippets.com[942] from my_project.snippets.template import render_block_to_string def ajax_view(request): # some random context context = Context({'items': range(100)}) # passing the template_name + block_name + context return_str = render_block_to_string('standard/subtemplate.html', 'results', context) return HttpResponse(return_str) </code></pre>
24
2009-05-19T18:29:24Z
[ "python", "ajax", "django", "json", "templates" ]
Rendering JSON objects using a Django template after an Ajax call
882,215
<p>I've been trying to understand what's the optimal way to do <a href="http://en.wikipedia.org/wiki/Ajax%5F%28programming%29">Ajax</a> in <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. By reading stuff here and there I gathered that the common process is: </p> <ol> <li><p>formulate your Ajax call using some <a href="http://en.wikipedia.org/wiki/JavaScript">JavaScript</a> library (e.g., <a href="http://en.wikipedia.org/wiki/JQuery">jQuery</a>), set up a URL pattern in Django that catches the call and passes it to a view function</p></li> <li><p>in the <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> view function retrieve the objects you are interested in and send them back to the client in JSON format or similar (by using the built in serializer module, or <a href="http://code.google.com/p/simplejson/">simplejson</a>)</p></li> <li><p>define a callback function in JavaScript that receives the JSON data and parses them, so to create whatever HTML is needed to be displayed. Finally, the JavaScript script puts the HTML wherever it should stay.</p></li> </ol> <p>Now, what I still don't get is <em>how are Django templates related to all of this?</em> Apparently, we're not making use of the power of templates at all. Ideally, I thought it'd be nice to pass back a JSON object and a template name, so that the data could be iterated over and an HTML block is created. But maybe I'm totally wrong here...</p> <p>The only resource I found that goes in this direction is <a href="http://www.djangosnippets.org/snippets/769/">this snippet (769)</a> but I haven't tried it yet. Obviously, what's going to happen in this case is that all the resulting HTML is created on the server side, then passed to the client. The JavaScript-callback function only has to display it in the right place.</p> <p>Does this cause performance problems? If not, even without using the snippet above, why not formatting the HTML directly in the backend using Python instead of the front-end?</p> <p>Many thanks! </p> <p><strong>UPDATE: please use <a href="http://www.djangosnippets.org/snippets/942/">snippet 942</a> because it is an enhanced version of the one above!</strong> I found that the inheritance support works much better this way..</p>
58
2009-05-19T11:36:21Z
3,067,558
<p>Unfortunately, Django templates are designed to be executed server side only. There is <a href="http://ajaxian.com/archives/django-template-language-in-javascript" rel="nofollow">at least one project to render</a> Django templates using Javascript, but I haven't used it and so I don't know how fast, well supported or up to date it is. Other than this, you have to either use the Django templates on the server or generate dynamic elements on the client without using templates.</p>
0
2010-06-18T06:15:13Z
[ "python", "ajax", "django", "json", "templates" ]
Rendering JSON objects using a Django template after an Ajax call
882,215
<p>I've been trying to understand what's the optimal way to do <a href="http://en.wikipedia.org/wiki/Ajax%5F%28programming%29">Ajax</a> in <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. By reading stuff here and there I gathered that the common process is: </p> <ol> <li><p>formulate your Ajax call using some <a href="http://en.wikipedia.org/wiki/JavaScript">JavaScript</a> library (e.g., <a href="http://en.wikipedia.org/wiki/JQuery">jQuery</a>), set up a URL pattern in Django that catches the call and passes it to a view function</p></li> <li><p>in the <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> view function retrieve the objects you are interested in and send them back to the client in JSON format or similar (by using the built in serializer module, or <a href="http://code.google.com/p/simplejson/">simplejson</a>)</p></li> <li><p>define a callback function in JavaScript that receives the JSON data and parses them, so to create whatever HTML is needed to be displayed. Finally, the JavaScript script puts the HTML wherever it should stay.</p></li> </ol> <p>Now, what I still don't get is <em>how are Django templates related to all of this?</em> Apparently, we're not making use of the power of templates at all. Ideally, I thought it'd be nice to pass back a JSON object and a template name, so that the data could be iterated over and an HTML block is created. But maybe I'm totally wrong here...</p> <p>The only resource I found that goes in this direction is <a href="http://www.djangosnippets.org/snippets/769/">this snippet (769)</a> but I haven't tried it yet. Obviously, what's going to happen in this case is that all the resulting HTML is created on the server side, then passed to the client. The JavaScript-callback function only has to display it in the right place.</p> <p>Does this cause performance problems? If not, even without using the snippet above, why not formatting the HTML directly in the backend using Python instead of the front-end?</p> <p>Many thanks! </p> <p><strong>UPDATE: please use <a href="http://www.djangosnippets.org/snippets/942/">snippet 942</a> because it is an enhanced version of the one above!</strong> I found that the inheritance support works much better this way..</p>
58
2009-05-19T11:36:21Z
3,674,621
<p>While templates are indeed just for presentation purposes, it shouldn't matter if you are doing it on the serverside or client side. It all comes down to separating the control logic that is performing an action, from the view logic that is just responsible for creating the markup. If your javascript control logic is having to handle how you are rendering or displaying the HTML, then you might be doing it wrong, but if you isolate that rendering logic to another object or function, and just passing it the data necessary for the render, then you should be fine; it mirrors how we separate our controllers, models and views on the server side. </p> <p>Take a look at the github project: <a href="http://github.com/comolongo/Yz-Javascript-Django-Template-Compiler" rel="nofollow">http://github.com/comolongo/Yz-Javascript-Django-Template-Compiler</a></p> <p>It compiles django templates into optimized javascript functions that will generate your presentation html with data that you pass it. The compiled functions are in pure javascript, so there are no dependencies on other libraries. Since the templates are compiled instead of being parsed at runtime, the strings and variables are all already placed into javascript strings that just need to be concatenated, so you get a <em>huge</em> speed increase compared to techniques that require you to do dom manipulation or script parsing to get the final presentation. Right now only the basic tags and filters are there, but should be enough for most things, and more tags will be added as people start making requests for them or start contributing to the project. </p>
3
2010-09-09T07:36:48Z
[ "python", "ajax", "django", "json", "templates" ]
Rendering JSON objects using a Django template after an Ajax call
882,215
<p>I've been trying to understand what's the optimal way to do <a href="http://en.wikipedia.org/wiki/Ajax%5F%28programming%29">Ajax</a> in <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29">Django</a>. By reading stuff here and there I gathered that the common process is: </p> <ol> <li><p>formulate your Ajax call using some <a href="http://en.wikipedia.org/wiki/JavaScript">JavaScript</a> library (e.g., <a href="http://en.wikipedia.org/wiki/JQuery">jQuery</a>), set up a URL pattern in Django that catches the call and passes it to a view function</p></li> <li><p>in the <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a> view function retrieve the objects you are interested in and send them back to the client in JSON format or similar (by using the built in serializer module, or <a href="http://code.google.com/p/simplejson/">simplejson</a>)</p></li> <li><p>define a callback function in JavaScript that receives the JSON data and parses them, so to create whatever HTML is needed to be displayed. Finally, the JavaScript script puts the HTML wherever it should stay.</p></li> </ol> <p>Now, what I still don't get is <em>how are Django templates related to all of this?</em> Apparently, we're not making use of the power of templates at all. Ideally, I thought it'd be nice to pass back a JSON object and a template name, so that the data could be iterated over and an HTML block is created. But maybe I'm totally wrong here...</p> <p>The only resource I found that goes in this direction is <a href="http://www.djangosnippets.org/snippets/769/">this snippet (769)</a> but I haven't tried it yet. Obviously, what's going to happen in this case is that all the resulting HTML is created on the server side, then passed to the client. The JavaScript-callback function only has to display it in the right place.</p> <p>Does this cause performance problems? If not, even without using the snippet above, why not formatting the HTML directly in the backend using Python instead of the front-end?</p> <p>Many thanks! </p> <p><strong>UPDATE: please use <a href="http://www.djangosnippets.org/snippets/942/">snippet 942</a> because it is an enhanced version of the one above!</strong> I found that the inheritance support works much better this way..</p>
58
2009-05-19T11:36:21Z
5,176,014
<p>you can use jquery.load() or similar to good effect, generating the html on the server and loading it into the dom with js. I think someone has called this AJAH.</p>
1
2011-03-03T02:30:34Z
[ "python", "ajax", "django", "json", "templates" ]
How to hide "cgi-bin", ".py", etc from my URLs?
882,430
<p>Brand new to web design, using python. Got Apache up and running, test python script working in cgi-bin directory. Get valid results when I type in the URL explicitly: ".../cgi-bin/showenv.py"</p> <p>But I don't want the URL to look that way. Here at stackoverflow, for example, the URLs that display in my address bar never have the messy details showing the script that was used to run them. They're clean of cgi-bin, .py, etc. extensions. How do I do that?</p> <p>EDIT: Thanks for responses, every single one helpful, lots to learn. I'm going with URL Rewriting for now; example in the docs looks extremely close to what I actually want to do. But I'm committed to python, so will have to look at WSGI down the road.</p>
11
2009-05-19T12:24:38Z
882,439
<p>I think you can do this by rewriting URL through Apache configuration. You can see the Apache documentation for rewriting <a href="http://httpd.apache.org/docs/2.0/misc/rewriteguide.html">here</a>.</p>
5
2009-05-19T12:27:48Z
[ "python", "cgi" ]
How to hide "cgi-bin", ".py", etc from my URLs?
882,430
<p>Brand new to web design, using python. Got Apache up and running, test python script working in cgi-bin directory. Get valid results when I type in the URL explicitly: ".../cgi-bin/showenv.py"</p> <p>But I don't want the URL to look that way. Here at stackoverflow, for example, the URLs that display in my address bar never have the messy details showing the script that was used to run them. They're clean of cgi-bin, .py, etc. extensions. How do I do that?</p> <p>EDIT: Thanks for responses, every single one helpful, lots to learn. I'm going with URL Rewriting for now; example in the docs looks extremely close to what I actually want to do. But I'm committed to python, so will have to look at WSGI down the road.</p>
11
2009-05-19T12:24:38Z
882,442
<p>You have to use URL Rewriting.</p> <p>It is not a noob question, it can be quite tricky :)</p> <p><a href="http://httpd.apache.org/docs/2.0/misc/rewriteguide.html" rel="nofollow">http://httpd.apache.org/docs/2.0/misc/rewriteguide.html</a></p> <p>Hope you find it helpful</p>
4
2009-05-19T12:28:22Z
[ "python", "cgi" ]
How to hide "cgi-bin", ".py", etc from my URLs?
882,430
<p>Brand new to web design, using python. Got Apache up and running, test python script working in cgi-bin directory. Get valid results when I type in the URL explicitly: ".../cgi-bin/showenv.py"</p> <p>But I don't want the URL to look that way. Here at stackoverflow, for example, the URLs that display in my address bar never have the messy details showing the script that was used to run them. They're clean of cgi-bin, .py, etc. extensions. How do I do that?</p> <p>EDIT: Thanks for responses, every single one helpful, lots to learn. I'm going with URL Rewriting for now; example in the docs looks extremely close to what I actually want to do. But I'm committed to python, so will have to look at WSGI down the road.</p>
11
2009-05-19T12:24:38Z
882,444
<p>Just use some good web framework e.g. django and you can have such URLs more than URLs you will have a better infrastructure, templates, db orm etc</p>
4
2009-05-19T12:28:23Z
[ "python", "cgi" ]
How to hide "cgi-bin", ".py", etc from my URLs?
882,430
<p>Brand new to web design, using python. Got Apache up and running, test python script working in cgi-bin directory. Get valid results when I type in the URL explicitly: ".../cgi-bin/showenv.py"</p> <p>But I don't want the URL to look that way. Here at stackoverflow, for example, the URLs that display in my address bar never have the messy details showing the script that was used to run them. They're clean of cgi-bin, .py, etc. extensions. How do I do that?</p> <p>EDIT: Thanks for responses, every single one helpful, lots to learn. I'm going with URL Rewriting for now; example in the docs looks extremely close to what I actually want to do. But I'm committed to python, so will have to look at WSGI down the road.</p>
11
2009-05-19T12:24:38Z
882,510
<p>this is an excerpt from a .htaccess that I use to achieve such a thing, this for example redirects all requests that were not to index.php to that file, of course you then have to check the server-variables within the file you redirect to to see, what was requested.</p> <p>Or you simply make a rewrite rule, where you use a RegExp like <code>^.*\/cgi-bin\/.*\.py$</code> to determine when and what to rewrite. Such a RegExp must be crafted very carefully, so that rewriting only takes place when desired.</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On #activate rewriting RewriteBase / #url base for rewriting RewriteCond %{REQUEST_FILENAME} !index.php #requested file is not index.php RewriteCond %{REQUEST_FILENAME} !^.*\.gif$ #requested file is no .gif RewriteCond %{REQUEST_FILENAME} !^.*\.jpg$ #requested file is no .jpg RewriteCond %{REQUEST_FILENAME} !-d #is not a directory RewriteRule . /index.php [L] #send it all to index.php &lt;/IfModule&gt; </code></pre> <p>The above Example uses <code>RewriteCond</code>itions to determine when to rewrite ( .gif's, .jpeg's and index.php are excluded ).</p> <p>Hmm, so thats a long text already. Hope it was a bit helpful, but you won't be able to avoid learning the syntax of the Apache RewriteEngine.</p>
3
2009-05-19T12:39:56Z
[ "python", "cgi" ]
How to hide "cgi-bin", ".py", etc from my URLs?
882,430
<p>Brand new to web design, using python. Got Apache up and running, test python script working in cgi-bin directory. Get valid results when I type in the URL explicitly: ".../cgi-bin/showenv.py"</p> <p>But I don't want the URL to look that way. Here at stackoverflow, for example, the URLs that display in my address bar never have the messy details showing the script that was used to run them. They're clean of cgi-bin, .py, etc. extensions. How do I do that?</p> <p>EDIT: Thanks for responses, every single one helpful, lots to learn. I'm going with URL Rewriting for now; example in the docs looks extremely close to what I actually want to do. But I'm committed to python, so will have to look at WSGI down the road.</p>
11
2009-05-19T12:24:38Z
882,664
<p>The python way of writing web applications is not cgi-bin. It is by using <a href="http://wsgi.org">WSGI</a>.</p> <p>WSGI is a standard interface between web servers and Python web applications or frameworks. The <a href="http://www.python.org/dev/peps/pep-0333/">PEP 0333</a> defines it.</p> <p>There are no disadvantages in using it instead of CGI. And you'll gain a lot. Beautiful URLs is just one of the neat things you can do easily.</p> <p>Also, writing a WSGI application means you can deploy on any web server that supports the WSGI interface. Apache does so by using <a href="http://code.google.com/p/modwsgi/">mod_wsgi</a>.</p> <p>You can configure it in apache like that:</p> <pre><code>WSGIScriptAlias /myapp /usr/local/www/wsgi-scripts/myapp.py </code></pre> <p>Then all requests on <code>http://myserver.domain/myapp</code> will go to myapp.py's <code>application</code> callable, including <code>http://myserver.domain/myapp/something/here</code>. </p> <p>example <code>myapp.py</code>:</p> <pre><code>def application(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')]) return ['Hello World!'] </code></pre>
12
2009-05-19T13:09:58Z
[ "python", "cgi" ]
How to hide "cgi-bin", ".py", etc from my URLs?
882,430
<p>Brand new to web design, using python. Got Apache up and running, test python script working in cgi-bin directory. Get valid results when I type in the URL explicitly: ".../cgi-bin/showenv.py"</p> <p>But I don't want the URL to look that way. Here at stackoverflow, for example, the URLs that display in my address bar never have the messy details showing the script that was used to run them. They're clean of cgi-bin, .py, etc. extensions. How do I do that?</p> <p>EDIT: Thanks for responses, every single one helpful, lots to learn. I'm going with URL Rewriting for now; example in the docs looks extremely close to what I actually want to do. But I'm committed to python, so will have to look at WSGI down the road.</p>
11
2009-05-19T12:24:38Z
882,671
<p>You'll find the <code>ScriptAlias</code> directive helpful. Using</p> <pre><code>ScriptAlias /urlpath /your/cgi-bin/script.py </code></pre> <p>you can access your script via <code>http://yourserver/urlpath</code>.</p> <p>You also might want to look into <a href="http://modrails.com" rel="nofollow"><code>mod_passenger</code></a>, though the last time I used it, WSGI was kind of a "second-class citizen" within the library—it could detect WSGI scripts if it were used to serve the whole domain, but otherwise there are no directives to get it to run a WSGI app.</p>
3
2009-05-19T13:11:46Z
[ "python", "cgi" ]
Sending HTML email using Python
882,712
<p>How can I send the HTML content in an email using Python? I can send simple text.</p>
148
2009-05-19T13:20:18Z
882,770
<p>From <a href="http://docs.python.org/library/email-examples.html#id4">Python v2.6.2 documentation - 19.1.11. email: Examples</a>:</p> <blockquote> <p>Here’s an example of how to create an HTML message with an alternative plain text version:</p> </blockquote> <pre class="lang-python prettyprint-override"><code>#! /usr/bin/python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # me == my email address # you == recipient's email address me = "my@email.com" you = "your@email.com" # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = "Link" msg['From'] = me msg['To'] = you # Create the body of the message (a plain-text and an HTML version). text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" html = """\ &lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;p&gt;Hi!&lt;br&gt; How are you?&lt;br&gt; Here is the &lt;a href="http://www.python.org"&gt;link&lt;/a&gt; you wanted. &lt;/p&gt; &lt;/body&gt; &lt;/html&gt; """ # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # Send the message via local SMTP server. s = smtplib.SMTP('localhost') # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. s.sendmail(me, you, msg.as_string()) s.quit() </code></pre>
225
2009-05-19T13:30:55Z
[ "python", "html-email" ]
Sending HTML email using Python
882,712
<p>How can I send the HTML content in an email using Python? I can send simple text.</p>
148
2009-05-19T13:20:18Z
882,804
<p>Here's sample code. This is inspired from code found on the <a href="http://code.activestate.com/recipes/langs/python/">Python Cookbook</a> site (can't find the exact link)</p> <pre><code>def createhtmlmail (html, text, subject, fromEmail): """Create a mime-message that will render HTML in popular MUAs, text in better ones""" import MimeWriter import mimetools import cStringIO out = cStringIO.StringIO() # output buffer for our message htmlin = cStringIO.StringIO(html) txtin = cStringIO.StringIO(text) writer = MimeWriter.MimeWriter(out) # # set up some basic headers... we put subject here # because smtplib.sendmail expects it to be in the # message body # writer.addheader("From", fromEmail) writer.addheader("Subject", subject) writer.addheader("MIME-Version", "1.0") # # start the multipart section of the message # multipart/alternative seems to work better # on some MUAs than multipart/mixed # writer.startmultipartbody("alternative") writer.flushheaders() # # the plain text section # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") pout = subpart.startbody("text/plain", [("charset", 'us-ascii')]) mimetools.encode(txtin, pout, 'quoted-printable') txtin.close() # # start the html subpart of the message # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") # # returns us a file-ish object we can write to # pout = subpart.startbody("text/html", [("charset", 'us-ascii')]) mimetools.encode(htmlin, pout, 'quoted-printable') htmlin.close() # # Now that we're done, close our writer and # return the message body # writer.lastpart() msg = out.getvalue() out.close() print msg return msg if __name__=="__main__": import smtplib html = 'html version' text = 'TEST VERSION' subject = "BACKUP REPORT" message = createhtmlmail(html, text, subject, 'From Host &lt;sender@host.com&gt;') server = smtplib.SMTP("smtp_server_address","smtp_port") server.login('username', 'password') server.sendmail('sender@host.com', 'target@otherhost.com', message) server.quit() </code></pre>
7
2009-05-19T13:37:02Z
[ "python", "html-email" ]
Sending HTML email using Python
882,712
<p>How can I send the HTML content in an email using Python? I can send simple text.</p>
148
2009-05-19T13:20:18Z
883,269
<p>You might try using my <a href="http://pypi.python.org/pypi/mailer/">mailer</a> module.</p> <pre class="lang-python prettyprint-override"><code>from mailer import Mailer from mailer import Message message = Message(From="me@example.com", To="you@example.com") message.Subject = "An HTML Email" message.Html = """&lt;p&gt;Hi!&lt;br&gt; How are you?&lt;br&gt; Here is the &lt;a href="http://www.python.org"&gt;link&lt;/a&gt; you wanted.&lt;/p&gt;""" sender = Mailer('smtp.example.com') sender.send(message) </code></pre>
46
2009-05-19T14:55:23Z
[ "python", "html-email" ]
Sending HTML email using Python
882,712
<p>How can I send the HTML content in an email using Python? I can send simple text.</p>
148
2009-05-19T13:20:18Z
1,901,298
<p>Just a big fat warning. If you are sending non-<a href="http://en.wikipedia.org/wiki/ASCII" rel="nofollow">ASCII</a> email using Python &lt; 3.0, consider using the email in <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="nofollow">Django</a>. It wraps <a href="http://en.wikipedia.org/wiki/UTF-8" rel="nofollow">UTF-8</a> strings correctly, and also is much simpler to use. You have been warned :-)</p>
5
2009-12-14T14:42:05Z
[ "python", "html-email" ]
Sending HTML email using Python
882,712
<p>How can I send the HTML content in an email using Python? I can send simple text.</p>
148
2009-05-19T13:20:18Z
26,369,282
<p>Here is a <a href="http://en.wikipedia.org/wiki/Gmail">Gmail</a> implementation of the accepted answer:</p> <pre><code>import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # me == my email address # you == recipient's email address me = "my@email.com" you = "your@email.com" # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = "Link" msg['From'] = me msg['To'] = you # Create the body of the message (a plain-text and an HTML version). text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" html = """\ &lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;p&gt;Hi!&lt;br&gt; How are you?&lt;br&gt; Here is the &lt;a href="http://www.python.org"&gt;link&lt;/a&gt; you wanted. &lt;/p&gt; &lt;/body&gt; &lt;/html&gt; """ # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # Send the message via local SMTP server. mail = smtplib.SMTP('smtp.gmail.com', 587) mail.ehlo() mail.starttls() mail.login('userName', 'password') mail.sendmail(me, you, msg.as_string()) mail.quit() </code></pre>
21
2014-10-14T19:59:15Z
[ "python", "html-email" ]
Sending HTML email using Python
882,712
<p>How can I send the HTML content in an email using Python? I can send simple text.</p>
148
2009-05-19T13:20:18Z
32,129,736
<p>Here is a simple way to send an HTML email, just by specifying the Content-Type header as 'text/html':</p> <pre><code>import email.message import smtplib msg = email.message.Message() msg['Subject'] = 'foo' msg['From'] = 'sender@test.com' msg['To'] = 'recipient@test.com' msg.add_header('Content-Type','text/html') msg.set_payload('Body of &lt;b&gt;message&lt;/b&gt;') s = smtplib.SMTP(mailmerge_conf.smtp_server) s.starttls() s.login(email_login, email_passwd) s.sendmail(msg['From'], [msg['To']], msg.as_string()) </code></pre>
16
2015-08-20T22:52:22Z
[ "python", "html-email" ]
Sending HTML email using Python
882,712
<p>How can I send the HTML content in an email using Python? I can send simple text.</p>
148
2009-05-19T13:20:18Z
36,682,833
<p>Actually, <a href="https://github.com/kootenpv/yagmail" rel="nofollow">yagmail</a> took a bit different approach. </p> <p>It will <strong>by default</strong> send HTML, with automatic fallback for incapable email-readers. It is not the 17th century anymore.</p> <p>Of course, it can be overridden, but here goes:</p> <pre><code>import yagmail yag = yagmail.SMTP("me@example.com", "mypassword") html_msg = """&lt;p&gt;Hi!&lt;br&gt; How are you?&lt;br&gt; Here is the &lt;a href="http://www.python.org"&gt;link&lt;/a&gt; you wanted.&lt;/p&gt;""" yag.send("to@example.com", "the subject", html_msg) </code></pre> <p>For installation instructions and many more great features, have a look at the <a href="https://github.com/kootenpv/yagmail" rel="nofollow">github</a>.</p>
0
2016-04-17T22:18:14Z
[ "python", "html-email" ]
Sending HTML email using Python
882,712
<p>How can I send the HTML content in an email using Python? I can send simple text.</p>
148
2009-05-19T13:20:18Z
39,517,007
<p>Here is my answer for AWS using boto3</p> <pre><code> subject = "Hello" html = "&lt;b&gt;Hello Consumer&lt;/b&gt;" client = boto3.client('ses', region_name='us-east-1', aws_access_key_id="your_key", aws_secret_access_key="your_secret") client.send_email( Source='ACME &lt;do-not-reply@acme.com&gt;', Destination={'ToAddresses': [email]}, Message={ 'Subject': {'Data': subject}, 'Body': { 'Html': {'Data': html} } } </code></pre>
0
2016-09-15T17:27:25Z
[ "python", "html-email" ]
Is there a way to poll a file handle returned from subprocess.Popen?
883,152
<p>Say I write this:</p> <pre><code>from subprocessing import Popen, STDOUT, PIPE p = Popen(["myproc"], stderr=STDOUT, stdout=PIPE) </code></pre> <p>Now if I do</p> <pre><code>line = p.stdout.readline() </code></pre> <p>my program waits until the subprocess outputs the next line. </p> <p>Is there any magic I can do to <code>p.stdout</code> so that I could read the output if it's there, but just continue otherwise? I'm looking for something like <code>Queue.get_nowait()</code></p> <p>I know I can just create a thread for reading <code>p.stdout</code>, but let's assume I can't create new threads.</p>
4
2009-05-19T14:33:15Z
883,166
<p>Use <code>p.stdout.read(1)</code> this will read character by character</p> <p>And here is a full example:</p> <pre><code>import subprocess import sys process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) while True: out = process.stdout.read(1) if out == '' and process.poll() != None: break if out != '': sys.stdout.write(out) sys.stdout.flush() </code></pre>
9
2009-05-19T14:36:21Z
[ "python", "pipe", "subprocess" ]
Is there a way to poll a file handle returned from subprocess.Popen?
883,152
<p>Say I write this:</p> <pre><code>from subprocessing import Popen, STDOUT, PIPE p = Popen(["myproc"], stderr=STDOUT, stdout=PIPE) </code></pre> <p>Now if I do</p> <pre><code>line = p.stdout.readline() </code></pre> <p>my program waits until the subprocess outputs the next line. </p> <p>Is there any magic I can do to <code>p.stdout</code> so that I could read the output if it's there, but just continue otherwise? I'm looking for something like <code>Queue.get_nowait()</code></p> <p>I know I can just create a thread for reading <code>p.stdout</code>, but let's assume I can't create new threads.</p>
4
2009-05-19T14:33:15Z
883,204
<p>Use the <code>select</code> module in Python's standard library, see <a href="http://docs.python.org/library/select.html">http://docs.python.org/library/select.html</a> . <code>select.select([p.stdout.fileno()], [], [], 0)</code> immediately returns a tuple whose items are three lists: the first one is going to be non-empty if there's something to read on that file descriptor.</p>
6
2009-05-19T14:42:41Z
[ "python", "pipe", "subprocess" ]
Calling python from python - persistence of module imports?
883,211
<p>So I have some Python scripts, and I've got a BaseHTTPServer to serve up their responses. If the requested file is a .py then I'll run that script using execfile(script.py).</p> <p>The question is this: are there any special rules about imports? One script needs to run just once, and it would be good to keep the objects it creates alive between requests. Can I trust that that will happen? </p> <p>Does script run via execfile() run any differently, or have any scope access issues?</p>
2
2009-05-19T14:43:39Z
883,471
<p>The documentation for the execfile method is <a href="http://docs.python.org/library/functions.html" rel="nofollow">here</a>. Since no particular version of python was specified, I'm going to assume we're talking about 2.6.2.</p> <p>The documentation for execfile specifies it takes three arguments: the filename, a dictionary (to act as the local variables), and a second dictionary (to act as the global variables). If you omit the second and third arguments, the file's contents are run in their own scope (like a module) that captures local variables but exposes global variables to the parent scope. So if the file creates local variables, they won't be retained, but global variables will be retained.</p> <p>However, running execfile without local and global contexts specified means that the file sees the locals and globals of the calling function. For code that you don't trust, this should be considered a security hole. It may generally be wise to create two dictionaries for locals and globals and pass those in as the second and third arguments to execfile. If you keep those dictionaries somewhere (such as in another dictionary keyed by the filename), then you could re-use those dictionaries the next time the file is served, which will keep the objects created by the file alive.</p> <p>So in short: execfile isn't exactly like import. But you can retain dictionaries of the locals and globals to keep the results of an execfile call around to be used again.</p>
2
2009-05-19T15:30:16Z
[ "python", "import", "module" ]
Calling python from python - persistence of module imports?
883,211
<p>So I have some Python scripts, and I've got a BaseHTTPServer to serve up their responses. If the requested file is a .py then I'll run that script using execfile(script.py).</p> <p>The question is this: are there any special rules about imports? One script needs to run just once, and it would be good to keep the objects it creates alive between requests. Can I trust that that will happen? </p> <p>Does script run via execfile() run any differently, or have any scope access issues?</p>
2
2009-05-19T14:43:39Z
883,478
<p>I recommend not using <code>execfile</code>. Instead, you can dynamically import the python file they request as a module using the builtin <code>__import__</code> function. Here's a complete, working example that I just wrote and tested:</p> <pre><code>from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() filename = self.path.lstrip("/") self.wfile.write("You requested " + filename + "\n\n") if filename.endswith(".py"): pyname = filename.replace("/", ".")[:-3] module = __import__(pyname) self.wfile.write( module.do_work() ) HTTPServer(("",8080), Handler).serve_forever() </code></pre> <p>So in this case, if someone visits <a href="http://localhost:8080/some_page" rel="nofollow">http://localhost:8080/some_page</a> then "You requested some_page" will be printed.</p> <p>But if you request <a href="http://localhost:8080/some_module.py" rel="nofollow">http://localhost:8080/some_module.py</a> then the file <code>some_module.py</code> will be imported as a Python module and the <code>do_work</code> function in that module will be called. So if that module contains the code</p> <pre><code>def do_work(): return "Hello World!" </code></pre> <p>and you make that request, then the resulting page will be</p> <pre><code>You requested some_module.py Hello World! </code></pre> <p>This should be a good starting point for dealing with such things. As an aside, if you find yourself wanting a more advanced web server, I highly recommend <a href="http://cherrypy.org/" rel="nofollow">CherryPy</a>.</p>
1
2009-05-19T15:31:04Z
[ "python", "import", "module" ]
django excel xlwt
883,313
<p>On a django site, I want to generate an excel file based on some data in the database.</p> <p>I'm thinking of using <a href="http://pypi.python.org/pypi/xlwt">xlwt</a>, but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?</p> <p>I've also found this <a href="http://www.djangosnippets.org/snippets/1151/">snippet</a> but it doesn't do what I need. All I want is a way to get the stream from the xlwt object to the response object (without writing to a temporary file)</p>
30
2009-05-19T15:04:14Z
883,351
<p>neat package! i didn't know about this</p> <p>According to the doc, the <code>save(filename_or_stream)</code> method takes either a filename to save on, or a file-like stream to write on.</p> <p>And a Django response object happens to be a file-like stream! so just do <code>xls.save(response)</code>. Look the Django docs about <a href="http://docs.djangoproject.com/en/dev/howto/outputting-pdf/#complex-pdfs">generating PDFs</a> with ReportLab to see a similar situation.</p> <p><strong>edit:</strong> (adapted from ShawnMilo's comment):</p> <pre><code>def xls_to_response(xls, fname): response = HttpResponse(mimetype="application/ms-excel") response['Content-Disposition'] = 'attachment; filename=%s' % fname xls.save(response) return response </code></pre> <p>then, from your view function, just create the <code>xls</code> object and finish with </p> <pre><code>return xls_to_response(xls,'foo.xls') </code></pre>
50
2009-05-19T15:09:44Z
[ "python", "django", "excel", "xlwt" ]
django excel xlwt
883,313
<p>On a django site, I want to generate an excel file based on some data in the database.</p> <p>I'm thinking of using <a href="http://pypi.python.org/pypi/xlwt">xlwt</a>, but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?</p> <p>I've also found this <a href="http://www.djangosnippets.org/snippets/1151/">snippet</a> but it doesn't do what I need. All I want is a way to get the stream from the xlwt object to the response object (without writing to a temporary file)</p>
30
2009-05-19T15:04:14Z
883,379
<p>If your data result doesn't need formulas or exact presentation styles, you can always use CSV. any spreadsheet program would directly read it. I've even seen some webapps that generate CSV but name it as .XSL just to be sure that Excel opens it</p>
0
2009-05-19T15:15:40Z
[ "python", "django", "excel", "xlwt" ]
django excel xlwt
883,313
<p>On a django site, I want to generate an excel file based on some data in the database.</p> <p>I'm thinking of using <a href="http://pypi.python.org/pypi/xlwt">xlwt</a>, but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?</p> <p>I've also found this <a href="http://www.djangosnippets.org/snippets/1151/">snippet</a> but it doesn't do what I need. All I want is a way to get the stream from the xlwt object to the response object (without writing to a temporary file)</p>
30
2009-05-19T15:04:14Z
884,543
<p>You can save your XLS file to a <a href="http://docs.python.org/library/stringio.html" rel="nofollow">StringIO</a> object, which is file-like.</p> <p>You can return the StringIO object's <code>getvalue()</code> in the response. Be sure to add headers to mark it as a downloadable spreadsheet.</p>
2
2009-05-19T19:17:54Z
[ "python", "django", "excel", "xlwt" ]
django excel xlwt
883,313
<p>On a django site, I want to generate an excel file based on some data in the database.</p> <p>I'm thinking of using <a href="http://pypi.python.org/pypi/xlwt">xlwt</a>, but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?</p> <p>I've also found this <a href="http://www.djangosnippets.org/snippets/1151/">snippet</a> but it doesn't do what I need. All I want is a way to get the stream from the xlwt object to the response object (without writing to a temporary file)</p>
30
2009-05-19T15:04:14Z
1,362,637
<p>You might want to check <a href="https://cybernetics.hudora.biz/projects/wiki/huDjango" rel="nofollow">huDjango</a> which comes fith a function called <code>serializers.queryset_to_xls()</code> do convert a queryset into an downloadable Excel Sheet.</p>
2
2009-09-01T13:56:18Z
[ "python", "django", "excel", "xlwt" ]
django excel xlwt
883,313
<p>On a django site, I want to generate an excel file based on some data in the database.</p> <p>I'm thinking of using <a href="http://pypi.python.org/pypi/xlwt">xlwt</a>, but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?</p> <p>I've also found this <a href="http://www.djangosnippets.org/snippets/1151/">snippet</a> but it doesn't do what I need. All I want is a way to get the stream from the xlwt object to the response object (without writing to a temporary file)</p>
30
2009-05-19T15:04:14Z
2,152,627
<p>***UPDATE: django-excel-templates no longer being maintained, instead try Marmir <a href="http://brianray.github.com/mm/" rel="nofollow">http://brianray.github.com/mm/</a></p> <p>Still in development as I type this but <a href="http://code.google.com/p/django-excel-templates/" rel="nofollow">http://code.google.com/p/django-excel-templates/</a> Django excel templates project aims to do what your asking.</p> <p>Specifically look at the tests. Here is a simple case:</p> <pre><code># from django_excel_templates import * from django_excel_templates.color_converter import * from models import * from django.http import HttpResponse def xls_simple(request): ## Simple ## testobj = Book.objects.all() formatter = ExcelFormatter() simpleStyle = ExcelStyle(vert=2,wrap=1) formatter.addBodyStyle(simpleStyle) formatter.setWidth('name,category,publish_date,bought_on',3000) formatter.setWidth('price',600) formatter.setWidth('ebook',1200) formatter.setWidth('about',20000) simple_report = ExcelReport() simple_report.addSheet("TestSimple") filter = ExcelFilter(order='name,category,publish_date,about,bought_on,price,ebook') simple_report.addQuerySet(testobj,REPORT_HORZ,formatter, filter) response = HttpResponse(simple_report.writeReport(),mimetype='application/ms-excel') response['Content-Disposition'] = 'attachment; filename=simple_test.xls' return response </code></pre>
6
2010-01-28T06:05:15Z
[ "python", "django", "excel", "xlwt" ]
django excel xlwt
883,313
<p>On a django site, I want to generate an excel file based on some data in the database.</p> <p>I'm thinking of using <a href="http://pypi.python.org/pypi/xlwt">xlwt</a>, but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?</p> <p>I've also found this <a href="http://www.djangosnippets.org/snippets/1151/">snippet</a> but it doesn't do what I need. All I want is a way to get the stream from the xlwt object to the response object (without writing to a temporary file)</p>
30
2009-05-19T15:04:14Z
7,675,018
<p>Use <a href="https://bitbucket.org/kmike/django-excel-response" rel="nofollow">https://bitbucket.org/kmike/django-excel-response</a></p>
1
2011-10-06T13:36:50Z
[ "python", "django", "excel", "xlwt" ]
wxPython + multiprocessing: Checking if a color string is legitimate
883,348
<p>I have a wxPython program with two processes: A primary and a secondary one (I'm using the multiprocessing module.) The primary one runs the wxPython GUI, the secondary one does not. However, there is something I would like to do from the secondary process: Given a string that describes a color, to check whether this would be legitimate color for wxPython. That means, whether I can create a <code>wx.Pen(color_string)</code> or not.</p> <p>How do I do this?</p> <p>(I tried making a wx.Pen and comparing its color to the null color, but that required to create a wx.App in the second process, and when I did create one the program raised an error in some special wxPython window.)</p>
0
2009-05-19T15:09:05Z
883,451
<p>You could make two Queues between the two processes and have the second one delegate wx-related functionality to the first one (by pushing on the first queue the parameters of the task to perform, and waiting for the result on the second one).</p>
1
2009-05-19T15:26:43Z
[ "python", "wxpython", "multiprocessing" ]
Python unittest: how do I test the argument in an Exceptions?
883,357
<p>I am testing for Exceptions using unittest, for example:</p> <pre><code>self.assertRaises(UnrecognizedAirportError, func, arg1, arg2) </code></pre> <p>and my code raises:</p> <pre><code>raise UnrecognizedAirportError('From') </code></pre> <p>Which works well.</p> <p>How do I test that the argument in the exception is what I expect it to be?</p> <p>I wish to somehow assert that <code>capturedException.argument == 'From'</code>.</p> <p>I hope this is clear enough - thanks in advance!</p> <p>Tal.</p>
5
2009-05-19T15:10:36Z
883,401
<p>Like this.</p> <pre><code>&gt;&gt;&gt; try: ... raise UnrecognizedAirportError("func","arg1","arg2") ... except UnrecognizedAirportError, e: ... print e.args ... ('func', 'arg1', 'arg2') &gt;&gt;&gt; </code></pre> <p>Your arguments are in <code>args</code>, if you simply subclass <code>Exception</code>. </p> <p>See <a href="http://docs.python.org/library/exceptions.html#module-exceptions">http://docs.python.org/library/exceptions.html#module-exceptions</a></p> <blockquote> <p>If the exception class is derived from the standard root class BaseException, the associated value is present as the exception instance’s args attribute.</p> </blockquote> <p><hr /></p> <p><strong>Edit</strong> Bigger Example.</p> <pre><code>class TestSomeException( unittest.TestCase ): def testRaiseWithArgs( self ): try: ... Something that raises the exception ... self.fail( "Didn't raise the exception" ) except UnrecognizedAirportError, e: self.assertEquals( "func", e.args[0] ) self.assertEquals( "arg1", e.args[1] ) except Exception, e: self.fail( "Raised the wrong exception" ) </code></pre>
11
2009-05-19T15:19:27Z
[ "python", "unit-testing" ]
Python unittest: how do I test the argument in an Exceptions?
883,357
<p>I am testing for Exceptions using unittest, for example:</p> <pre><code>self.assertRaises(UnrecognizedAirportError, func, arg1, arg2) </code></pre> <p>and my code raises:</p> <pre><code>raise UnrecognizedAirportError('From') </code></pre> <p>Which works well.</p> <p>How do I test that the argument in the exception is what I expect it to be?</p> <p>I wish to somehow assert that <code>capturedException.argument == 'From'</code>.</p> <p>I hope this is clear enough - thanks in advance!</p> <p>Tal.</p>
5
2009-05-19T15:10:36Z
883,433
<p><code>assertRaises</code> is a bit simplistic, and doesn't let you test the details of the raised exception beyond it belonging to a specified class. For finer-grained testing of exceptions, you need to "roll your own" with a <code>try/except/else</code> block (you can do it once and for all in a <code>def assertDetailedRaises</code> method you add to your own generic subclass of unittest's test-case, then have your test cases all inherit your subclass instead of unittest's).</p>
1
2009-05-19T15:23:55Z
[ "python", "unit-testing" ]
Python Multiprocessing atexit Error "Error in atexit._run_exitfuncs"
883,370
<p>I am trying to run a simple multiple processes application in Python. The main thread spawns 1 to N processes and waits until they all done processing. The processes each run an infinite loop, so they can potentially run forever without some user interruption, so I put in some code to handle a KeyboardInterrupt:</p> <pre><code>#!/usr/bin/env python import sys import time from multiprocessing import Process def main(): # Set up inputs.. # Spawn processes Proc( 1).start() Proc( 2).start() class Proc ( Process ): def __init__ ( self, procNum): self.id = procNum Process.__init__(self) def run ( self ): doneWork = False while True: try: # Do work... time.sleep(1) sys.stdout.write('.') if doneWork: print "PROC#" + str(self.id) + " Done." break except KeyboardInterrupt: print "User aborted." sys.exit() # Main Entry if __name__=="__main__": main() </code></pre> <p>The problem is that when using CTRL-C to exit, I get an additional error even though the processes seem to exit immediately:</p> <pre><code>......User aborted. Error in atexit._run_exitfuncs: Traceback (most recent call last): File "C:\Python26\lib\atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "C:\Python26\lib\multiprocessing\util.py", line 281, in _exit_function p.join() File "C:\Python26\lib\multiprocessing\process.py", line 119, in join res = self._popen.wait(timeout) File "C:\Python26\lib\multiprocessing\forking.py", line 259, in wait res = _subprocess.WaitForSingleObject(int(self._handle), msecs) KeyboardInterrupt Error in sys.exitfunc: Traceback (most recent call last): File "C:\Python26\lib\atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "C:\Python26\lib\multiprocessing\util.py", line 281, in _exit_function p.join() File "C:\Python26\lib\multiprocessing\process.py", line 119, in join res = self._popen.wait(timeout) File "C:\Python26\lib\multiprocessing\forking.py", line 259, in wait res = _subprocess.WaitForSingleObject(int(self._handle), msecs) KeyboardInterrupt </code></pre> <p>I am running Python 2.6 on Windows. If there is a better way to handle multiprocessing in Python, please let me know.</p>
7
2009-05-19T15:13:33Z
883,500
<p>Rather then just forcing <code>sys.exit()</code>, you want to send a signal to your threads to tell them to stop. Look into using <a href="http://docs.python.org/library/signal.html" rel="nofollow">signal handlers</a> and threads in Python.</p> <p>You could potentially do this by changing your <code>while True:</code> loop to be <code>while keep_processing:</code> where <code>keep_processing</code> is some sort of global variable that gets set on the KeyboardInterrupt exception. I don't think this is a good practice though.</p>
2
2009-05-19T15:36:09Z
[ "python", "process", "interrupt", "atexit" ]
Regex for finding date in Apache access log
883,520
<p>I'm writing a python script to extract data out of our 2GB Apache access log. Here's one line from the log.</p> <pre><code>81.52.143.15 - - [01/Apr/2008:00:07:20 -0600] "GET /robots.txt HTTP/1.1" 200 29 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) VoilaBot BETA 1.2 (http://www.voila.com/)" </code></pre> <p>I'm trying to get the date portion from that line, and regex is failing me, and I'm not sure why. Here's my python code:</p> <pre><code>l = 81.52.143.15 - - [01/Apr/2008:00:07:20 -0600] "GET /robots.txt HTTP/1.1" 200 29 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) VoilaBot BETA 1.2 (http://www.voila.com/)" re.match(r"\d{2}/\w{3}/\d{4}", l) </code></pre> <p>returns nothing. Neither do the following:</p> <pre><code>re.match(r"\d{2}/", l) re.match(r"\w{3}", l) </code></pre> <p>or anything else I can thing of to even get <em>part</em> of the date. What am I misunderstanding?</p>
1
2009-05-19T15:39:41Z
883,552
<p><code>match()</code> tries to match the entire string. Try <a href="http://docs.python.org/library/re.html#re.search" rel="nofollow"><code>search()</code></a> instead.</p> <p>See also the <a href="http://docs.python.org/howto/regex.html" rel="nofollow">Python Regular Expression HOWTO</a>, and the <a href="http://www.regular-expressions.info/python.html" rel="nofollow">Python page</a> at the always-excellent <a href="http://www.regular-expressions.info/" rel="nofollow">regular-expressions.info</a>.</p>
0
2009-05-19T15:45:19Z
[ "python", "regex" ]
Regex for finding date in Apache access log
883,520
<p>I'm writing a python script to extract data out of our 2GB Apache access log. Here's one line from the log.</p> <pre><code>81.52.143.15 - - [01/Apr/2008:00:07:20 -0600] "GET /robots.txt HTTP/1.1" 200 29 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) VoilaBot BETA 1.2 (http://www.voila.com/)" </code></pre> <p>I'm trying to get the date portion from that line, and regex is failing me, and I'm not sure why. Here's my python code:</p> <pre><code>l = 81.52.143.15 - - [01/Apr/2008:00:07:20 -0600] "GET /robots.txt HTTP/1.1" 200 29 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) VoilaBot BETA 1.2 (http://www.voila.com/)" re.match(r"\d{2}/\w{3}/\d{4}", l) </code></pre> <p>returns nothing. Neither do the following:</p> <pre><code>re.match(r"\d{2}/", l) re.match(r"\w{3}", l) </code></pre> <p>or anything else I can thing of to even get <em>part</em> of the date. What am I misunderstanding?</p>
1
2009-05-19T15:39:41Z
883,553
<p>match() looks for a match at the beginning of the string. Use search() to look for a match anywhere in the string. More info here: <a href="http://docs.python.org/library/re.html#matching-vs-searching" rel="nofollow">http://docs.python.org/library/re.html#matching-vs-searching</a></p>
5
2009-05-19T15:46:07Z
[ "python", "regex" ]
Regex for finding date in Apache access log
883,520
<p>I'm writing a python script to extract data out of our 2GB Apache access log. Here's one line from the log.</p> <pre><code>81.52.143.15 - - [01/Apr/2008:00:07:20 -0600] "GET /robots.txt HTTP/1.1" 200 29 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) VoilaBot BETA 1.2 (http://www.voila.com/)" </code></pre> <p>I'm trying to get the date portion from that line, and regex is failing me, and I'm not sure why. Here's my python code:</p> <pre><code>l = 81.52.143.15 - - [01/Apr/2008:00:07:20 -0600] "GET /robots.txt HTTP/1.1" 200 29 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) VoilaBot BETA 1.2 (http://www.voila.com/)" re.match(r"\d{2}/\w{3}/\d{4}", l) </code></pre> <p>returns nothing. Neither do the following:</p> <pre><code>re.match(r"\d{2}/", l) re.match(r"\w{3}", l) </code></pre> <p>or anything else I can thing of to even get <em>part</em> of the date. What am I misunderstanding?</p>
1
2009-05-19T15:39:41Z
885,019
<p>Rather than using regular expressions to get the date, it might be easier to just split the line on spaces and extract the date:</p> <pre><code> l = '81.52.143.15 - - [01/Apr/2008:00:07:20 -0600] "GET /robots.txt HTTP/1.1" 200 29 "-" Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) VoilaBot BETA 1.2 (http://www.voila.com/)"' date = l.split()[3] </code></pre> <p>If you're processing very large files, this is probably more efficient than using regular expressions.</p>
0
2009-05-19T21:04:31Z
[ "python", "regex" ]
Regex for finding date in Apache access log
883,520
<p>I'm writing a python script to extract data out of our 2GB Apache access log. Here's one line from the log.</p> <pre><code>81.52.143.15 - - [01/Apr/2008:00:07:20 -0600] "GET /robots.txt HTTP/1.1" 200 29 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) VoilaBot BETA 1.2 (http://www.voila.com/)" </code></pre> <p>I'm trying to get the date portion from that line, and regex is failing me, and I'm not sure why. Here's my python code:</p> <pre><code>l = 81.52.143.15 - - [01/Apr/2008:00:07:20 -0600] "GET /robots.txt HTTP/1.1" 200 29 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) VoilaBot BETA 1.2 (http://www.voila.com/)" re.match(r"\d{2}/\w{3}/\d{4}", l) </code></pre> <p>returns nothing. Neither do the following:</p> <pre><code>re.match(r"\d{2}/", l) re.match(r"\w{3}", l) </code></pre> <p>or anything else I can thing of to even get <em>part</em> of the date. What am I misunderstanding?</p>
1
2009-05-19T15:39:41Z
3,969,728
<p>Or you can use one of already available python apache log parsers like :</p> <ul> <li>Apachelogs</li> <li>Logtools</li> <li>Logrep (Wtop package)</li> </ul>
1
2010-10-19T14:59:11Z
[ "python", "regex" ]
Custom ordering in Django
883,575
<p>How do you define a specific ordering in Django <code>QuerySet</code>s?</p> <p>Specifically, if I have a <code>QuerySet</code> like so: <code>['a10', 'a1', 'a2']</code>.</p> <p>Regular order (using <code>Whatever.objects.order_by('someField')</code>) will give me <code>['a1', 'a10', 'a2']</code>, while I am looking for: <code>['a1', 'a2', 'a10']</code>.</p> <p>What is the proper way to define my own ordering technique?</p>
20
2009-05-19T15:49:31Z
883,641
<p>As far as I'm aware, there's no way to specify database-side ordering in this way as it would be too backend-specific. You may wish to resort to good old-fashioned Python sorting:</p> <pre><code>class Foo(models.Model): name = models.CharField(max_length=128) Foo.objects.create(name='a10') Foo.objects.create(name='a1') Foo.objects.create(name='a2') ordered = sorted(Foo.objects.all(), key=lambda n: (n[0], int(n[1:]))) print ordered # yields a1, a2, 10 </code></pre> <p>If you find yourself needing this kind of sorting a lot, I'd recommend making a custom <code>models.Manager</code> subclass for your model that performs the ordering. Something like:</p> <pre><code>class FooManager(models.Manager): def in_a_number_order(self, *args, **kwargs): qs = self.get_query_set().filter(*args, **kwargs) return sorted(qs, key=lambda n: (n[0], int(n[1:]))) class Foo(models.Model): ... as before ... objects = FooManager() print Foo.objects.in_a_number_order() print Foo.objects.in_a_number_order(id__in=[5, 4, 3]) # or any filtering expression </code></pre>
37
2009-05-19T16:03:55Z
[ "python", "django", "django-models" ]
Custom ordering in Django
883,575
<p>How do you define a specific ordering in Django <code>QuerySet</code>s?</p> <p>Specifically, if I have a <code>QuerySet</code> like so: <code>['a10', 'a1', 'a2']</code>.</p> <p>Regular order (using <code>Whatever.objects.order_by('someField')</code>) will give me <code>['a1', 'a10', 'a2']</code>, while I am looking for: <code>['a1', 'a2', 'a10']</code>.</p> <p>What is the proper way to define my own ordering technique?</p>
20
2009-05-19T15:49:31Z
883,645
<p>It depends on where you want to use it. </p> <p>If you want to use it in your own templates, I would suggest to write a template-tag, that will do the ordering for you In it, you could use any sorting algorithm you want to use.</p> <p>In admin I do custom sorting by extending the templates to my needs and loading a template-tag as described above</p>
0
2009-05-19T16:04:56Z
[ "python", "django", "django-models" ]
Custom ordering in Django
883,575
<p>How do you define a specific ordering in Django <code>QuerySet</code>s?</p> <p>Specifically, if I have a <code>QuerySet</code> like so: <code>['a10', 'a1', 'a2']</code>.</p> <p>Regular order (using <code>Whatever.objects.order_by('someField')</code>) will give me <code>['a1', 'a10', 'a2']</code>, while I am looking for: <code>['a1', 'a2', 'a10']</code>.</p> <p>What is the proper way to define my own ordering technique?</p>
20
2009-05-19T15:49:31Z
889,445
<p>@Jarret's answer (do the sort in Python) works great for simple cases. As soon as you have a large table and want to, say, pull only the first page of results sorted in a certain way, this approach breaks (you have to pull every single row from the database before you can do the sort). At that point I would look into adding a denormalized "sort" field which you populate from the "name" field at save-time, that you can sort on at the DB-level in the usual way.</p>
21
2009-05-20T18:20:33Z
[ "python", "django", "django-models" ]
Custom ordering in Django
883,575
<p>How do you define a specific ordering in Django <code>QuerySet</code>s?</p> <p>Specifically, if I have a <code>QuerySet</code> like so: <code>['a10', 'a1', 'a2']</code>.</p> <p>Regular order (using <code>Whatever.objects.order_by('someField')</code>) will give me <code>['a1', 'a10', 'a2']</code>, while I am looking for: <code>['a1', 'a2', 'a10']</code>.</p> <p>What is the proper way to define my own ordering technique?</p>
20
2009-05-19T15:49:31Z
26,731,696
<p>If you have larger data sets and additionally use a SOLR backend (e.g. with Haystack):</p> <p>Use <code>solr.ICUCollationField</code> with the <code>numeric=true</code> option as type for the sort fields. This will sort according to language and if numbers are present will sort the number part according to numeric rules instead of string sorting.</p> <p>See: <a href="https://cwiki.apache.org/confluence/display/solr/Language+Analysis#LanguageAnalysis-UnicodeCollation" rel="nofollow">https://cwiki.apache.org/confluence/display/solr/Language+Analysis#LanguageAnalysis-UnicodeCollation</a> <a href="http://www.solr-start.com/javadoc/solr-lucene/org/apache/solr/schema/ICUCollationField.html" rel="nofollow">http://www.solr-start.com/javadoc/solr-lucene/org/apache/solr/schema/ICUCollationField.html</a></p>
0
2014-11-04T09:31:39Z
[ "python", "django", "django-models" ]
Given a date range how to calculate the number of weekends partially or wholly within that range?
883,615
<p>Given a date range how to calculate the number of weekends partially or wholly within that range?</p> <p>(A few definitions as requested: take 'weekend' to mean Saturday and Sunday. The date range is inclusive i.e. the end date is part of the range 'wholly or partially' means that any part of the weekend falling within the date range means the whole weekend is counted.)</p> <p>To simplify I imagine you only actually need to know the duration and what day of the week the initial day is...</p> <p>I darn well now it's going to involve doing integer division by 7 and some logic to add 1 depending on the remainder but I can't quite work out what...</p> <p>extra points for answers in Python ;-) </p> <p><strong>Edit</strong></p> <p>Here's my final code.</p> <p>Weekends are Friday and Saturday (as we are counting nights stayed) and days are 0-indexed starting from Monday. I used onebyone's algorithm and Tom's code layout. Thanks a lot folks.</p> <pre><code>def calc_weekends(start_day, duration): days_until_weekend = [5, 4, 3, 2, 1, 1, 6] adjusted_duration = duration - days_until_weekend[start_day] if adjusted_duration &lt; 0: weekends = 0 else: weekends = (adjusted_duration/7)+1 if start_day == 5 and duration % 7 == 0: #Saturday to Saturday is an exception weekends += 1 return weekends if __name__ == "__main__": days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] for start_day in range(0,7): for duration in range(1,16): print "%s to %s (%s days): %s weekends" % (days[start_day], days[(start_day+duration) % 7], duration, calc_weekends(start_day, duration)) print </code></pre>
1
2009-05-19T15:58:57Z
883,669
<p>You would need external logic beside raw math. You need to have a calendar library (or if you have a decent amount of time implement it yourself) to define what a weekend, what day of the week you start on, end on, etc.</p> <p>Take a look at <a href="http://docs.python.org/library/calendar.html" rel="nofollow">Python's calendar class</a>.</p> <p>Without a logical definition of days in your code, a pure mathematical methods would fail on corner case, like a interval of 1 day or, I believe, anything lower then a full week (or lower then 6 days if you allowed partials).</p>
0
2009-05-19T16:09:02Z
[ "python", "date", "date-arithmetic" ]
Given a date range how to calculate the number of weekends partially or wholly within that range?
883,615
<p>Given a date range how to calculate the number of weekends partially or wholly within that range?</p> <p>(A few definitions as requested: take 'weekend' to mean Saturday and Sunday. The date range is inclusive i.e. the end date is part of the range 'wholly or partially' means that any part of the weekend falling within the date range means the whole weekend is counted.)</p> <p>To simplify I imagine you only actually need to know the duration and what day of the week the initial day is...</p> <p>I darn well now it's going to involve doing integer division by 7 and some logic to add 1 depending on the remainder but I can't quite work out what...</p> <p>extra points for answers in Python ;-) </p> <p><strong>Edit</strong></p> <p>Here's my final code.</p> <p>Weekends are Friday and Saturday (as we are counting nights stayed) and days are 0-indexed starting from Monday. I used onebyone's algorithm and Tom's code layout. Thanks a lot folks.</p> <pre><code>def calc_weekends(start_day, duration): days_until_weekend = [5, 4, 3, 2, 1, 1, 6] adjusted_duration = duration - days_until_weekend[start_day] if adjusted_duration &lt; 0: weekends = 0 else: weekends = (adjusted_duration/7)+1 if start_day == 5 and duration % 7 == 0: #Saturday to Saturday is an exception weekends += 1 return weekends if __name__ == "__main__": days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] for start_day in range(0,7): for duration in range(1,16): print "%s to %s (%s days): %s weekends" % (days[start_day], days[(start_day+duration) % 7], duration, calc_weekends(start_day, duration)) print </code></pre>
1
2009-05-19T15:58:57Z
883,744
<p>General approach for this kind of thing:</p> <p>For each day of the week, figure out how many days are required before a period starting on that day "contains a weekend". For instance, if "contains a weekend" means "contains both the Saturday and the Sunday", then we have the following table:</p> <p>Sunday: 8 Monday: 7 Tuesday: 6 Wednesday: 5 Thursday: 4 Friday: 3 Saturday: 2</p> <p>For "partially or wholly", we have:</p> <p>Sunday: 1 Monday: 6 Tuesday: 5 Wednesday: 4 Thursday: 3 Friday: 2 Saturday: 1</p> <p>Obviously this doesn't have to be coded as a table, now that it's obvious what it looks like.</p> <p>Then, given the day-of-week of the start of your period, subtract[*] the magic value from the length of the period in days (probably start-end+1, to include both fenceposts). If the result is less than 0, it contains 0 weekends. If it is equal to or greater than 0, then it contains (at least) 1 weekend.</p> <p>Then you have to deal with the remaining days. In the first case this is easy, one extra weekend per full 7 days. This is also true in the second case for every starting day except Sunday, which only requires 6 more days to include another weekend. So in the second case for periods starting on Sunday you could count 1 weekend at the start of the period, then subtract 1 from the length and recalculate from Monday.</p> <p>More generally, what's happening here for "whole or part" weekends is that we're checking to see whether we start midway through the interesting bit (the "weekend"). If so, we can either:</p> <ul> <li>1) Count one, move the start date to the end of the interesting bit, and recalculate.</li> <li>2) Move the start date back to the beginning of the interesting bit, and recalculate.</li> </ul> <p>In the case of weekends, there's only one special case which starts midway, so (1) looks good. But if you were getting the date as a date+time in seconds rather than day, or if you were interested in 5-day working weeks rather than 2-day weekends, then (2) might be simpler to understand.</p> <p>[*] Unless you're using unsigned types, of course.</p>
5
2009-05-19T16:19:16Z
[ "python", "date", "date-arithmetic" ]
Given a date range how to calculate the number of weekends partially or wholly within that range?
883,615
<p>Given a date range how to calculate the number of weekends partially or wholly within that range?</p> <p>(A few definitions as requested: take 'weekend' to mean Saturday and Sunday. The date range is inclusive i.e. the end date is part of the range 'wholly or partially' means that any part of the weekend falling within the date range means the whole weekend is counted.)</p> <p>To simplify I imagine you only actually need to know the duration and what day of the week the initial day is...</p> <p>I darn well now it's going to involve doing integer division by 7 and some logic to add 1 depending on the remainder but I can't quite work out what...</p> <p>extra points for answers in Python ;-) </p> <p><strong>Edit</strong></p> <p>Here's my final code.</p> <p>Weekends are Friday and Saturday (as we are counting nights stayed) and days are 0-indexed starting from Monday. I used onebyone's algorithm and Tom's code layout. Thanks a lot folks.</p> <pre><code>def calc_weekends(start_day, duration): days_until_weekend = [5, 4, 3, 2, 1, 1, 6] adjusted_duration = duration - days_until_weekend[start_day] if adjusted_duration &lt; 0: weekends = 0 else: weekends = (adjusted_duration/7)+1 if start_day == 5 and duration % 7 == 0: #Saturday to Saturday is an exception weekends += 1 return weekends if __name__ == "__main__": days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] for start_day in range(0,7): for duration in range(1,16): print "%s to %s (%s days): %s weekends" % (days[start_day], days[(start_day+duration) % 7], duration, calc_weekends(start_day, duration)) print </code></pre>
1
2009-05-19T15:58:57Z
884,037
<p>To count whole weekends, just adjust the number of days so that you start on a Monday, then divide by seven. (Note that if the start day is a weekday, add days to move to the previous Monday, and if it is on a weekend, subtract days to move to the next Monday since you already missed this weekend.)</p> <pre><code>days = {"Saturday":-2, "Sunday":-1, "Monday":0, "Tuesday":1, "Wednesday":2, "Thursday":3, "Friday":4} def n_full_weekends(n_days, start_day): n_days += days[start_day] if n_days &lt;= 0: n_weekends = 0 else: n_weekends = n_days//7 return n_weekends if __name__ == "__main__": tests = [("Tuesday", 10, 1), ("Monday", 7, 1), ("Wednesday", 21, 3), ("Saturday", 1, 0), ("Friday", 1, 0), ("Friday", 3, 1), ("Wednesday", 3, 0), ("Sunday", 8, 1), ("Sunday", 21, 2)] for start_day, n_days, expected in tests: print start_day, n_days, expected, n_full_weekends(n_days, start_day) </code></pre> <p>If you want to know partial weekends (or weeks), just look at the fractional part of the division by seven.</p>
1
2009-05-19T17:20:36Z
[ "python", "date", "date-arithmetic" ]
Given a date range how to calculate the number of weekends partially or wholly within that range?
883,615
<p>Given a date range how to calculate the number of weekends partially or wholly within that range?</p> <p>(A few definitions as requested: take 'weekend' to mean Saturday and Sunday. The date range is inclusive i.e. the end date is part of the range 'wholly or partially' means that any part of the weekend falling within the date range means the whole weekend is counted.)</p> <p>To simplify I imagine you only actually need to know the duration and what day of the week the initial day is...</p> <p>I darn well now it's going to involve doing integer division by 7 and some logic to add 1 depending on the remainder but I can't quite work out what...</p> <p>extra points for answers in Python ;-) </p> <p><strong>Edit</strong></p> <p>Here's my final code.</p> <p>Weekends are Friday and Saturday (as we are counting nights stayed) and days are 0-indexed starting from Monday. I used onebyone's algorithm and Tom's code layout. Thanks a lot folks.</p> <pre><code>def calc_weekends(start_day, duration): days_until_weekend = [5, 4, 3, 2, 1, 1, 6] adjusted_duration = duration - days_until_weekend[start_day] if adjusted_duration &lt; 0: weekends = 0 else: weekends = (adjusted_duration/7)+1 if start_day == 5 and duration % 7 == 0: #Saturday to Saturday is an exception weekends += 1 return weekends if __name__ == "__main__": days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] for start_day in range(0,7): for duration in range(1,16): print "%s to %s (%s days): %s weekends" % (days[start_day], days[(start_day+duration) % 7], duration, calc_weekends(start_day, duration)) print </code></pre>
1
2009-05-19T15:58:57Z
2,815,480
<p>My general approach for this sort of thing: don't start messing around trying to reimplement your own date logic - it's hard, ie. you'll screw it up for the edge cases and look bad. <strong>Hint:</strong> if you have mod 7 arithmetic anywhere in your program, or are treating dates as integers anywhere in your program: <strong><em>you fail</em></strong>. If I saw the "accepted solution" anywhere in (or even near) my codebase, someone would need to start over. It beggars the imagination that anyone who considers themselves a programmer would vote that answer up.</p> <p>Instead, use the built in date/time logic that comes with Python:</p> <p>First, get a list of all of the days that you're interested in:</p> <pre><code>from datetime import date, timedelta FRI = 5; SAT = 6 # a couple of random test dates now = date.today() start_date = now - timedelta(57) end_date = now - timedelta(13) print start_date, '...', end_date # debug days = [date.fromordinal(d) for d in range( start_date.toordinal(), end_date.toordinal()+1 )] </code></pre> <p>Next, filter down to just the days which are weekends. In your case you're interested in Friday and Saturday nights, which are 5 and 6. (Notice how I'm not trying to roll this part into the previous list comprehension, since that'd be hard to verify as correct).</p> <pre><code>weekend_days = [d for d in days if d.weekday() in (FRI,SAT)] for day in weekend_days: # debug print day, day.weekday() # debug </code></pre> <p>Finally, you want to figure out how many weekends are in your list. This is the tricky part, but there are really only four cases to consider, one for each end for either Friday or Saturday. Concrete examples help make it clearer, plus this is really the sort of thing you want documented in your code:</p> <pre><code>num_weekends = len(weekend_days) // 2 # if we start on Friday and end on Saturday we're ok, # otherwise add one weekend # # F,S|F,S|F,S ==3 and 3we, +0 # F,S|F,S|F ==2 but 3we, +1 # S|F,S|F,S ==2 but 3we, +1 # S|F,S|F ==2 but 3we, +1 ends = (weekend_days[0].weekday(), weekend_days[-1].weekday()) if ends != (FRI, SAT): num_weekends += 1 print num_weekends # your answer </code></pre> <p>Shorter, clearer and easier to understand means that you can have more confidence in your code, and can get on with more interesting problems.</p>
2
2010-05-12T00:59:02Z
[ "python", "date", "date-arithmetic" ]
Optparse: Usage on variable arg callback action does not indicate that extra params are needed
883,679
<p>I have implemented in my python code a callback for variable arguments similar to what can be found here:<br /> hxxp://docs.python.org/library/optparse.html#callback-example-6-variable-arguments</p> <p>Adding the option like this: </p> <pre><code>parser.add_option("-c", "--callback", dest="vararg_attr", action="callback", callback=vararg_callback) </code></pre> <p>The problem is, that there is no indication for the user that the option requires extra input: </p> <pre><code>Options: -h, --help show this help message and exit -c, --callback </code></pre> <p>Is there any way to change optparse's usage so that the usage will print something like: </p> <pre><code>-c=LIST, --callback=LIST </code></pre> <p>Thanks for your help!<br /> Ben</p>
3
2009-05-19T16:10:00Z
883,734
<p>user the <code>metavar</code> keyword argument:</p> <pre><code>parser.add_option("-c", "--callback", dest="vararg_attr", action="callback", callback=vararg_callback, metavar='LIST') </code></pre> <p>Reference: <a href="http://docs.python.org/library/optparse.html" rel="nofollow">http://docs.python.org/library/optparse.html</a></p>
1
2009-05-19T16:17:24Z
[ "python", "callback", "optparse" ]
Optparse: Usage on variable arg callback action does not indicate that extra params are needed
883,679
<p>I have implemented in my python code a callback for variable arguments similar to what can be found here:<br /> hxxp://docs.python.org/library/optparse.html#callback-example-6-variable-arguments</p> <p>Adding the option like this: </p> <pre><code>parser.add_option("-c", "--callback", dest="vararg_attr", action="callback", callback=vararg_callback) </code></pre> <p>The problem is, that there is no indication for the user that the option requires extra input: </p> <pre><code>Options: -h, --help show this help message and exit -c, --callback </code></pre> <p>Is there any way to change optparse's usage so that the usage will print something like: </p> <pre><code>-c=LIST, --callback=LIST </code></pre> <p>Thanks for your help!<br /> Ben</p>
3
2009-05-19T16:10:00Z
884,606
<p>This involves monkeypatching and might not be the best solution. On the other hand, it seems to work.</p> <pre><code>from optparse import OptionParser, Option # Complete hack. Option.ALWAYS_TYPED_ACTIONS += ('callback',) def dostuff(*a): pass parser = OptionParser() parser.add_option("-c", "--callback", dest="filename", action="callback", callback=dostuff, metavar='LIST', help='do stuff', ) (options, args) = parser.parse_args() </code></pre> <p>Output:</p> <pre><code>Usage: opt.py [options] Options: -h, --help show this help message and exit -c LIST, --callback=LIST do stuff </code></pre>
2
2009-05-19T19:30:51Z
[ "python", "callback", "optparse" ]
Optparse: Usage on variable arg callback action does not indicate that extra params are needed
883,679
<p>I have implemented in my python code a callback for variable arguments similar to what can be found here:<br /> hxxp://docs.python.org/library/optparse.html#callback-example-6-variable-arguments</p> <p>Adding the option like this: </p> <pre><code>parser.add_option("-c", "--callback", dest="vararg_attr", action="callback", callback=vararg_callback) </code></pre> <p>The problem is, that there is no indication for the user that the option requires extra input: </p> <pre><code>Options: -h, --help show this help message and exit -c, --callback </code></pre> <p>Is there any way to change optparse's usage so that the usage will print something like: </p> <pre><code>-c=LIST, --callback=LIST </code></pre> <p>Thanks for your help!<br /> Ben</p>
3
2009-05-19T16:10:00Z
32,220,734
<p>optparse does not display the indication for an additional argument if the type is None (default). If you specify type and metavar it is displayed in the help:</p> <pre><code>parser.add_option("-c", "--callback", dest="vararg_attr", type="string", metavar="LIST", action="callback", callback=vararg_callback, help="do stuff") </code></pre> <p>Output:</p> <pre><code>Options: -h, --help show this help message and exit -c LIST, --callback=LIST do stuff </code></pre>
0
2015-08-26T07:43:25Z
[ "python", "callback", "optparse" ]
Custom implementation of "tail -f" functionality in C
883,784
<p><strong>EDIT:</strong> I used, finally, inotify. As stefanB says, inotify is the thing to use. I found a tail clone that uses inotify to implement the -f mode, <a href="http://distanz.ch/inotail/" rel="nofollow">inotail</a>.</p> <p>Original question text:</p> <p>I'm trying to implement the "tail -f" logic in a C project, for prototyping purposes I developed it in python as follow:</p> <pre><code> # A forever loop, each 5 seconds writes a line into file.txt from time import * while 1: sleep(5) file = open("file.txt", "a") file.write("This is a test\n") file.close() </code></pre> <p>The next code follows the eof of file.txt (updated by the code above)</p> <pre><code> # tail -f from time import * file = open("file.txt", "r") file.seek(0, 2) while 1: line = file.readline() if not line: sleep(1) else: print line file.close() </code></pre> <p>All works fine but the C implementation is not working (there are no check-error code). The inclusion of stdio.h, string.h and unistd.h is omitted (the colorization hides the header inclusion code).</p> <pre><code> #define LINE_LEN 256 int main(int argc, char **argv) { FILE *f; char line[LINE_LEN]; f = fopen("file.txt", "r"); fseek(f, 0, SEEK_END); while (1) { fgets(line, LINE_LEN, f); if (strlen(line) == 0) { sleep(1); } else { printf("Readed: %s", line); } } fclose(f); return 0; } </code></pre> <p>Some idea?</p> <p>Is a good idea implement it with a poll() instead the presented solution?.</p> <p>Thanks in advance.</p>
2
2009-05-19T16:27:08Z
883,829
<p>Once a FILE * has seen an error or eof, it has its internal status set so that it continues to return error or eof on subsequent calls. You need to call <code>clearerr(f);</code> after the sleep returns to clear the eof setting and get it to try to read more data from the file.</p>
3
2009-05-19T16:35:20Z
[ "python", "c" ]
Custom implementation of "tail -f" functionality in C
883,784
<p><strong>EDIT:</strong> I used, finally, inotify. As stefanB says, inotify is the thing to use. I found a tail clone that uses inotify to implement the -f mode, <a href="http://distanz.ch/inotail/" rel="nofollow">inotail</a>.</p> <p>Original question text:</p> <p>I'm trying to implement the "tail -f" logic in a C project, for prototyping purposes I developed it in python as follow:</p> <pre><code> # A forever loop, each 5 seconds writes a line into file.txt from time import * while 1: sleep(5) file = open("file.txt", "a") file.write("This is a test\n") file.close() </code></pre> <p>The next code follows the eof of file.txt (updated by the code above)</p> <pre><code> # tail -f from time import * file = open("file.txt", "r") file.seek(0, 2) while 1: line = file.readline() if not line: sleep(1) else: print line file.close() </code></pre> <p>All works fine but the C implementation is not working (there are no check-error code). The inclusion of stdio.h, string.h and unistd.h is omitted (the colorization hides the header inclusion code).</p> <pre><code> #define LINE_LEN 256 int main(int argc, char **argv) { FILE *f; char line[LINE_LEN]; f = fopen("file.txt", "r"); fseek(f, 0, SEEK_END); while (1) { fgets(line, LINE_LEN, f); if (strlen(line) == 0) { sleep(1); } else { printf("Readed: %s", line); } } fclose(f); return 0; } </code></pre> <p>Some idea?</p> <p>Is a good idea implement it with a poll() instead the presented solution?.</p> <p>Thanks in advance.</p>
2
2009-05-19T16:27:08Z
883,831
<p>From the <code>tail</code> <a href="http://www.monkey.org/cgi-bin/man2html?tail" rel="nofollow">man page</a>:</p> <blockquote> <p>-f Do not stop when end-of-file is reached, but rather to wait for additional data to be appended to the input. If the file is replaced (i.e., the inode number changes), tail will reopen the file and continue. If the file is truncated, tail will reset its position to the beginning. This makes tail more useful for watching log files that may get rotated. The -f option is ignored if the standard input is a pipe, but not if it is a FIFO.</p> </blockquote> <p>So, you could do the same thing:</p> <ol> <li>Use <a href="http://linux.die.net/man/2/stat" rel="nofollow">stat()</a> to read the inode number of the file</li> <li>Display the contents of that file. Store the position of the file descriptor eg, p = ftell(fd)</li> <li>Use stat() again, and see if the inode has changed. If so, display the contents of the file from position p onward</li> <li>Repeat </li> </ol>
2
2009-05-19T16:35:27Z
[ "python", "c" ]
Custom implementation of "tail -f" functionality in C
883,784
<p><strong>EDIT:</strong> I used, finally, inotify. As stefanB says, inotify is the thing to use. I found a tail clone that uses inotify to implement the -f mode, <a href="http://distanz.ch/inotail/" rel="nofollow">inotail</a>.</p> <p>Original question text:</p> <p>I'm trying to implement the "tail -f" logic in a C project, for prototyping purposes I developed it in python as follow:</p> <pre><code> # A forever loop, each 5 seconds writes a line into file.txt from time import * while 1: sleep(5) file = open("file.txt", "a") file.write("This is a test\n") file.close() </code></pre> <p>The next code follows the eof of file.txt (updated by the code above)</p> <pre><code> # tail -f from time import * file = open("file.txt", "r") file.seek(0, 2) while 1: line = file.readline() if not line: sleep(1) else: print line file.close() </code></pre> <p>All works fine but the C implementation is not working (there are no check-error code). The inclusion of stdio.h, string.h and unistd.h is omitted (the colorization hides the header inclusion code).</p> <pre><code> #define LINE_LEN 256 int main(int argc, char **argv) { FILE *f; char line[LINE_LEN]; f = fopen("file.txt", "r"); fseek(f, 0, SEEK_END); while (1) { fgets(line, LINE_LEN, f); if (strlen(line) == 0) { sleep(1); } else { printf("Readed: %s", line); } } fclose(f); return 0; } </code></pre> <p>Some idea?</p> <p>Is a good idea implement it with a poll() instead the presented solution?.</p> <p>Thanks in advance.</p>
2
2009-05-19T16:27:08Z
883,843
<p><strong>EDIT</strong>: Seems like <a href="http://www.linuxjournal.com/article/8478" rel="nofollow">inotify</a> is the thing to use. It should be included in linux kernel since 2.6.13 . <a href="http://www.ibm.com/developerworks/linux/library/l-ubuntu-inotify/index.html?ca=drs-" rel="nofollow">An article from IBM developerworks about inotify</a>.</p> <p>Previous answer:</p> <p>Have a look at Linux <a href="http://oss.sgi.com/projects/fam/faq.html" rel="nofollow">File Alteration Monitor</a> (in linux kernels 2.4.x >). It's a framework that let's you subscribe for file changes and you get callback from kernel when change happens. This should be better than polling.</p> <p><a href="http://techpubs.sgi.com/library/tpl/cgi-bin/getdoc.cgi?coll=0650&amp;db=bks&amp;fname=/SGI%5FDeveloper/books/IIDsktp%5FIG/sgi%5Fhtml/ch08.html" rel="nofollow">Examples</a> how to poll for file changes, check out sections <strong>Waiting for file changes</strong> and <strong>Polling for file changes</strong>.</p> <p>I haven't tried it yet.</p>
3
2009-05-19T16:39:54Z
[ "python", "c" ]
datetime.now() in Django application goes bad
883,823
<p>I've had some problems with a Django application after I deployed it. I use a Apache + mod-wsgi on a ubuntu server. A while after I reboot the server the time goes foobar, it's wrong by around -10 hours. I made a Django view that looks like:</p> <pre><code>def servertime(): return HttpResponse( datetime.now() ) </code></pre> <p>and after I reboot the server and check the url that shows that view it first looks alright. Then at one point it sometimes gives the correct time and sometimes not and later it gives the wrong time always. The server time is corect though.</p> <p>Any clues? I've googled it without luck.</p>
5
2009-05-19T16:34:03Z
883,873
<p>Can I see your urls.py as well?</p> <p>Similar behaviors stumped me once before...</p> <p>What it turned out to be was the way that my urls.py called the view. Python ran the datetime.now() once and stored that for future calls, never really calling it again. This is why django devs had to implement the ability to pass a function, not a function call, to a model's default value, because it would take the first call of the function and use that until python is restarted.</p> <p>Your behavior sounds like the first time is correct because its the first time the view was called. It was incorrect at times because it got that same date again. Then it was randomly correct again because your apache probably started another worker process for it, and the craziness probably happens when you get bounced in between which process was handling the request.</p>
6
2009-05-19T16:48:05Z
[ "python", "django", "apache", "datetime", "mod-wsgi" ]
datetime.now() in Django application goes bad
883,823
<p>I've had some problems with a Django application after I deployed it. I use a Apache + mod-wsgi on a ubuntu server. A while after I reboot the server the time goes foobar, it's wrong by around -10 hours. I made a Django view that looks like:</p> <pre><code>def servertime(): return HttpResponse( datetime.now() ) </code></pre> <p>and after I reboot the server and check the url that shows that view it first looks alright. Then at one point it sometimes gives the correct time and sometimes not and later it gives the wrong time always. The server time is corect though.</p> <p>Any clues? I've googled it without luck.</p>
5
2009-05-19T16:34:03Z
885,871
<p>you may need to specify the content type like so</p> <pre><code>def servertime(): return HttpResponse( datetime.now(), content_type="text/plain" ) </code></pre> <p>another idea:</p> <p>it may not be working because datetime.now() returns a datetime object. Try this:</p> <pre><code>def servertime(): return HttpResponse( str(datetime.now()), content_type="text/plain" ) </code></pre>
0
2009-05-20T02:12:41Z
[ "python", "django", "apache", "datetime", "mod-wsgi" ]
datetime.now() in Django application goes bad
883,823
<p>I've had some problems with a Django application after I deployed it. I use a Apache + mod-wsgi on a ubuntu server. A while after I reboot the server the time goes foobar, it's wrong by around -10 hours. I made a Django view that looks like:</p> <pre><code>def servertime(): return HttpResponse( datetime.now() ) </code></pre> <p>and after I reboot the server and check the url that shows that view it first looks alright. Then at one point it sometimes gives the correct time and sometimes not and later it gives the wrong time always. The server time is corect though.</p> <p>Any clues? I've googled it without luck.</p>
5
2009-05-19T16:34:03Z
890,876
<p>Maybe the server is evaluating the datetime.now() at server start, try making it lazy through a template or use a variable in your view.</p> <p>Take a look at this <a href="http://paltman.com/2008/may/07/a-default-bug-in-django/" rel="nofollow">blog post</a>.</p>
1
2009-05-21T00:20:08Z
[ "python", "django", "apache", "datetime", "mod-wsgi" ]
datetime.now() in Django application goes bad
883,823
<p>I've had some problems with a Django application after I deployed it. I use a Apache + mod-wsgi on a ubuntu server. A while after I reboot the server the time goes foobar, it's wrong by around -10 hours. I made a Django view that looks like:</p> <pre><code>def servertime(): return HttpResponse( datetime.now() ) </code></pre> <p>and after I reboot the server and check the url that shows that view it first looks alright. Then at one point it sometimes gives the correct time and sometimes not and later it gives the wrong time always. The server time is corect though.</p> <p>Any clues? I've googled it without luck.</p>
5
2009-05-19T16:34:03Z
1,075,389
<p>I found that putting wsgi in daemon mode works. Not sure why, but it did. Seems like some of the newly created processes gets the time screwed up.</p>
5
2009-07-02T16:32:36Z
[ "python", "django", "apache", "datetime", "mod-wsgi" ]
datetime.now() in Django application goes bad
883,823
<p>I've had some problems with a Django application after I deployed it. I use a Apache + mod-wsgi on a ubuntu server. A while after I reboot the server the time goes foobar, it's wrong by around -10 hours. I made a Django view that looks like:</p> <pre><code>def servertime(): return HttpResponse( datetime.now() ) </code></pre> <p>and after I reboot the server and check the url that shows that view it first looks alright. Then at one point it sometimes gives the correct time and sometimes not and later it gives the wrong time always. The server time is corect though.</p> <p>Any clues? I've googled it without luck.</p>
5
2009-05-19T16:34:03Z
2,817,400
<p>Django sets the system time zone based on your settings variable TIME_ZONE. This may lead to all kinds of confusion when running multiple Django instances with different TIME_ZONE settings.</p> <p>This is what Django does:</p> <pre><code>os.environ['TZ'] = self.TIME_ZONE </code></pre> <p>The above answer:</p> <blockquote> <p>"I found that putting wsgi in daemon mode works"</p> </blockquote> <p>does not work for me...</p> <p>I think I'm going with not using django's built in TIME_ZONE anymore.</p>
1
2010-05-12T09:18:48Z
[ "python", "django", "apache", "datetime", "mod-wsgi" ]
datetime.now() in Django application goes bad
883,823
<p>I've had some problems with a Django application after I deployed it. I use a Apache + mod-wsgi on a ubuntu server. A while after I reboot the server the time goes foobar, it's wrong by around -10 hours. I made a Django view that looks like:</p> <pre><code>def servertime(): return HttpResponse( datetime.now() ) </code></pre> <p>and after I reboot the server and check the url that shows that view it first looks alright. Then at one point it sometimes gives the correct time and sometimes not and later it gives the wrong time always. The server time is corect though.</p> <p>Any clues? I've googled it without luck.</p>
5
2009-05-19T16:34:03Z
8,403,828
<p>datetime.now() is probably being evaluated once, when your class is instantiated. Try removing the parenthesis so that the function datetime.now is returned and THEN evaluated. I had a similar issue with setting default values for my DateTimeFields and wrote up my solution <a href="http://david.feinzeig.com/blog/2011/12/06/how-to-properly-set-a-default-value-for-a-datetimefield-in-django/" rel="nofollow">here</a>.</p>
2
2011-12-06T17:06:24Z
[ "python", "django", "apache", "datetime", "mod-wsgi" ]