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
In Django, How do I get escaped html in HttpResponse?
1,946,281
<p>The following code in one of my views returns unescaped html string which cannot be parsed in frontend since it is an Ajax request.</p> <pre><code>return render_to_response(template_name, { 'form': form, redirect_field_name: redirect_to, 'site': current_site, 'site_name': current_sit...
4
2009-12-22T13:07:26Z
1,946,320
<p>To return just plain HTML to the client from within your view, use <code>django.http.HttpResponse</code></p> <pre><code>from django.http import HttpResponse def view(request) # Do stuff here output = ''' &lt;html&gt; &lt;head&gt; &lt;title&gt;Hey mum!&lt;/title&gt; &lt;/head...
4
2009-12-22T13:16:11Z
[ "python", "django", "django-templates", "escaping", "httpresponse" ]
In Django, How do I get escaped html in HttpResponse?
1,946,281
<p>The following code in one of my views returns unescaped html string which cannot be parsed in frontend since it is an Ajax request.</p> <pre><code>return render_to_response(template_name, { 'form': form, redirect_field_name: redirect_to, 'site': current_site, 'site_name': current_sit...
4
2009-12-22T13:07:26Z
1,946,799
<p>It should escape by default.</p> <p>But, if you want to, you can explicitly force escaping.</p> <pre><code>from django.utils.safestring import mark_for_escaping return HttpResponse(mark_for_escaping(loader.render_to_string(""""Render Response Syntax""")) </code></pre>
1
2009-12-22T14:45:55Z
[ "python", "django", "django-templates", "escaping", "httpresponse" ]
In Django, How do I get escaped html in HttpResponse?
1,946,281
<p>The following code in one of my views returns unescaped html string which cannot be parsed in frontend since it is an Ajax request.</p> <pre><code>return render_to_response(template_name, { 'form': form, redirect_field_name: redirect_to, 'site': current_site, 'site_name': current_sit...
4
2009-12-22T13:07:26Z
11,558,474
<p><strong>Lakshman Prasad</strong>'s answer is technically correct, but a bit cumbersome. A better way to <em>escape</em> text would be (as suggested in a comment by <strong>miku</strong> above):</p> <pre><code>from django.utils.html import escape return HttpResponse(escape(some_string)) </code></pre>
10
2012-07-19T10:06:39Z
[ "python", "django", "django-templates", "escaping", "httpresponse" ]
Making Python code Pythonic
1,946,701
<p><strong>How would you make the give code more Pythonic?</strong></p> <p>I want to get Paths out of the sample like <code>/usr/local/sources/devel/algebra.py: def _alg(...)</code> without the character <code>:</code>.</p> <p><strong>My code</strong></p> <pre><code>import os FunctionPath = "/usr/local/sources/devel...
0
2009-12-22T14:30:04Z
1,946,742
<p>Why not do this:</p> <pre><code>for line in open(FunctionPath): line = line.strip() if line.startswith('def '): print '%s: %s' % (FunctionPath, line.partition(':')[0]) </code></pre> <p>And if you use <a href="http://docs.python.org/library/fileinput.html">fileinput</a> module you can iterate over l...
11
2009-12-22T14:36:34Z
[ "python" ]
Making Python code Pythonic
1,946,701
<p><strong>How would you make the give code more Pythonic?</strong></p> <p>I want to get Paths out of the sample like <code>/usr/local/sources/devel/algebra.py: def _alg(...)</code> without the character <code>:</code>.</p> <p><strong>My code</strong></p> <pre><code>import os FunctionPath = "/usr/local/sources/devel...
0
2009-12-22T14:30:04Z
1,946,779
<p>Literaly: "without the modules os, subprocess or Popen"</p> <p>You can also use <a href="http://docs.python.org/library/commands.html#commands.getoutput" rel="nofollow">commands</a> module :P</p>
1
2009-12-22T14:42:16Z
[ "python" ]
Making Python code Pythonic
1,946,701
<p><strong>How would you make the give code more Pythonic?</strong></p> <p>I want to get Paths out of the sample like <code>/usr/local/sources/devel/algebra.py: def _alg(...)</code> without the character <code>:</code>.</p> <p><strong>My code</strong></p> <pre><code>import os FunctionPath = "/usr/local/sources/devel...
0
2009-12-22T14:30:04Z
1,946,815
<p><strong>Same with os.walk</strong></p> <pre><code>for path, dirnames, filenames in os.walk(function_path): for filename in filenames: path = os.path.join(path, filename) with open(path) as f: for line in f: # Instead of grep if 'def ' in line: ...
1
2009-12-22T14:47:52Z
[ "python" ]
Making Python code Pythonic
1,946,701
<p><strong>How would you make the give code more Pythonic?</strong></p> <p>I want to get Paths out of the sample like <code>/usr/local/sources/devel/algebra.py: def _alg(...)</code> without the character <code>:</code>.</p> <p><strong>My code</strong></p> <pre><code>import os FunctionPath = "/usr/local/sources/devel...
0
2009-12-22T14:30:04Z
1,946,832
<p>If you're using Python mainly as a wrapper to sh, why not doing everything directly from the shell?</p> <pre><code>set SEARCH_PATH=/usr/local/sources/devel/sage-main/build/sage/ grep -R 'def ' $SEARCH_PATH | awk -F':' '{print $1 $2}' </code></pre>
1
2009-12-22T14:50:20Z
[ "python" ]
How does the Python conditional operator workaround work?
1,947,030
<p>From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).</p> <p>I found the following code as a substitute:</p> <pre><code>def val(): var = float(raw_input("Age:")) status = ("Working","Retired")[var&gt;65] print "You should be:",status </...
21
2009-12-22T15:22:26Z
1,947,050
<p>Python (2.5 and above) does indeed have a syntax for what you are looking for:</p> <pre><code>x = foo if condition else bar </code></pre> <p>If <code>condition</code> is True, <code>x</code> will be set to <code>foo</code>, otherwise it will be set to <code>bar</code>.</p> <p>Examples:</p> <pre><code>&gt;&gt;&gt...
9
2009-12-22T15:24:40Z
[ "python", "indexing", "boolean", "conditional-operator" ]
How does the Python conditional operator workaround work?
1,947,030
<p>From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).</p> <p>I found the following code as a substitute:</p> <pre><code>def val(): var = float(raw_input("Age:")) status = ("Working","Retired")[var&gt;65] print "You should be:",status </...
21
2009-12-22T15:22:26Z
1,947,085
<p>In Python 2.6 and up:</p> <pre><code>print "You should be {0}.".format("retired" if var&gt;65 else "working") </code></pre> <p>In Python 3.1 and up:</p> <pre><code>print ("You should be {}.".format("retired" if var&gt;65 else "working")) </code></pre>
0
2009-12-22T15:29:43Z
[ "python", "indexing", "boolean", "conditional-operator" ]
How does the Python conditional operator workaround work?
1,947,030
<p>From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).</p> <p>I found the following code as a substitute:</p> <pre><code>def val(): var = float(raw_input("Age:")) status = ("Working","Retired")[var&gt;65] print "You should be:",status </...
21
2009-12-22T15:22:26Z
1,947,102
<p>because True casts to 1 and False casts to 0 so if var = 70</p> <pre><code>("Working","Retired")[var&gt;65] </code></pre> <p>becomes</p> <pre><code>("Working", "Retired")[1] </code></pre> <p>a nice little shortcut ... but I find it can be a little confusing with anything but a simple condition, so I would go wit...
8
2009-12-22T15:31:01Z
[ "python", "indexing", "boolean", "conditional-operator" ]
How does the Python conditional operator workaround work?
1,947,030
<p>From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).</p> <p>I found the following code as a substitute:</p> <pre><code>def val(): var = float(raw_input("Age:")) status = ("Working","Retired")[var&gt;65] print "You should be:",status </...
21
2009-12-22T15:22:26Z
1,947,107
<p>in the code that you posted the following line is emulating ternary:</p> <pre><code>status = ("Working","Retired")[var&gt;65] </code></pre> <p>here tuple <code>("Working","Retired")</code> accessed with an index <code>[var&gt;65]</code> which evaluates to either <code>True</code> (<code>1</code>) or <code>False</c...
0
2009-12-22T15:31:28Z
[ "python", "indexing", "boolean", "conditional-operator" ]
How does the Python conditional operator workaround work?
1,947,030
<p>From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).</p> <p>I found the following code as a substitute:</p> <pre><code>def val(): var = float(raw_input("Age:")) status = ("Working","Retired")[var&gt;65] print "You should be:",status </...
21
2009-12-22T15:22:26Z
1,947,109
<p>Python has a construct that is sort of like the ternary operator in C, et al. It works something like this:</p> <pre><code>my_var = "Retired" if age &gt; 65 else "Working" </code></pre> <p>and is equivalent to this C code:</p> <pre><code>my_var = age &gt; 65 ? "Retired" : "Working"; </code></pre> <p>As for how t...
51
2009-12-22T15:31:54Z
[ "python", "indexing", "boolean", "conditional-operator" ]
How does the Python conditional operator workaround work?
1,947,030
<p>From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).</p> <p>I found the following code as a substitute:</p> <pre><code>def val(): var = float(raw_input("Age:")) status = ("Working","Retired")[var&gt;65] print "You should be:",status </...
21
2009-12-22T15:22:26Z
1,947,113
<p>this is the form with the python ternary operator</p> <pre><code>def val(): var = float(raw_input("Age:")) status = "Retired" if var &gt; 65 else "Working" print "You should be:",status </code></pre> <p>the code you showed is a bit tricky: it creates a two elements tuple whose elements are at position ...
0
2009-12-22T15:32:16Z
[ "python", "indexing", "boolean", "conditional-operator" ]
How does the Python conditional operator workaround work?
1,947,030
<p>From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).</p> <p>I found the following code as a substitute:</p> <pre><code>def val(): var = float(raw_input("Age:")) status = ("Working","Retired")[var&gt;65] print "You should be:",status </...
21
2009-12-22T15:22:26Z
1,947,120
<p>There was originally no ternary operator because "Explicit is better than implicit", and it was seen as unpythonic. I don't like python's ternary op too much, either, but it exists:</p> <pre><code>x = foo if condition else bar </code></pre> <p>as shown by TM.</p> <p>As for <code>status = ("Working","Retired")[var...
0
2009-12-22T15:32:52Z
[ "python", "indexing", "boolean", "conditional-operator" ]
How does the Python conditional operator workaround work?
1,947,030
<p>From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).</p> <p>I found the following code as a substitute:</p> <pre><code>def val(): var = float(raw_input("Age:")) status = ("Working","Retired")[var&gt;65] print "You should be:",status </...
21
2009-12-22T15:22:26Z
1,947,132
<pre><code>status = ("Working","Retired")[var&gt;65] </code></pre> <p>This line works as a ternary operator because the expression <code>var&gt;65</code> returns 1 or 0, depending on whether <code>var</code> is bigger than 65 or not. So if <code>var&gt;65</code>, then the line becomes this:</p> <pre><code>status = (...
0
2009-12-22T15:34:53Z
[ "python", "indexing", "boolean", "conditional-operator" ]
How does the Python conditional operator workaround work?
1,947,030
<p>From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).</p> <p>I found the following code as a substitute:</p> <pre><code>def val(): var = float(raw_input("Age:")) status = ("Working","Retired")[var&gt;65] print "You should be:",status </...
21
2009-12-22T15:22:26Z
1,947,136
<p>Only the "status =" line of that code implements something like the ternary operator.</p> <pre><code>status = ("Working","Retired")[var&gt;65] </code></pre> <p>This creates a two-element tuple, with strings 'Working' at index 0, and 'Retired' at index 1. Following this, it indexes into that tuple to pick one of t...
0
2009-12-22T15:35:37Z
[ "python", "indexing", "boolean", "conditional-operator" ]
How does the Python conditional operator workaround work?
1,947,030
<p>From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).</p> <p>I found the following code as a substitute:</p> <pre><code>def val(): var = float(raw_input("Age:")) status = ("Working","Retired")[var&gt;65] print "You should be:",status </...
21
2009-12-22T15:22:26Z
1,947,155
<p>trying to give a complete answer based on the answers given here.</p> <p>the way you found (please don't use this one because it is not very readable):</p> <pre><code>def val(): var = float(raw_input("Age:")) status = ("Working","Retired")[var&gt;65] print "You should be:",status </code></pre> <p>usin...
0
2009-12-22T15:39:14Z
[ "python", "indexing", "boolean", "conditional-operator" ]
How does the Python conditional operator workaround work?
1,947,030
<p>From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).</p> <p>I found the following code as a substitute:</p> <pre><code>def val(): var = float(raw_input("Age:")) status = ("Working","Retired")[var&gt;65] print "You should be:",status </...
21
2009-12-22T15:22:26Z
1,948,943
<h3>indexing into a list</h3> <p>The use of</p> <pre><code>[expression_when_false, expression_when_true][condition] # or (expression_when_false, expression_when_true)[condition] </code></pre> <p>takes advantage of the fact that in Python True equals (but isn't!) 1 and False equals (but isn't!) 0. The expression abov...
6
2009-12-22T20:32:04Z
[ "python", "indexing", "boolean", "conditional-operator" ]
How does the Python conditional operator workaround work?
1,947,030
<p>From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).</p> <p>I found the following code as a substitute:</p> <pre><code>def val(): var = float(raw_input("Age:")) status = ("Working","Retired")[var&gt;65] print "You should be:",status </...
21
2009-12-22T15:22:26Z
1,969,011
<h2>Short-circuit boolean expressions</h2> <p>There is also an option to short-circuit logical operations:</p> <pre><code>&gt;&gt;&gt; (2+2 == 4) and "Yes" or "No" 'Yes' &gt;&gt;&gt; (2+2 == 5) and "Yes" or "No" 'No' </code></pre> <p>In your example:</p> <pre><code>&gt;&gt;&gt; (int(raw_input("Age: ")) &gt; 65) and...
2
2009-12-28T11:17:44Z
[ "python", "indexing", "boolean", "conditional-operator" ]
select object to edit
1,947,067
<p>I have a simple view function that's designed to allow the user to choose from items listed in an html table (records). Clicking on a record should divert the user to the template from which he can edit that specific record. The code is as follows:</p> <pre><code>def edit_record(request): if request.method ...
0
2009-12-22T15:26:33Z
1,947,114
<p>Without more information it is hard to tell what you need to change, but your guess is correct, the problem is with your <code>ProjectRecord.objects.get()</code> call. </p> <p>You should be passing some sort of information to get in order to limit the list down to one.</p> <p>In most cases, you will need:</p> <pr...
0
2009-12-22T15:32:17Z
[ "python", "django", "django-views" ]
select object to edit
1,947,067
<p>I have a simple view function that's designed to allow the user to choose from items listed in an html table (records). Clicking on a record should divert the user to the template from which he can edit that specific record. The code is as follows:</p> <pre><code>def edit_record(request): if request.method ...
0
2009-12-22T15:26:33Z
1,947,119
<p>The important thing about <code>get</code> is "get what?"</p> <p>When you say</p> <pre><code>a=ProjectRecord.objects.get() </code></pre> <p>you neglected to provide any selection criteria. Which row do you want from the database?</p> <p>Which row? Hmmmm... How does the <code>GET</code> transaction know which r...
2
2009-12-22T15:32:48Z
[ "python", "django", "django-views" ]
urllib2.urlopen() vs urllib.urlopen() - urllib2 throws 404 while urllib works! WHY?
1,947,133
<pre><code>import urllib print urllib.urlopen('http://www.reefgeek.com/equipment/Controllers_&amp;_Monitors/Neptune_Systems_AquaController/Apex_Controller_&amp;_Accessories/').read() </code></pre> <p>The above script works and returns the expected results while:</p> <pre><code>import urllib2 print urllib2.urlopen('...
15
2009-12-22T15:34:59Z
1,947,232
<p>That URL does indeed result in a 404, but with lots of HTML content. <code>urllib2</code> is handling it (correctly) as an error condition. You can recover the content of that site's 404 page like so:</p> <pre><code>import urllib2 try: print urllib2.urlopen('http://www.reefgeek.com/equipment/Controllers_&amp;_M...
34
2009-12-22T15:50:59Z
[ "python", "url", "http-status-code-404", "urllib2", "urllib" ]
Django - Using trees to build a comment system
1,947,176
<p>A few days back I was messing around with Django, trying to get a feel for how stuff works, when I decided to try and build a simple forum, one that resembled a forum that I frequented (but is now closed down). The idea was that each of the comments would be parent to any number of comments, like so:</p> <pre><code...
0
2009-12-22T15:42:48Z
1,947,366
<p>I would only define the parent and give it a related name</p> <pre><code>class Comment(models.Model): parent=models.ForeignKey('self', related_name="children", null=True, blank=True) #other fields </code></pre> <p>Then you could get its children</p> <pre><code>comment=Comment.objects.get(id=1) children=commen...
1
2009-12-22T16:12:22Z
[ "python", "django", "tree" ]
Django - Using trees to build a comment system
1,947,176
<p>A few days back I was messing around with Django, trying to get a feel for how stuff works, when I decided to try and build a simple forum, one that resembled a forum that I frequented (but is now closed down). The idea was that each of the comments would be parent to any number of comments, like so:</p> <pre><code...
0
2009-12-22T15:42:48Z
1,947,452
<p>Have a look at <a href="http://github.com/ericflo/django-threadedcomments" rel="nofollow">django-threadedcomments</a>. It's purpose is more fit to be used as comments on a blog than a full featured forum, but if it doesn't fit your case, you can at least look at the source code and learn a couple things from it.</p>...
2
2009-12-22T16:24:13Z
[ "python", "django", "tree" ]
fastcgi, cherrypy, and python
1,947,344
<p>So I'm trying to do more web development in python, and I've picked cherrypy, hosted by lighttpd w/ fastcgi. But my question is a very basic one: why do I need to restart lighttpd (or apache) every time I change my application code, or the code for an underlying library?</p> <p>I realize this question extends from ...
5
2009-12-22T16:09:21Z
1,947,457
<p><strong>From a system-software-writer's pointer of view:</strong> This all depends on how the meta-data about the server process is organized within your daemon (lighttpd or fcgi). Some programs are designed for one time only initialization -- <strong>MOSTLY</strong> this allows a much simpler and better performing ...
0
2009-12-22T16:24:41Z
[ "python", "fastcgi", "lighttpd", "cherrypy" ]
fastcgi, cherrypy, and python
1,947,344
<p>So I'm trying to do more web development in python, and I've picked cherrypy, hosted by lighttpd w/ fastcgi. But my question is a very basic one: why do I need to restart lighttpd (or apache) every time I change my application code, or the code for an underlying library?</p> <p>I realize this question extends from ...
5
2009-12-22T16:09:21Z
1,947,512
<p>This is because of performance. For development, autoreloading is helpful. But for production, you <em>don't</em> want to autoreload. This is actually a decently-sized bottleneck in say PHP. Every time you access a PHP webpage, the server has to parse and load each page from scratch. With Python, the script is ...
8
2009-12-22T16:33:44Z
[ "python", "fastcgi", "lighttpd", "cherrypy" ]
buildbot: run SVNPoller with --trust-server-cert
1,947,508
<p>I asked <a href="http://stackoverflow.com/questions/1908856/buildbot-run-svn-with-trust-server-cert">this similar</a> question and got a satisfactory answer. However, doing the same with SVNPoller doesn't work.</p> <p>So how can I pass <code>--trust-server-cert</code> as an extra param to SVNPoller in buildbot </p>...
1
2009-12-22T16:33:08Z
1,979,238
<pre><code>class MyPoller(SVNPoller): def __init__(...): SVNPoller.__init__(self, ...) def getProcessOutput(self, args): args += ["--trust-server-cert"] return SVNPoller.getProcessOutput(self, args) </code></pre>
0
2009-12-30T09:22:07Z
[ "python", "svn", "project-management", "build-process", "buildbot" ]
buildbot: run SVNPoller with --trust-server-cert
1,947,508
<p>I asked <a href="http://stackoverflow.com/questions/1908856/buildbot-run-svn-with-trust-server-cert">this similar</a> question and got a satisfactory answer. However, doing the same with SVNPoller doesn't work.</p> <p>So how can I pass <code>--trust-server-cert</code> as an extra param to SVNPoller in buildbot </p>...
1
2009-12-22T16:33:08Z
2,268,440
<p>Use extra_args if specified, an array of strings that will be passed as extra arguments to the svn binary.</p>
0
2010-02-15T19:37:03Z
[ "python", "svn", "project-management", "build-process", "buildbot" ]
python email error
1,947,701
<p>I am trying to email a results file. I am getting an import error: </p> <pre><code>Traceback (most recent call last): File "email_results.py", line 5, in ? from email import encoders ImportError: cannot import name encoders </code></pre> <p>I am also unsure on how to get this to connect to the server....
2
2009-12-22T16:58:43Z
1,947,769
<p>The problem isn't that you can't connect to the server, it's that you aren't able to import email.encoders for some reason. Do you have a file named email.py or email.pyc by any chance?</p>
7
2009-12-22T17:08:11Z
[ "python" ]
Does Python support MySQL prepared statements?
1,947,750
<p>I worked on a PHP project earlier where prepared statements made the SELECT queries 20% faster.</p> <p>I'm wondering if it works on Python? I can't seem to find anything that specifically says it does or does NOT.</p>
37
2009-12-22T17:06:46Z
1,947,993
<p>Most languages provide a way to do generic parameterized statements, Python is no different. When a parameterized query is used databases that support preparing statements will automatically do so.</p> <p>In python a parameterized query looks like this:</p> <pre><code>cursor.execute("SELECT FROM tablename WHERE f...
42
2009-12-22T17:40:05Z
[ "python", "mysql", "prepared-statement" ]
Does Python support MySQL prepared statements?
1,947,750
<p>I worked on a PHP project earlier where prepared statements made the SELECT queries 20% faster.</p> <p>I'm wondering if it works on Python? I can't seem to find anything that specifically says it does or does NOT.</p>
37
2009-12-22T17:06:46Z
1,948,037
<p>Not directly related, but <a href="http://stackoverflow.com/questions/283645/python-list-in-sql-query-as-parameter/283801#283801">this answer</a> to another question at SO includes the syntax details of 'templated' queries. I'd say that the auto-escaping would be their most important feature...</p> <p>As for perfor...
1
2009-12-22T17:47:31Z
[ "python", "mysql", "prepared-statement" ]
Does Python support MySQL prepared statements?
1,947,750
<p>I worked on a PHP project earlier where prepared statements made the SELECT queries 20% faster.</p> <p>I'm wondering if it works on Python? I can't seem to find anything that specifically says it does or does NOT.</p>
37
2009-12-22T17:06:46Z
1,948,130
<p>After a quick look through an execute() method of a Cursor object of a MySQLdb package (a kind of de-facto package for integrating with mysql, I guess), it seems, that (at least by default) it only does string interpolation and quoting and not the actual parametrized query:</p> <pre><code>if args is not None: q...
11
2009-12-22T18:04:14Z
[ "python", "mysql", "prepared-statement" ]
Does Python support MySQL prepared statements?
1,947,750
<p>I worked on a PHP project earlier where prepared statements made the SELECT queries 20% faster.</p> <p>I'm wondering if it works on Python? I can't seem to find anything that specifically says it does or does NOT.</p>
37
2009-12-22T17:06:46Z
2,539,467
<p>Using the SQL Interface as suggested by Amit can work if you're only concerned about performance. However, you then lose the protection against SQL injection that a native Python support for prepared statements could bring. Python 3 has modules that provide prepared statement support for PostgreSQL. For MySQL, "o...
5
2010-03-29T16:13:43Z
[ "python", "mysql", "prepared-statement" ]
Does Python support MySQL prepared statements?
1,947,750
<p>I worked on a PHP project earlier where prepared statements made the SELECT queries 20% faster.</p> <p>I'm wondering if it works on Python? I can't seem to find anything that specifically says it does or does NOT.</p>
37
2009-12-22T17:06:46Z
17,237,567
<p><strong>Direct answer, no it doesn't.</strong></p> <p><a href="http://stackoverflow.com/a/1947993/20774">joshperry's answer</a> is a good explanation of what it does instead.</p> <p>From <a href="http://stackoverflow.com/questions/2424531/does-the-mysqldb-module-support-prepared-statements/2425500#2425500">eugene ...
10
2013-06-21T14:18:19Z
[ "python", "mysql", "prepared-statement" ]
Does Python support MySQL prepared statements?
1,947,750
<p>I worked on a PHP project earlier where prepared statements made the SELECT queries 20% faster.</p> <p>I'm wondering if it works on Python? I can't seem to find anything that specifically says it does or does NOT.</p>
37
2009-12-22T17:06:46Z
31,979,062
<p>For people just trying to figure this out, <strong>YES</strong> you can use prepared statements with Python and MySQL. Just use MySQL Connector/Python from MySQL itself and instantiate the right cursor:</p> <p><a href="https://dev.mysql.com/doc/connector-python/en/index.html" rel="nofollow">https://dev.mysql.com/do...
3
2015-08-13T03:32:09Z
[ "python", "mysql", "prepared-statement" ]
Does Python support MySQL prepared statements?
1,947,750
<p>I worked on a PHP project earlier where prepared statements made the SELECT queries 20% faster.</p> <p>I'm wondering if it works on Python? I can't seem to find anything that specifically says it does or does NOT.</p>
37
2009-12-22T17:06:46Z
35,503,524
<p>There is a Solution!</p> <p>You can use them if you put them into a stored procedure on the server and call them like this from python... </p> <pre><code>cursor.callproc(Procedurename, args) </code></pre> <p>Here is a nice little tutorial on Stored procedures in mysql and python.</p> <p><a href="http://www.mysql...
0
2016-02-19T10:52:54Z
[ "python", "mysql", "prepared-statement" ]
authenticate returns nothing
1,947,811
<p>what im experimenting is the next:</p> <pre><code>S:\proj&gt;manage.py shell Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) django 1.1.1 &gt;&gt;&gt; from django.contrib.auth.models import User &gt;&gt;&gt; u = User(username='luis', password='admin') &gt;&gt;&gt; u.save() #sucessfull created in mysql db &gt;&gt;...
0
2009-12-22T17:13:50Z
1,947,867
<p>The problem is not with <code>authenticate</code>, but with your creation of the user.</p> <p>The value stored in <code>u.password</code> needs to be the hashed value of the password, not the raw password itself.</p> <p>You can use <code>u.set_password('password')</code> to take care of the hashing for you:</p> <...
4
2009-12-22T17:20:42Z
[ "python", "django", "django-models" ]
Diacritic signs
1,947,837
<p>How should I write "mąka" in Python without an exception?</p> <p>I've tried <code>var= u"mąka"</code> and <code>var= unicode("mąka")</code> etc... nothing helps</p> <p>I have coding definition in first line in my document, and still I've got that exception:</p> <blockquote> <p>'utf8' codec can't decode byte ...
2
2009-12-22T17:16:50Z
1,947,916
<p>What exception are you getting?</p> <p>You might try saving your source code file as UTF-8, and putting this at the top of the file:</p> <pre><code># coding=utf-8 </code></pre> <p>That tells Python that the file’s saved as UTF-8. </p>
1
2009-12-22T17:27:23Z
[ "python", "django", "unicode" ]
Diacritic signs
1,947,837
<p>How should I write "mąka" in Python without an exception?</p> <p>I've tried <code>var= u"mąka"</code> and <code>var= unicode("mąka")</code> etc... nothing helps</p> <p>I have coding definition in first line in my document, and still I've got that exception:</p> <blockquote> <p>'utf8' codec can't decode byte ...
2
2009-12-22T17:16:50Z
1,948,141
<p>This code works for me, saving the file as UTF-8:</p> <pre><code>v = u"mąka" print repr(v) </code></pre> <p>The output I get is:</p> <pre><code>u'm\u0105ka' </code></pre> <p>Please copy and paste the exact error you are getting. If you are getting this error:</p> <pre><code>UnicodeEncodeError: 'charmap' codec ...
1
2009-12-22T18:05:57Z
[ "python", "django", "unicode" ]
Diacritic signs
1,947,837
<p>How should I write "mąka" in Python without an exception?</p> <p>I've tried <code>var= u"mąka"</code> and <code>var= unicode("mąka")</code> etc... nothing helps</p> <p>I have coding definition in first line in my document, and still I've got that exception:</p> <blockquote> <p>'utf8' codec can't decode byte ...
2
2009-12-22T17:16:50Z
1,948,280
<p>The # -<em>- coding: -</em>- line must specify the encoding the <em>source file</em> is saved in. This error message:</p> <pre><code>'utf8' codec can't decode byte 0xb1 in position 0: unexpected code byte </code></pre> <p>indicates you aren't saving the source file in UTF-8. You can save your source file in any ...
2
2009-12-22T18:32:48Z
[ "python", "django", "unicode" ]
Diacritic signs
1,947,837
<p>How should I write "mąka" in Python without an exception?</p> <p>I've tried <code>var= u"mąka"</code> and <code>var= unicode("mąka")</code> etc... nothing helps</p> <p>I have coding definition in first line in my document, and still I've got that exception:</p> <blockquote> <p>'utf8' codec can't decode byte ...
2
2009-12-22T17:16:50Z
1,948,316
<p>Save the following 2 lines into <code>write_mako.py</code>:</p> <pre><code># -*- encoding: utf-8 -*- open(u"mąka.txt", 'w').write("mąka\n") </code></pre> <p>Run:</p> <pre><code>$ python write_mako.py </code></pre> <p><code>mąka.txt</code> file that contains the word <code>mąka</code> should be created in the...
4
2009-12-22T18:38:30Z
[ "python", "django", "unicode" ]
How can I pickle a nested class in python?
1,947,904
<p>I have a nested class:</p> <pre> class WidgetType(object): class FloatType(object): pass class TextType(object): pass </pre> <p>.. and an oject that refers the nested class type (not an instance of it) like this</p> <pre> class ObjectToPickle(object): def __init__(self): ...
22
2009-12-22T17:25:36Z
1,947,965
<p>Pickle only works with classes defined in module scope (top level). In this case, it looks like you could define the nested classes in module scope and then set them as properties on WidgetType, assuming there's a reason not to just reference <code>TextType</code> and <code>FloatType</code> in your code. Or, import ...
0
2009-12-22T17:36:12Z
[ "python", "class", "nested", "pickle" ]
How can I pickle a nested class in python?
1,947,904
<p>I have a nested class:</p> <pre> class WidgetType(object): class FloatType(object): pass class TextType(object): pass </pre> <p>.. and an oject that refers the nested class type (not an instance of it) like this</p> <pre> class ObjectToPickle(object): def __init__(self): ...
22
2009-12-22T17:25:36Z
1,948,057
<p>The pickle module is trying to get the TextType class from the module. But since the class is nested it doesn't work. jasonjs's suggestion will work. Here are the lines in pickle.py responsible for the error message:</p> <pre><code> try: __import__(module) mod = sys.modules[module] klass ...
21
2009-12-22T17:51:23Z
[ "python", "class", "nested", "pickle" ]
How can I pickle a nested class in python?
1,947,904
<p>I have a nested class:</p> <pre> class WidgetType(object): class FloatType(object): pass class TextType(object): pass </pre> <p>.. and an oject that refers the nested class type (not an instance of it) like this</p> <pre> class ObjectToPickle(object): def __init__(self): ...
22
2009-12-22T17:25:36Z
1,949,236
<p>Nadia's answer is pretty complete - it is practically not something you want to be doing; are you sure you can't use inheritance in <code>WidgetTypes</code> instead of nested classes? </p> <p>The only reason to use nested classes is to encapsulate classes working together closely, your specific example looks like a...
1
2009-12-22T21:19:04Z
[ "python", "class", "nested", "pickle" ]
How can I pickle a nested class in python?
1,947,904
<p>I have a nested class:</p> <pre> class WidgetType(object): class FloatType(object): pass class TextType(object): pass </pre> <p>.. and an oject that refers the nested class type (not an instance of it) like this</p> <pre> class ObjectToPickle(object): def __init__(self): ...
22
2009-12-22T17:25:36Z
2,392,184
<p>In sage [www.sagemath.org] we have a lot in instance of this pickling issues. The way we decide to systematically solve it is to put the <em>outer</em> class inside a specific metaclass whose goal is to implement and hide the hack. Note that this automatically propagate through nested classes if there are several le...
4
2010-03-06T10:41:46Z
[ "python", "class", "nested", "pickle" ]
How can I pickle a nested class in python?
1,947,904
<p>I have a nested class:</p> <pre> class WidgetType(object): class FloatType(object): pass class TextType(object): pass </pre> <p>.. and an oject that refers the nested class type (not an instance of it) like this</p> <pre> class ObjectToPickle(object): def __init__(self): ...
22
2009-12-22T17:25:36Z
11,493,777
<p>I know this is a <strong>very</strong> old question, but I have never explicitly seen a satisfactory solution to this question other than the obvious, and most likely correct, answer to re-structure your code.</p> <p>Unfortunately, it is not always practical to do such a thing, in which case as a very last resort, ...
17
2012-07-15T16:50:45Z
[ "python", "class", "nested", "pickle" ]
How can I pickle a nested class in python?
1,947,904
<p>I have a nested class:</p> <pre> class WidgetType(object): class FloatType(object): pass class TextType(object): pass </pre> <p>.. and an oject that refers the nested class type (not an instance of it) like this</p> <pre> class ObjectToPickle(object): def __init__(self): ...
22
2009-12-22T17:25:36Z
21,345,710
<p>If you use <code>dill</code> instead of <code>pickle</code>, it works.</p> <pre><code>&gt;&gt;&gt; import dill &gt;&gt;&gt; &gt;&gt;&gt; class WidgetType(object): ... class FloatType(object): ... pass ... class TextType(object): ... pass ... &gt;&gt;&gt; class ObjectToPickle(object): ... def __init_...
4
2014-01-25T02:09:42Z
[ "python", "class", "nested", "pickle" ]
Adding new forms to a Django formset based on POST data
1,948,052
<p>I am trying to populate a Django formset using data from a POST request. I am able to display the formset properly and instantiate it again mostly alright, but I'm having an issue where the formset is ending up with 2 blank rows at the end, which is undesirable. Below is the function we've been using in views.py:<...
2
2009-12-22T17:50:38Z
1,948,786
<p>In your views.py:</p> <pre><code>- formset = DepositFormSet(initial=formset.cleaned_data) + data = formset.cleaned_data + if data[-1]=={}: + data=data[:-1] + formset = DepositFormSet(initial=data) </code></pre> <p>It looks pretty much like a feature than l...
2
2009-12-22T20:02:29Z
[ "python", "django", "django-forms" ]
Adding new forms to a Django formset based on POST data
1,948,052
<p>I am trying to populate a Django formset using data from a POST request. I am able to display the formset properly and instantiate it again mostly alright, but I'm having an issue where the formset is ending up with 2 blank rows at the end, which is undesirable. Below is the function we've been using in views.py:<...
2
2009-12-22T17:50:38Z
4,484,878
<p>I've not done this myself, but if you wanted to actually make it invalid with a blank entry, perhaps you'd consider putting it in the clean method:</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/forms/formsets/#custom-formset-validation" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/forms/...
1
2010-12-19T20:14:05Z
[ "python", "django", "django-forms" ]
How to create an excel file with an autofilter in the first row with xlwt?
1,948,224
<p>I am using Python 2.6 + xlwt module to generate excel files.</p> <p>Is it possible to include an autofilter in the first row with xlwt or pyExcelerator or anything else besides COM? </p> <p>Thanks</p>
6
2009-12-22T18:21:18Z
1,948,362
<p>I found <a href="http://groups.google.com.au/group/python-excel/browse%5Fthread/thread/5c07232e17c20af0/d8a4900e7f67e20f?lnk=gst&amp;q=autofilter#d8a4900e7f67e20f" rel="nofollow">this message</a> in a Google group. It looks like it's not possible, unfortunately.</p>
2
2009-12-22T18:44:47Z
[ "python", "excel", "xlwt", "pyexcelerator" ]
How to create an excel file with an autofilter in the first row with xlwt?
1,948,224
<p>I am using Python 2.6 + xlwt module to generate excel files.</p> <p>Is it possible to include an autofilter in the first row with xlwt or pyExcelerator or anything else besides COM? </p> <p>Thanks</p>
6
2009-12-22T18:21:18Z
1,948,940
<p>AFAIK xlwt doesn't allow you to add a filter.</p> <p>However you can add a filter using <a href="http://starship.python.net/crew/mhammond/win32/Downloads.html" rel="nofollow">Mark Hammond's Python Win32 Extensions</a>. Download for 2.6 <a href="http://sourceforge.net/projects/pywin32/files/" rel="nofollow">here</a>...
4
2009-12-22T20:31:31Z
[ "python", "excel", "xlwt", "pyexcelerator" ]
How to create an excel file with an autofilter in the first row with xlwt?
1,948,224
<p>I am using Python 2.6 + xlwt module to generate excel files.</p> <p>Is it possible to include an autofilter in the first row with xlwt or pyExcelerator or anything else besides COM? </p> <p>Thanks</p>
6
2009-12-22T18:21:18Z
20,838,509
<p>I have the same issue, running a linux server.</p> <p>i'm going to check creating an ODS or XLSX file with auto-filter by other means, and then convert them with a libreoffice command line to "xls".</p>
2
2013-12-30T11:22:59Z
[ "python", "excel", "xlwt", "pyexcelerator" ]
pygtk: howto change background of a gtk.TextView widget
1,948,396
<p>I want to make the background of a textview widget black and the foreground white.</p> <p>Been trying the <code>.modify_bg</code> and <code>.modify_fg</code> methods, but none affect the way this thing looks.</p> <p>Can anyone suggest anything or is this just not possible?</p>
0
2009-12-22T18:52:43Z
1,948,481
<p>I resolved some similar manipulating the gtk rcstyles:</p> <pre><code>widget.set_name('mywidget') # Set mywidget internal style. gtk.rc_parse_string('\ style "mywidget"\n\ {\n\ attribute1 = value1\n\ attribute2 = value2\n\ }\n\ widget "*.mywidget" style "mywidget"') </code></pre> <...
2
2009-12-22T19:08:10Z
[ "python", "gtk", "pygtk" ]
pygtk: howto change background of a gtk.TextView widget
1,948,396
<p>I want to make the background of a textview widget black and the foreground white.</p> <p>Been trying the <code>.modify_bg</code> and <code>.modify_fg</code> methods, but none affect the way this thing looks.</p> <p>Can anyone suggest anything or is this just not possible?</p>
0
2009-12-22T18:52:43Z
1,948,993
<p>Use <code>gtk.Widget.modify_text</code> and <code>gtk.Widget.modify_base</code> instead of fg and bg.</p>
2
2009-12-22T20:38:11Z
[ "python", "gtk", "pygtk" ]
Python library for sending/managing usage statistics
1,948,404
<p>Recall those applications that provide the option to "Send usage statistics to help improve X" during the installation? I presume it collects certain patterns of usage and sends it back to the server. Back at the server, there may be some sort of mining going on.</p> <p>Is there a Python library to do this .. at le...
3
2009-12-22T18:53:56Z
1,948,685
<h3><a href="http://docs.python.org/library/logging.html#sending-and-receiving-logging-events-across-a-network" rel="nofollow">Sending and receiving logging events across a network</a></h3> <p>From the docs:</p> <pre><code>import logging, logging.handlers rootLogger = logging.getLogger('') rootLogger.setLevel(loggin...
2
2009-12-22T19:47:18Z
[ "python", "usage-statistics" ]
twisted threading with subprocess.Popen?
1,948,641
<p>I'm trying to implement a service with Twisted that's fairly close to the "finger" tutorial found here: <a href="http://twistedmatrix.com/documents/current/core/howto/tutorial/intro.html" rel="nofollow">http://twistedmatrix.com/documents/current/core/howto/tutorial/intro.html</a></p> <p>I've got a basic.LineListene...
3
2009-12-22T19:39:09Z
1,949,819
<p>As mg said in his comment, don't use the subprocess module. On POSIX platforms, it's necessary (more or less) to handle the <code>SIGCHLD</code> signal to deal with child processes that exit. Since there can only be one <code>SIGCHLD</code> handler, multiple libraries generally won't cooperate. Twisted's child pr...
6
2009-12-22T23:11:11Z
[ "python", "multithreading", "twisted", "subprocess" ]
How to redirect to another page in Python in CGIAr
1,948,756
<p><strong>If I want to redirect the user from a cgi script to a HTML page using core libraries from the following:</strong></p> <pre><code>import cgi </code></pre> <p>Please could someone point me in the right direction. Nothing more. Simply redirect from cgi script to html page. How ever you would do this Python....
1
2009-12-22T19:58:02Z
1,948,848
<p>You need to output one more header ("Status") in addition to the <code>Location</code> one, e.g.:</p> <pre><code>print "Status: 301 Moved", print "Location:/wherever.com/" </code></pre>
4
2009-12-22T20:17:00Z
[ "python", "cgi" ]
How to redirect to another page in Python in CGIAr
1,948,756
<p><strong>If I want to redirect the user from a cgi script to a HTML page using core libraries from the following:</strong></p> <pre><code>import cgi </code></pre> <p>Please could someone point me in the right direction. Nothing more. Simply redirect from cgi script to html page. How ever you would do this Python....
1
2009-12-22T19:58:02Z
29,632,776
<p><strong>To redirect use Location header</strong></p> <pre><code>print "Location:URL\r\n" # URL is the location where you want to redirct to </code></pre> <p>One point to remember is that location header should be written before any other print statements.If other print statements are written before it then the lo...
0
2015-04-14T16:36:02Z
[ "python", "cgi" ]
Is the Python 3.x signal library for Windows incomplete?
1,948,862
<p>I went to write a system script using 3.0 and found the SIGALRM signal and signal.alarm() call missing amongst many others on the Windows deployment. Does anyone know why these are missing? Below is a dir() of the 2.5 vs 3.0 signal packages on windows. I haven't found any 3.0 docs yet mentioning that this was moved<...
3
2009-12-22T20:19:14Z
1,948,883
<p>Windows is <em>NOT</em> posix compliant OS so it does not have all signals - my guess is that on 3.0 the missing signals do not show up there any longer.</p>
3
2009-12-22T20:23:17Z
[ "python" ]
Is the Python 3.x signal library for Windows incomplete?
1,948,862
<p>I went to write a system script using 3.0 and found the SIGALRM signal and signal.alarm() call missing amongst many others on the Windows deployment. Does anyone know why these are missing? Below is a dir() of the 2.5 vs 3.0 signal packages on windows. I haven't found any 3.0 docs yet mentioning that this was moved<...
3
2009-12-22T20:19:14Z
1,950,153
<p>It seems you are running your 2.5 in cygwin, which is probably the reason that it shows up there.</p> <pre><code>Python 2.5.1 (r251:54863, May 18 2007, 16:56:43) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin </code></pre> <p>In my 2.5 for win32 it looks just like in your 3.1:</p> <pre><code>P...
3
2009-12-23T00:59:39Z
[ "python" ]
CPython/Jython cross-implementation GUI
1,948,925
<p>I need to make some GUIs for a Jython application, but would like to minimize translation time should the project switch over to CPython. HTML or XUL are possibilities, but ones that I'd like to avoid. Any ideas on a cross-implementation pythonic GUI toolkit?</p>
1
2009-12-22T20:28:53Z
1,953,170
<p>From <a href="http://old.nabble.com/wxWidgets-for-Java---Jython---IronPython---td21359279.html" rel="nofollow">the discussion here</a>, it doesn't look as though there is a single GUI toolkit that can be used across both Jython and CPython. There have been attempts like <a href="http://sourceforge.net/projects/wx4j/...
0
2009-12-23T14:39:32Z
[ "python", "user-interface", "jython" ]
how can I catch the error of "no existing page" in python
1,949,049
<p>I developpe a browser with python and pyqt4 but I don't know what I put in loaderror</p> <pre><code>try: self.webView.load(QtCore.QUrl(self.lineEdit.text())) except loaderreur: self.webView.load(QtCore.QUrl('erreur.html')) </code></pre> <p>when the page doesn't exist thx </p>
0
2009-12-22T20:47:50Z
1,949,118
<p>Try loading up your browser of choice, and see what they do when given a page that doesn't exist.</p> <p>You likely want to mimic that behaviour (Generic 404 page).</p>
0
2009-12-22T21:01:55Z
[ "python", "pyqt4" ]
"painting" one array onto another using python / numpy
1,949,225
<p>I'm writing a library to process gaze tracking in Python, and I'm rather new to the whole numpy / scipy world. Essentially, I'm looking to take an array of (x,y) values in time and "paint" some shape onto a canvas at those coordinates. For example, the shape might be a blurred circle. </p> <p>The operation I have i...
6
2009-12-22T21:17:03Z
1,949,253
<p>Have you looked into <a href="http://docs.python.org/library/tkinter.html" rel="nofollow">Tkinter</a>?</p> <p><a href="http://www.pythonware.com/products/pil/" rel="nofollow">Python Image Library</a> may be some help too.</p>
0
2009-12-22T21:22:02Z
[ "python", "image-processing", "numpy", "scipy" ]
"painting" one array onto another using python / numpy
1,949,225
<p>I'm writing a library to process gaze tracking in Python, and I'm rather new to the whole numpy / scipy world. Essentially, I'm looking to take an array of (x,y) values in time and "paint" some shape onto a canvas at those coordinates. For example, the shape might be a blurred circle. </p> <p>The operation I have i...
6
2009-12-22T21:17:03Z
1,949,306
<p>In your question you describe a Gaussian filter, for which scipy has support via a <a href="http://www.scipy.org/SciPyPackages/Ndimage" rel="nofollow">package</a>. For example:</p> <pre><code>from scipy import * # rand from pylab import * # figure, imshow from scipy.ndimage import gaussian_filter # random "image" ...
7
2009-12-22T21:29:28Z
[ "python", "image-processing", "numpy", "scipy" ]
"painting" one array onto another using python / numpy
1,949,225
<p>I'm writing a library to process gaze tracking in Python, and I'm rather new to the whole numpy / scipy world. Essentially, I'm looking to take an array of (x,y) values in time and "paint" some shape onto a canvas at those coordinates. For example, the shape might be a blurred circle. </p> <p>The operation I have i...
6
2009-12-22T21:17:03Z
1,994,530
<p>You should really look into Andrew Straw's <a href="http://code.astraw.com/projects/motmot/" rel="nofollow">motmot</a> and <a href="http://code.astraw.com/projects/motmot/libcamiface.html#libcamiface" rel="nofollow">libcamiface</a>. He uses it for fly behaviour experiments but it's a flexible library for doing just ...
2
2010-01-03T10:23:56Z
[ "python", "image-processing", "numpy", "scipy" ]
"painting" one array onto another using python / numpy
1,949,225
<p>I'm writing a library to process gaze tracking in Python, and I'm rather new to the whole numpy / scipy world. Essentially, I'm looking to take an array of (x,y) values in time and "paint" some shape onto a canvas at those coordinates. For example, the shape might be a blurred circle. </p> <p>The operation I have i...
6
2009-12-22T21:17:03Z
2,432,728
<p>Doing a little of math in Fourier space may help: a translation (convolution by a dirac) is equal to a simple multiplication by a phase in Fourier... this makes your paintbrush move to the exact place (a similar solution than catchmeifyoutry &amp; dwf, but this allows a translation finer than the pixel, like 2.5, al...
2
2010-03-12T12:41:18Z
[ "python", "image-processing", "numpy", "scipy" ]
"painting" one array onto another using python / numpy
1,949,225
<p>I'm writing a library to process gaze tracking in Python, and I'm rather new to the whole numpy / scipy world. Essentially, I'm looking to take an array of (x,y) values in time and "paint" some shape onto a canvas at those coordinates. For example, the shape might be a blurred circle. </p> <p>The operation I have i...
6
2009-12-22T21:17:03Z
17,601,457
<p>OpenCV uses numpy arrays and has basic drawing functions: circles, elipses, polylines...</p> <p>To draw a line you can call </p> <pre><code>cv.line(array,previous_point,new_point,colour,thickness=x) </code></pre> <p>each time you get a mouse event.</p>
1
2013-07-11T19:08:58Z
[ "python", "image-processing", "numpy", "scipy" ]
Choice of database for a Django-based RSS application?
1,949,228
<p>I'm planning a web application using Django, and it's based on a big pile of data from RSS feeds. What would be the best database to use to store the content of a lot of posts and metadata, as well as data about how each user relates to each post?</p> <p>I've heard that the consensus is that ZODB is too slow, but i...
0
2009-12-22T21:17:55Z
1,949,262
<p>Django is tuned to work (and perform) nicely with RDBMS, so that's probably the path of least resistance, until you've demonstrated to yourself that an RDBMS won't solve your problem. If you do reach that point, this <a href="http://code.djangoproject.com/wiki/NonSqlBackends" rel="nofollow">page on the wiki</a> is p...
3
2009-12-22T21:23:33Z
[ "python", "database", "django", "rss" ]
How to add clickable links to a field in Django admin?
1,949,248
<p>I have this admin.py</p> <pre><code>class LawyerAdmin(admin.ModelAdmin): fieldsets = [ ('Name', {'fields': ['last', 'first', 'firm_name', 'firm_url', 'school', 'year_graduated']}), ] list_display = ('last', 'first', 'school', 'year_graduated', 'firm_name', 'firm_url') list_filter = ['schoo...
22
2009-12-22T21:20:49Z
1,949,340
<p>Define a custom method in your LawyerAdmin class that returns the link as HTML:</p> <pre><code>def show_firm_url(self, obj): return '&lt;a href="%s"&gt;%s&lt;/a&gt;' % (obj.firm_url, obj.firm_url) show_firm_url.allow_tags = True </code></pre> <p>See <a href="http://docs.djangoproject.com/en/dev/ref/contrib/adm...
45
2009-12-22T21:35:23Z
[ "python", "django" ]
How to add clickable links to a field in Django admin?
1,949,248
<p>I have this admin.py</p> <pre><code>class LawyerAdmin(admin.ModelAdmin): fieldsets = [ ('Name', {'fields': ['last', 'first', 'firm_name', 'firm_url', 'school', 'year_graduated']}), ] list_display = ('last', 'first', 'school', 'year_graduated', 'firm_name', 'firm_url') list_filter = ['schoo...
22
2009-12-22T21:20:49Z
1,949,839
<p>add <code>show_firm_url</code> to <code>list_display</code></p>
3
2009-12-22T23:16:10Z
[ "python", "django" ]
How to add clickable links to a field in Django admin?
1,949,248
<p>I have this admin.py</p> <pre><code>class LawyerAdmin(admin.ModelAdmin): fieldsets = [ ('Name', {'fields': ['last', 'first', 'firm_name', 'firm_url', 'school', 'year_graduated']}), ] list_display = ('last', 'first', 'school', 'year_graduated', 'firm_name', 'firm_url') list_filter = ['schoo...
22
2009-12-22T21:20:49Z
13,268,825
<blockquote> <p>But it overrides the text display specified in my models and displays "show firm url" on the head of the column</p> </blockquote> <p>You can change it by assigning short_description property:</p> <pre><code>show_firm_url.short_description = "Firm URL" </code></pre>
2
2012-11-07T11:27:59Z
[ "python", "django" ]
How to add clickable links to a field in Django admin?
1,949,248
<p>I have this admin.py</p> <pre><code>class LawyerAdmin(admin.ModelAdmin): fieldsets = [ ('Name', {'fields': ['last', 'first', 'firm_name', 'firm_url', 'school', 'year_graduated']}), ] list_display = ('last', 'first', 'school', 'year_graduated', 'firm_name', 'firm_url') list_filter = ['schoo...
22
2009-12-22T21:20:49Z
31,745,953
<p>Use the <code>format_html</code> utility. This will escape any html from parameters and mark the string as safe to use in templates. The <code>allow_tags</code> method attribute has been deprecated in Django 1.9.</p> <pre><code>from django.utils.html import format_html class LawyerAdmin(admin.ModelAdmin): list...
19
2015-07-31T12:14:38Z
[ "python", "django" ]
Checking if a website is up via Python
1,949,318
<p>By using python, how can I check if a website is up? From what I read, I need to check the "HTTP HEAD" and see status code "200 OK", but how to do so ?</p> <p>Cheers</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python">How do you send a HE...
21
2009-12-22T21:31:41Z
1,949,335
<p>If by up, you simply mean "the server is serving", then you could use cURL, and if you get a response than it's up.</p> <p>I can't give you specific advice because I'm not a python programmer, however here is a link to pycurl <a href="http://pycurl.sourceforge.net/" rel="nofollow">http://pycurl.sourceforge.net/</a>...
2
2009-12-22T21:34:12Z
[ "python", "http", "scripting", "httprequest", "http-head" ]
Checking if a website is up via Python
1,949,318
<p>By using python, how can I check if a website is up? From what I read, I need to check the "HTTP HEAD" and see status code "200 OK", but how to do so ?</p> <p>Cheers</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python">How do you send a HE...
21
2009-12-22T21:31:41Z
1,949,338
<p>The <a href="http://docs.python.org/library/httplib.html#httpconnection-objects" rel="nofollow"><code>HTTPConnection</code></a> object from the <code>httplib</code> module in the standard library will probably do the trick for you. BTW, if you start doing anything advanced with HTTP in Python, be sure to check out <...
4
2009-12-22T21:34:44Z
[ "python", "http", "scripting", "httprequest", "http-head" ]
Checking if a website is up via Python
1,949,318
<p>By using python, how can I check if a website is up? From what I read, I need to check the "HTTP HEAD" and see status code "200 OK", but how to do so ?</p> <p>Cheers</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python">How do you send a HE...
21
2009-12-22T21:31:41Z
1,949,360
<p>You could try to do this with <code>getcode()</code> from <a href="http://docs.python.org/library/urllib.html"><strong>urllib</strong></a> </p> <pre><code>&gt;&gt;&gt; print urllib.urlopen("http://www.stackoverflow.com").getcode() &gt;&gt;&gt; 200 </code></pre>
39
2009-12-22T21:38:11Z
[ "python", "http", "scripting", "httprequest", "http-head" ]
Checking if a website is up via Python
1,949,318
<p>By using python, how can I check if a website is up? From what I read, I need to check the "HTTP HEAD" and see status code "200 OK", but how to do so ?</p> <p>Cheers</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python">How do you send a HE...
21
2009-12-22T21:31:41Z
1,949,393
<p>You can use <a href="http://docs.python.org/library/httplib.html">httplib</a></p> <pre><code>import httplib conn = httplib.HTTPConnection("www.python.org") conn.request("HEAD", "/") r1 = conn.getresponse() print r1.status, r1.reason </code></pre> <p>prints</p> <pre><code>200 OK </code></pre> <p>Of course, only i...
7
2009-12-22T21:44:21Z
[ "python", "http", "scripting", "httprequest", "http-head" ]
Checking if a website is up via Python
1,949,318
<p>By using python, how can I check if a website is up? From what I read, I need to check the "HTTP HEAD" and see status code "200 OK", but how to do so ?</p> <p>Cheers</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python">How do you send a HE...
21
2009-12-22T21:31:41Z
1,949,507
<pre><code>import httplib import socket import re def is_website_online(host): """ This function checks to see if a host name has a DNS entry by checking for socket info. If the website gets something in return, we know it's available to DNS. """ try: socket.gethostbyname(host) ...
2
2009-12-22T22:06:52Z
[ "python", "http", "scripting", "httprequest", "http-head" ]
Checking if a website is up via Python
1,949,318
<p>By using python, how can I check if a website is up? From what I read, I need to check the "HTTP HEAD" and see status code "200 OK", but how to do so ?</p> <p>Cheers</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python">How do you send a HE...
21
2009-12-22T21:31:41Z
15,743,618
<p>I think the easiest way to do it is by using <a href="http://docs.python-requests.org/en/latest/" rel="nofollow">Requests</a> module.</p> <pre><code>import requests def url_ok(url): r = requests.head(url) return r.status_code == 200 </code></pre>
2
2013-04-01T12:36:55Z
[ "python", "http", "scripting", "httprequest", "http-head" ]
Checking if a website is up via Python
1,949,318
<p>By using python, how can I check if a website is up? From what I read, I need to check the "HTTP HEAD" and see status code "200 OK", but how to do so ?</p> <p>Cheers</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python">How do you send a HE...
21
2009-12-22T21:31:41Z
38,145,622
<pre><code>from urllib.request import Request, urlopen from urllib.error import URLError, HTTPError req = Request("http://stackoverflow.com") try: response = urlopen(req) except HTTPError as e: print('The server couldn\'t fulfill the request.') print('Error code: ', e.code) except URLError as e: print('...
1
2016-07-01T12:36:53Z
[ "python", "http", "scripting", "httprequest", "http-head" ]
Mako templates use old version until I manually update template files
1,949,516
<p>I periodically get this problem where all of a sudden mako is using old versions of templates, and it's not until I manually go and update the template files that they'll use the current version. I'm using</p> <pre><code>./manage.py runserver </code></pre> <p>I think it's usually after I update using source contro...
0
2009-12-22T22:08:24Z
1,950,247
<p>It kinda feels like there some caching going on. You don't give a very specific description of the process, so it's hard to go any deeper than that.</p>
0
2009-12-23T01:44:29Z
[ "python", "django", "mako" ]
Mako templates use old version until I manually update template files
1,949,516
<p>I periodically get this problem where all of a sudden mako is using old versions of templates, and it's not until I manually go and update the template files that they'll use the current version. I'm using</p> <pre><code>./manage.py runserver </code></pre> <p>I think it's usually after I update using source contro...
0
2009-12-22T22:08:24Z
2,603,689
<p>In your settings.py file you can use the MAKO_TEMPLATE_OPTS setting to specify where the temporary compiled templates go.</p> <pre><code>import os import tempfile MAKO_TEMPLATE_OPTS=dict(input_encoding='utf-8', module_directory=os.path.join( tempfile.gettempdir(), os.environ.get('LOG...
0
2010-04-08T21:47:42Z
[ "python", "django", "mako" ]
Parsing an html file and adding found images to a zip file
1,949,549
<p>I am trying to parse an html for all its img tags, download all the images pointed to by src, and then add those files to a zip file. I would prefer to do all this in memory since I can guarantee there won't be that many images.</p> <p>Assume the images variable is already populated from parsing the html. What I ne...
2
2009-12-22T22:16:59Z
1,949,607
<p>I'm not quite sure what you're asking here, since you appear to have most of it sorted. </p> <p>Have you investigated <a href="http://docs.python.org/library/htmlparser.html" rel="nofollow">HtmlParser</a> to actually perform the HTML parsing ? I wouldn't try hand-rolling a parser yourself - it's a major task with n...
1
2009-12-22T22:24:42Z
[ "python", "zip" ]
Parsing an html file and adding found images to a zip file
1,949,549
<p>I am trying to parse an html for all its img tags, download all the images pointed to by src, and then add those files to a zip file. I would prefer to do all this in memory since I can guarantee there won't be that many images.</p> <p>Assume the images variable is already populated from parsing the html. What I ne...
2
2009-12-22T22:16:59Z
1,949,635
<p>The easiest way I can think of to do this would be to use the BeautifulSoup library.</p> <p>Something along the lines of:</p> <pre><code>from BeautifulSoup import BeautifulSoup from collections import defaultdict def getImgSrces(html): srcs = [] soup = BeautifulSoup(html) for tag in soup('img'): ...
1
2009-12-22T22:31:05Z
[ "python", "zip" ]
Parsing an html file and adding found images to a zip file
1,949,549
<p>I am trying to parse an html for all its img tags, download all the images pointed to by src, and then add those files to a zip file. I would prefer to do all this in memory since I can guarantee there won't be that many images.</p> <p>Assume the images variable is already populated from parsing the html. What I ne...
2
2009-12-22T22:16:59Z
1,949,965
<p>To answer your specific question about how you create the ZIP archive (others here have discussed parsing the URLs), I tested out your code. You are really remarkably close to having a finished product already. </p> <p>Here's how I would augment what you have to create a Zip archive (in this example, I'm writing th...
1
2009-12-22T23:53:29Z
[ "python", "zip" ]
tornado - transferring a file to cdn without blocking
1,950,055
<p>I have the nginx upload module handling site uploads, but still need to transfer files (let's say 3-20mb each) to our cdn, and would rather not delegate that to a background job.</p> <p>What is the best way to do this with tornado without blocking other requests? Can i do this in an async callback? </p>
0
2009-12-23T00:24:59Z
1,950,329
<p>You may find it useful in the overall architecture of your site to add a message queuing service such as <a href="http://www.rabbitmq.com/">RabbitMQ</a>.</p> <p>This would let you complete the upload via the nginx module, then in the tornado handler, post a message containing the uploaded file path and exit. A sepa...
5
2009-12-23T02:13:04Z
[ "python", "cdn", "tornado" ]
tornado - transferring a file to cdn without blocking
1,950,055
<p>I have the nginx upload module handling site uploads, but still need to transfer files (let's say 3-20mb each) to our cdn, and would rather not delegate that to a background job.</p> <p>What is the best way to do this with tornado without blocking other requests? Can i do this in an async callback? </p>
0
2009-12-23T00:24:59Z
1,961,968
<p>advice on the tornado google group points to using an async callback (documented at <a href="http://www.tornadoweb.org/documentation#non-blocking-asynchronous-requests" rel="nofollow">http://www.tornadoweb.org/documentation#non-blocking-asynchronous-requests</a>) to move the file to the cdn. </p> <p>the nginx uploa...
0
2009-12-25T21:13:54Z
[ "python", "cdn", "tornado" ]
Python: intercept a class loading action
1,950,062
<p>Summary: when a certain python module is imported, I want to be able to intercept this action, and instead of loading the required class, I want to load another class of my choice.</p> <p>Reason: I am working on some legacy code. I need to write some unit test code before I start some enhancement/refactoring. The c...
4
2009-12-23T00:29:55Z
1,950,109
<p>Well, if the import fails by raising an exception, you could put it in a try...except loop:</p> <pre><code>try: from LegacyDataLoader import load_me_data except: # put error that occurs here, so as not to mask actual problems from MockDataLoader import load_me_data </code></pre> <p>Is that what you're look...
1
2009-12-23T00:45:10Z
[ "python", "unit-testing" ]
Python: intercept a class loading action
1,950,062
<p>Summary: when a certain python module is imported, I want to be able to intercept this action, and instead of loading the required class, I want to load another class of my choice.</p> <p>Reason: I am working on some legacy code. I need to write some unit test code before I start some enhancement/refactoring. The c...
4
2009-12-23T00:29:55Z
1,950,205
<p>There are cleaner ways to do this, but I'll assume that you can't modify the file containing <code>from LegacyDataLoader import load_me_data</code>.</p> <p>The simplest thing to do is probably to create a new directory called testing_shims, and create LegacyDataLoader.py file in it. In that file, define whatever f...
1
2009-12-23T01:23:28Z
[ "python", "unit-testing" ]
Python: intercept a class loading action
1,950,062
<p>Summary: when a certain python module is imported, I want to be able to intercept this action, and instead of loading the required class, I want to load another class of my choice.</p> <p>Reason: I am working on some legacy code. I need to write some unit test code before I start some enhancement/refactoring. The c...
4
2009-12-23T00:29:55Z
1,950,214
<p>The import statement just grabs stuff from sys.modules if a matching name is found there, so the simplest thing is to make sure you insert your own module into sys.modules under the target name <em>before</em> anything else tries to import the real thing.</p> <pre><code># in test code import sys import MockDataLoad...
1
2009-12-23T01:26:54Z
[ "python", "unit-testing" ]
Python: intercept a class loading action
1,950,062
<p>Summary: when a certain python module is imported, I want to be able to intercept this action, and instead of loading the required class, I want to load another class of my choice.</p> <p>Reason: I am working on some legacy code. I need to write some unit test code before I start some enhancement/refactoring. The c...
4
2009-12-23T00:29:55Z
1,950,986
<p>You can intercept <code>import</code> and <code>from ... import</code> statements by defining your own <code>__import__</code> function and assigning it to <code>__builtin__.__import__</code> (make sure to save the previous value, since your override will no doubt want to delegate to it; and you'll need to <code>imp...
2
2009-12-23T06:19:48Z
[ "python", "unit-testing" ]
Suspicious Operation Django
1,950,069
<p>I've been running into a problem while trying to delete uploaded images.</p> <p>The error is along these lines:</p> <pre><code>SuspiciousOperation: Attempted access to '/media/artists/12-stones/154339.jpg' denied. </code></pre> <p>After reading around it looks like the error is due to the fact that it's looking f...
23
2009-12-23T00:32:32Z
1,950,178
<p>Well, a little grepping around in the code shows that there may be a deeper error message that got homogenized along the way.</p> <p>in django/core/files/storage.py, line 210 (this is in 1.1.1) we have:</p> <pre><code>def path(self, name): try: path = safe_join(self.location, name) except ValueErro...
28
2009-12-23T01:13:17Z
[ "python", "django" ]
Suspicious Operation Django
1,950,069
<p>I've been running into a problem while trying to delete uploaded images.</p> <p>The error is along these lines:</p> <pre><code>SuspiciousOperation: Attempted access to '/media/artists/12-stones/154339.jpg' denied. </code></pre> <p>After reading around it looks like the error is due to the fact that it's looking f...
23
2009-12-23T00:32:32Z
1,950,368
<p>Ah figured it out, slightly embarrassing, but it turns out the error was higher up. I was plugging these images in by a script and while going over it again realized that <strong>my</strong> paths started with /media/.</p> <p>Now I have about 4000 images with wrong paths ... is there a way to somehow amend the path...
2
2009-12-23T02:25:33Z
[ "python", "django" ]
Suspicious Operation Django
1,950,069
<p>I've been running into a problem while trying to delete uploaded images.</p> <p>The error is along these lines:</p> <pre><code>SuspiciousOperation: Attempted access to '/media/artists/12-stones/154339.jpg' denied. </code></pre> <p>After reading around it looks like the error is due to the fact that it's looking f...
23
2009-12-23T00:32:32Z
1,954,204
<p>You really should just ask a new question on this. Try the following:</p> <p>Write a standalone django script that looks something like this:</p> <pre><code>from django.core.management import setup_environ from mysite import settings setup_environ(settings) from django.db import transaction from app.models import...
2
2009-12-23T17:32:35Z
[ "python", "django" ]
Suspicious Operation Django
1,950,069
<p>I've been running into a problem while trying to delete uploaded images.</p> <p>The error is along these lines:</p> <pre><code>SuspiciousOperation: Attempted access to '/media/artists/12-stones/154339.jpg' denied. </code></pre> <p>After reading around it looks like the error is due to the fact that it's looking f...
23
2009-12-23T00:32:32Z
4,976,681
<p>This bug is fixed in django 1.2.5. See <a href="http://docs.djangoproject.com/en/dev/releases/1.2.5/#filefield-no-longer-deletes-files" rel="nofollow">http://docs.djangoproject.com/en/dev/releases/1.2.5/#filefield-no-longer-deletes-files</a></p>
0
2011-02-12T06:23:01Z
[ "python", "django" ]
Suspicious Operation Django
1,950,069
<p>I've been running into a problem while trying to delete uploaded images.</p> <p>The error is along these lines:</p> <pre><code>SuspiciousOperation: Attempted access to '/media/artists/12-stones/154339.jpg' denied. </code></pre> <p>After reading around it looks like the error is due to the fact that it's looking f...
23
2009-12-23T00:32:32Z
6,204,619
<p>I got this error when I put a leading slash in the upload_to definition.</p> <p>BAD</p> <pre><code>pic = models.ImageField(upload_to="/uploads/product_images/") </code></pre> <p>GOOD</p> <pre><code>pic = models.ImageField(upload_to="uploads/product_images/") </code></pre>
53
2011-06-01T16:34:42Z
[ "python", "django" ]
Suspicious Operation Django
1,950,069
<p>I've been running into a problem while trying to delete uploaded images.</p> <p>The error is along these lines:</p> <pre><code>SuspiciousOperation: Attempted access to '/media/artists/12-stones/154339.jpg' denied. </code></pre> <p>After reading around it looks like the error is due to the fact that it's looking f...
23
2009-12-23T00:32:32Z
10,275,680
<p>if you want use other location ,such as /data/images/myfile/ , you should set you MEDIA_ROOT to /data/images in django settings.py file . </p>
1
2012-04-23T06:14:56Z
[ "python", "django" ]
Suspicious Operation Django
1,950,069
<p>I've been running into a problem while trying to delete uploaded images.</p> <p>The error is along these lines:</p> <pre><code>SuspiciousOperation: Attempted access to '/media/artists/12-stones/154339.jpg' denied. </code></pre> <p>After reading around it looks like the error is due to the fact that it's looking f...
23
2009-12-23T00:32:32Z
11,346,592
<p>As a note for others this issue can be caused when you have a double '//' in the static file resource you are looking for.</p> <pre><code>{{ STATIC_URL }}/style.css # Causes the issue it should be {{ STATIC_URL }}style.css </code></pre>
7
2012-07-05T14:36:48Z
[ "python", "django" ]
Suspicious Operation Django
1,950,069
<p>I've been running into a problem while trying to delete uploaded images.</p> <p>The error is along these lines:</p> <pre><code>SuspiciousOperation: Attempted access to '/media/artists/12-stones/154339.jpg' denied. </code></pre> <p>After reading around it looks like the error is due to the fact that it's looking f...
23
2009-12-23T00:32:32Z
29,140,680
<p>I got this error too. Debugging through I found that the following exception is being raised.</p> <pre><code>SuspiciousOperation(u"Attempted access to '2015-03-19-08:29:51-2-f8945842891244629dfd0c0af4c72a9c.pdf' denied.",) </code></pre> <p>BTW, I am using django-storages (v1.1.8) to store my media files onto S3 (u...
0
2015-03-19T09:15:18Z
[ "python", "django" ]
Suspicious Operation Django
1,950,069
<p>I've been running into a problem while trying to delete uploaded images.</p> <p>The error is along these lines:</p> <pre><code>SuspiciousOperation: Attempted access to '/media/artists/12-stones/154339.jpg' denied. </code></pre> <p>After reading around it looks like the error is due to the fact that it's looking f...
23
2009-12-23T00:32:32Z
34,993,727
<p>I found out, by using dumb <code>print</code> statements, that some media files have <code>/media</code> prefixed in their url paths. While the default storage option handles that, there is a problem if you use <code>S3BotoStorage</code> from <code>django-storages</code>.</p> <p>So I fixed it by overriding the <cod...
0
2016-01-25T13:23:39Z
[ "python", "django" ]
Does Python have any for loop equivalent (not foreach)
1,950,098
<p>Python's iterators are great and all, but sometimes I really do want a C-style for loop - not a foreach loop. For example, I have a start date and an end date and I want to do something for every day in that range. I can do this with a while loop, of course:</p> <pre><code> current = start while current &lt;...
13
2009-12-23T00:41:31Z
1,950,162
<p>For the sake of iterating only, you should actually use <strong>xrange</strong> over range, since xrange will simply return an iterator, whereas range will create an actual list object containing the whole integer range from first to last-1 (which is obviously less efficient when all you want is a simple for-loop):<...
-2
2009-12-23T01:05:30Z
[ "python", "loops", "for-loop" ]