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 |
|---|---|---|---|---|---|---|---|---|---|
Supplying password to wrapped-up MySQL
| 619,804
|
<p>Greetings.</p>
<p>I have written a little python script that calls MySQL in a subprocess. [Yes, I know that the right approach is to use MySQLdb, but compiling it under OS X Leopard is a pain, and likely more painful if I wanted to use the script on computers of different architectures.] The subprocess technique works, provided that I supply the password in the command that starts the process; however, that means that other users on the machine could see the password.</p>
<p>The original code I wrote can be seen <a href="http://armagons-isles.blogspot.com/2009/03/python-subprocess-wrapper-for-mysql.html" rel="nofollow">here</a>.</p>
<p>This variant below is very similar, although I will omit the test routine to keep it shorter:</p>
<pre><code>#!/usr/bin/env python
from subprocess import Popen, PIPE
# Set the command you need to connect to your database
mysql_cmd_line = "/Applications/MAMP/Library/bin/mysql -u root -p"
mysql_password = "root"
def RunSqlCommand(sql_statement, database=None):
"""Pass in the SQL statement that you would like executed.
Optionally, specify a database to operate on. Returns the result."""
command_list = mysql_cmd_line.split()
if database:
command_list.append(database)
# Run mysql in a subprocess
process = Popen(command_list, stdin=PIPE, stdout=PIPE,
stderr=PIPE, close_fds=True)
#print "Asking for output"
#needs_pw = process.stdout.readline()
#print "Got: " + needs_pw
# pass it in the password
process.stdin.write(mysql_password + "\n")
# pass it our commands, and get the results
#(stdout, stderr) = process.communicate( mysql_password + "\n" + sql_statement)
(stdout, stderr) = process.communicate( sql_statement )
return stdout
</code></pre>
<p>I am suspicious that the MySQL password prompt is not actually on stdout (or stderr), although I don't know how that could be or if it means I could trap it.</p>
<p>I did try reading output first, before supplying a password, but it didn't work. I also tried passing the password</p>
<p>Again, if I supply the password on the command line (and thus have no code between the "Popen" and "communicate" functions) my wrapped function works.</p>
<p><hr /></p>
<p><em>Two new thoughts, months laster:</em></p>
<ol>
<li><p>Using <a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">pexpect</a> would let me supply a password. It simulates a tty and gets all output, even that which bypasses stdout and stderr.</p></li>
<li><p>There is a project called <a href="https://launchpad.net/myconnpy" rel="nofollow">MySQL Connector/Python</a>, in early alpha, that will allow provide a pure python library for accessing MySQL, without requiring you to compile any C-code.</p></li>
</ol>
| 2
|
2009-03-06T17:58:49Z
| 619,903
|
<p>Try this:</p>
<pre><code>process.stdin.write(mysql_password + "\n")
process.communicate()
(stdout, stderr) = process.communicate( sql_statement )
process.stdin.close()
return stdout
</code></pre>
<p>Call communicate() to force what you just wrote to the buffer to send. Also, it's good to close stdin when you are done.</p>
| 0
|
2009-03-06T18:24:09Z
|
[
"python",
"mysql",
"subprocess"
] |
Supplying password to wrapped-up MySQL
| 619,804
|
<p>Greetings.</p>
<p>I have written a little python script that calls MySQL in a subprocess. [Yes, I know that the right approach is to use MySQLdb, but compiling it under OS X Leopard is a pain, and likely more painful if I wanted to use the script on computers of different architectures.] The subprocess technique works, provided that I supply the password in the command that starts the process; however, that means that other users on the machine could see the password.</p>
<p>The original code I wrote can be seen <a href="http://armagons-isles.blogspot.com/2009/03/python-subprocess-wrapper-for-mysql.html" rel="nofollow">here</a>.</p>
<p>This variant below is very similar, although I will omit the test routine to keep it shorter:</p>
<pre><code>#!/usr/bin/env python
from subprocess import Popen, PIPE
# Set the command you need to connect to your database
mysql_cmd_line = "/Applications/MAMP/Library/bin/mysql -u root -p"
mysql_password = "root"
def RunSqlCommand(sql_statement, database=None):
"""Pass in the SQL statement that you would like executed.
Optionally, specify a database to operate on. Returns the result."""
command_list = mysql_cmd_line.split()
if database:
command_list.append(database)
# Run mysql in a subprocess
process = Popen(command_list, stdin=PIPE, stdout=PIPE,
stderr=PIPE, close_fds=True)
#print "Asking for output"
#needs_pw = process.stdout.readline()
#print "Got: " + needs_pw
# pass it in the password
process.stdin.write(mysql_password + "\n")
# pass it our commands, and get the results
#(stdout, stderr) = process.communicate( mysql_password + "\n" + sql_statement)
(stdout, stderr) = process.communicate( sql_statement )
return stdout
</code></pre>
<p>I am suspicious that the MySQL password prompt is not actually on stdout (or stderr), although I don't know how that could be or if it means I could trap it.</p>
<p>I did try reading output first, before supplying a password, but it didn't work. I also tried passing the password</p>
<p>Again, if I supply the password on the command line (and thus have no code between the "Popen" and "communicate" functions) my wrapped function works.</p>
<p><hr /></p>
<p><em>Two new thoughts, months laster:</em></p>
<ol>
<li><p>Using <a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">pexpect</a> would let me supply a password. It simulates a tty and gets all output, even that which bypasses stdout and stderr.</p></li>
<li><p>There is a project called <a href="https://launchpad.net/myconnpy" rel="nofollow">MySQL Connector/Python</a>, in early alpha, that will allow provide a pure python library for accessing MySQL, without requiring you to compile any C-code.</p></li>
</ol>
| 2
|
2009-03-06T17:58:49Z
| 619,944
|
<p>The only secure method is to use a MySQL cnf file as one of the other posters mentions. You can also pass a MYSQL_PWD env variable, but that is insecure as well: <a href="http://dev.mysql.com/doc/refman/5.0/en/password-security.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.0/en/password-security.html</a></p>
<p>Alternatively, you can communicate with the database using a Unix socket file and with a little bit of tweaking you can control permissions at the user id level.</p>
<p>Even better, you can use the free BitNami stack DjangoStack that has Python and MySQLDB precompiled for OS X (And Windows and Linux) <a href="http://bitnami.org/stacks" rel="nofollow">http://bitnami.org/stacks</a></p>
| 3
|
2009-03-06T18:38:01Z
|
[
"python",
"mysql",
"subprocess"
] |
Progammatically restart windows to make system logs think user logged out
| 620,154
|
<p>I'm hoping to make a quick script to log-out/restart windows at a set time. For example, start a script to "Restart windows in ten minutes". For this implementation I don't need it to run in the background or pop=up on its own. I just want to set the script and walk away knowing that the computer will log-out/restart at a set time. </p>
<p><strong>Why would I want to do this?</strong>
On a corporate network, sometimes system logs will be reviewed and if one is found to be leaving X minutes too early, then complications arise. Kinda annoying.</p>
<p><strong>Did I already Google it?</strong>
Yep. I found <a href="http://kvance.livejournal.com/985732.html" rel="nofollow">this</a>. But it wasn't too helpful. It requires a framework I couldn't find, and likely couldn't install since we don't have admin privs on these machines.</p>
<p>I'd like to use Python for it, and I'd really like for it to look like the user did it, not a script. Perhaps screen scraping would be the only way, and if so just point me to a quick guide or IDE and I'll post the source code for everyone.</p>
<p><strong>EDIT</strong>: I also ran into <a href="http://sourceforge.net/projects/pywinauto/" rel="nofollow">this</a></p>
<p>Thanks in advance</p>
| 4
|
2009-03-06T19:44:12Z
| 620,194
|
<p>The shutdown command in batch will shutdown the computer</p>
<p>-s to turn it off,
-f to force it,
-t xx to have it shutdown in x seconds,</p>
<p>use the subprocess module in python to call it.</p>
<p>Since you want it to shutdown at a specific time, to automate the job completely you'd need to use something like autosys. Set the script up to call shutdown with a value for T equal to time you want to shut down - current time in seconds. Run it before you leave for the day, or have it set to run on start up and just ignore that stupid window it brings up.</p>
| 10
|
2009-03-06T19:53:01Z
|
[
"python",
"windows",
"automation"
] |
Progammatically restart windows to make system logs think user logged out
| 620,154
|
<p>I'm hoping to make a quick script to log-out/restart windows at a set time. For example, start a script to "Restart windows in ten minutes". For this implementation I don't need it to run in the background or pop=up on its own. I just want to set the script and walk away knowing that the computer will log-out/restart at a set time. </p>
<p><strong>Why would I want to do this?</strong>
On a corporate network, sometimes system logs will be reviewed and if one is found to be leaving X minutes too early, then complications arise. Kinda annoying.</p>
<p><strong>Did I already Google it?</strong>
Yep. I found <a href="http://kvance.livejournal.com/985732.html" rel="nofollow">this</a>. But it wasn't too helpful. It requires a framework I couldn't find, and likely couldn't install since we don't have admin privs on these machines.</p>
<p>I'd like to use Python for it, and I'd really like for it to look like the user did it, not a script. Perhaps screen scraping would be the only way, and if so just point me to a quick guide or IDE and I'll post the source code for everyone.</p>
<p><strong>EDIT</strong>: I also ran into <a href="http://sourceforge.net/projects/pywinauto/" rel="nofollow">this</a></p>
<p>Thanks in advance</p>
| 4
|
2009-03-06T19:44:12Z
| 620,195
|
<p><a href="http://technet.microsoft.com/en-us/sysinternals/bb897541.aspx" rel="nofollow">PsShutdown</a> is probably what you are looking for.</p>
| 1
|
2009-03-06T19:53:08Z
|
[
"python",
"windows",
"automation"
] |
Progammatically restart windows to make system logs think user logged out
| 620,154
|
<p>I'm hoping to make a quick script to log-out/restart windows at a set time. For example, start a script to "Restart windows in ten minutes". For this implementation I don't need it to run in the background or pop=up on its own. I just want to set the script and walk away knowing that the computer will log-out/restart at a set time. </p>
<p><strong>Why would I want to do this?</strong>
On a corporate network, sometimes system logs will be reviewed and if one is found to be leaving X minutes too early, then complications arise. Kinda annoying.</p>
<p><strong>Did I already Google it?</strong>
Yep. I found <a href="http://kvance.livejournal.com/985732.html" rel="nofollow">this</a>. But it wasn't too helpful. It requires a framework I couldn't find, and likely couldn't install since we don't have admin privs on these machines.</p>
<p>I'd like to use Python for it, and I'd really like for it to look like the user did it, not a script. Perhaps screen scraping would be the only way, and if so just point me to a quick guide or IDE and I'll post the source code for everyone.</p>
<p><strong>EDIT</strong>: I also ran into <a href="http://sourceforge.net/projects/pywinauto/" rel="nofollow">this</a></p>
<p>Thanks in advance</p>
| 4
|
2009-03-06T19:44:12Z
| 620,224
|
<p>You can use the <a href="http://technet.microsoft.com/en-us/library/cc732503.aspx" rel="nofollow">shutdown</a> command in a batch script.</p>
| 1
|
2009-03-06T20:04:24Z
|
[
"python",
"windows",
"automation"
] |
Convert Year/Month/Day to Day of Year in Python
| 620,305
|
<p>I'm using the Python "datetime" module, i.e.:</p>
<pre><code>>>> import datetime
>>> today = datetime.datetime.now()
>>> print today
2009-03-06 13:24:58.857946
</code></pre>
<p>and I would like to compute the day of year that is sensitive of leap years. e.g. oday (March 6, 2009) is the 65th day of 2009. <a href="http://mistupid.com/calendar/dayofyear.htm">Here's web-based DateTime calculator</a>.</p>
<p>Anyway, I see a two options:</p>
<ol>
<li><p>Create a number_of_days_in_month array = [31, 28, ...], decide if it's a leap year, manually sum up the days</p></li>
<li><p>Use datetime.timedelta to make a guess & then binary search for the correct day of year:</p></li>
</ol>
<p>.</p>
<pre><code>>>> import datetime
>>> YEAR = 2009
>>> DAY_OF_YEAR = 62
>>> d = datetime.date(YEAR, 1, 1) + datetime.timedelta(DAY_OF_YEAR - 1)
</code></pre>
<p>These both feel pretty clunky & I have a gut feeling that there's a more "Pythonic" way of calculating day of year. Any ideas/suggestions?</p>
| 60
|
2009-03-06T20:34:32Z
| 620,322
|
<p>Couldn't you use <a href="http://docs.python.org/library/datetime.html#strftime-behavior"><code>strftime</code></a>?</p>
<pre><code>>>> import datetime
>>> today = datetime.datetime.now()
>>> print today
2009-03-06 15:37:02.484000
>>> today.strftime('%j')
'065'
</code></pre>
<h3>Edit</h3>
<p>As noted in the comments, if you wish to do comparisons or calculations with this number, you would have to convert it to <code>int()</code> because <code>strftime()</code> returns a string. If that is the case, you are better off using <a href="http://stackoverflow.com/questions/620305/convert-year-month-day-to-day-of-year-in-python/623312#623312">DzinX's</a> answer.</p>
| 17
|
2009-03-06T20:37:27Z
|
[
"python",
"datetime"
] |
Convert Year/Month/Day to Day of Year in Python
| 620,305
|
<p>I'm using the Python "datetime" module, i.e.:</p>
<pre><code>>>> import datetime
>>> today = datetime.datetime.now()
>>> print today
2009-03-06 13:24:58.857946
</code></pre>
<p>and I would like to compute the day of year that is sensitive of leap years. e.g. oday (March 6, 2009) is the 65th day of 2009. <a href="http://mistupid.com/calendar/dayofyear.htm">Here's web-based DateTime calculator</a>.</p>
<p>Anyway, I see a two options:</p>
<ol>
<li><p>Create a number_of_days_in_month array = [31, 28, ...], decide if it's a leap year, manually sum up the days</p></li>
<li><p>Use datetime.timedelta to make a guess & then binary search for the correct day of year:</p></li>
</ol>
<p>.</p>
<pre><code>>>> import datetime
>>> YEAR = 2009
>>> DAY_OF_YEAR = 62
>>> d = datetime.date(YEAR, 1, 1) + datetime.timedelta(DAY_OF_YEAR - 1)
</code></pre>
<p>These both feel pretty clunky & I have a gut feeling that there's a more "Pythonic" way of calculating day of year. Any ideas/suggestions?</p>
| 60
|
2009-03-06T20:34:32Z
| 620,345
|
<p>Just subtract january 1 from the date:</p>
<pre><code>import datetime
today = datetime.datetime.now()
day_of_year = (today - datetime.datetime(today.year, 1, 1)).days + 1
</code></pre>
| 5
|
2009-03-06T20:43:04Z
|
[
"python",
"datetime"
] |
Convert Year/Month/Day to Day of Year in Python
| 620,305
|
<p>I'm using the Python "datetime" module, i.e.:</p>
<pre><code>>>> import datetime
>>> today = datetime.datetime.now()
>>> print today
2009-03-06 13:24:58.857946
</code></pre>
<p>and I would like to compute the day of year that is sensitive of leap years. e.g. oday (March 6, 2009) is the 65th day of 2009. <a href="http://mistupid.com/calendar/dayofyear.htm">Here's web-based DateTime calculator</a>.</p>
<p>Anyway, I see a two options:</p>
<ol>
<li><p>Create a number_of_days_in_month array = [31, 28, ...], decide if it's a leap year, manually sum up the days</p></li>
<li><p>Use datetime.timedelta to make a guess & then binary search for the correct day of year:</p></li>
</ol>
<p>.</p>
<pre><code>>>> import datetime
>>> YEAR = 2009
>>> DAY_OF_YEAR = 62
>>> d = datetime.date(YEAR, 1, 1) + datetime.timedelta(DAY_OF_YEAR - 1)
</code></pre>
<p>These both feel pretty clunky & I have a gut feeling that there's a more "Pythonic" way of calculating day of year. Any ideas/suggestions?</p>
| 60
|
2009-03-06T20:34:32Z
| 623,312
|
<p>There is a very simple solution:</p>
<pre><code>day_of_year = datetime.now().timetuple().tm_yday
</code></pre>
| 133
|
2009-03-08T09:27:24Z
|
[
"python",
"datetime"
] |
Convert Year/Month/Day to Day of Year in Python
| 620,305
|
<p>I'm using the Python "datetime" module, i.e.:</p>
<pre><code>>>> import datetime
>>> today = datetime.datetime.now()
>>> print today
2009-03-06 13:24:58.857946
</code></pre>
<p>and I would like to compute the day of year that is sensitive of leap years. e.g. oday (March 6, 2009) is the 65th day of 2009. <a href="http://mistupid.com/calendar/dayofyear.htm">Here's web-based DateTime calculator</a>.</p>
<p>Anyway, I see a two options:</p>
<ol>
<li><p>Create a number_of_days_in_month array = [31, 28, ...], decide if it's a leap year, manually sum up the days</p></li>
<li><p>Use datetime.timedelta to make a guess & then binary search for the correct day of year:</p></li>
</ol>
<p>.</p>
<pre><code>>>> import datetime
>>> YEAR = 2009
>>> DAY_OF_YEAR = 62
>>> d = datetime.date(YEAR, 1, 1) + datetime.timedelta(DAY_OF_YEAR - 1)
</code></pre>
<p>These both feel pretty clunky & I have a gut feeling that there's a more "Pythonic" way of calculating day of year. Any ideas/suggestions?</p>
| 60
|
2009-03-06T20:34:32Z
| 13,032,755
|
<p><a href="http://stackoverflow.com/a/623312/40785">DZinX's answer</a> is a great answer for the question. I found this question while looking for the inverse function. I found this to work :</p>
<pre><code>import datetime
datetime.datetime.strptime('1936-077T13:14:15','%Y-%jT%H:%M:%S')
>>>> datetime.datetime(1936, 3, 17, 13, 14, 15)
datetime.datetime.strptime('1936-077T13:14:15','%Y-%jT%H:%M:%S').timetuple().tm_yday
>>>> 77
</code></pre>
<p>I'm not sure of etiquette around here, but I thought a pointer to the inverse function might be useful for others like me.</p>
| 7
|
2012-10-23T14:28:51Z
|
[
"python",
"datetime"
] |
Convert Year/Month/Day to Day of Year in Python
| 620,305
|
<p>I'm using the Python "datetime" module, i.e.:</p>
<pre><code>>>> import datetime
>>> today = datetime.datetime.now()
>>> print today
2009-03-06 13:24:58.857946
</code></pre>
<p>and I would like to compute the day of year that is sensitive of leap years. e.g. oday (March 6, 2009) is the 65th day of 2009. <a href="http://mistupid.com/calendar/dayofyear.htm">Here's web-based DateTime calculator</a>.</p>
<p>Anyway, I see a two options:</p>
<ol>
<li><p>Create a number_of_days_in_month array = [31, 28, ...], decide if it's a leap year, manually sum up the days</p></li>
<li><p>Use datetime.timedelta to make a guess & then binary search for the correct day of year:</p></li>
</ol>
<p>.</p>
<pre><code>>>> import datetime
>>> YEAR = 2009
>>> DAY_OF_YEAR = 62
>>> d = datetime.date(YEAR, 1, 1) + datetime.timedelta(DAY_OF_YEAR - 1)
</code></pre>
<p>These both feel pretty clunky & I have a gut feeling that there's a more "Pythonic" way of calculating day of year. Any ideas/suggestions?</p>
| 60
|
2009-03-06T20:34:32Z
| 25,852,628
|
<p>I want to present performance of different approaches, on Python 3.4, Linux x64. Excerpt from line profiler:</p>
<pre><code> Line # Hits Time Per Hit % Time Line Contents
==============================================================
(...)
823 1508 11334 7.5 41.6 yday = int(period_end.strftime('%j'))
824 1508 2492 1.7 9.1 yday = period_end.toordinal() - date(period_end.year, 1, 1).toordinal() + 1
825 1508 1852 1.2 6.8 yday = (period_end - date(period_end.year, 1, 1)).days + 1
826 1508 5078 3.4 18.6 yday = period_end.timetuple().tm_yday
(...)
</code></pre>
<p>So most efficient is</p>
<pre><code>yday = (period_end - date(period_end.year, 1, 1)).days
</code></pre>
| 3
|
2014-09-15T16:29:18Z
|
[
"python",
"datetime"
] |
Convert Year/Month/Day to Day of Year in Python
| 620,305
|
<p>I'm using the Python "datetime" module, i.e.:</p>
<pre><code>>>> import datetime
>>> today = datetime.datetime.now()
>>> print today
2009-03-06 13:24:58.857946
</code></pre>
<p>and I would like to compute the day of year that is sensitive of leap years. e.g. oday (March 6, 2009) is the 65th day of 2009. <a href="http://mistupid.com/calendar/dayofyear.htm">Here's web-based DateTime calculator</a>.</p>
<p>Anyway, I see a two options:</p>
<ol>
<li><p>Create a number_of_days_in_month array = [31, 28, ...], decide if it's a leap year, manually sum up the days</p></li>
<li><p>Use datetime.timedelta to make a guess & then binary search for the correct day of year:</p></li>
</ol>
<p>.</p>
<pre><code>>>> import datetime
>>> YEAR = 2009
>>> DAY_OF_YEAR = 62
>>> d = datetime.date(YEAR, 1, 1) + datetime.timedelta(DAY_OF_YEAR - 1)
</code></pre>
<p>These both feel pretty clunky & I have a gut feeling that there's a more "Pythonic" way of calculating day of year. Any ideas/suggestions?</p>
| 60
|
2009-03-06T20:34:32Z
| 30,169,668
|
<p>If you have reason to avoid the use of the datetime module, then these functions will work.</p>
<pre><code>def is_leap_year(year):
""" if year is a leap year return True
else return False """
if year % 100 == 0:
return year % 400 == 0
return year % 4 == 0
def doy(Y,M,D):
""" given year, month, day return day of year
Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7 """
if is_leap_year(Y):
K = 1
else:
K = 2
N = int((275 * M) / 9.0) - K * int((M + 9) / 12.0) + D - 30
return N
def ymd(Y,N):
""" given year = Y and day of year = N, return year, month, day
Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7 """
if is_leap_year(Y):
K = 1
else:
K = 2
M = int((9 * (K + N)) / 275.0 + 0.98)
if N < 32:
M = 1
D = N - int((275 * M) / 9.0) + K * int((M + 9) / 12.0) + 30
return Y, M, D
</code></pre>
| 1
|
2015-05-11T13:58:49Z
|
[
"python",
"datetime"
] |
How to import a Django project settings.py Python file from a sub-directory?
| 620,342
|
<p>I created a sub-directory of my Django project called <code>bin</code> where I want to put all command-line run Python scripts. Some of these scripts need to import my Django project <code>settings.py</code> file that is in a parent directory of <code>bin</code>.</p>
<p>How can I import the <code>settings.py</code> file from a sub-directory of the project?</p>
<p>The code that I use in my command-line script to set into the "Django context" of the project is:</p>
<pre><code>from django.core.management import setup_environ
import settings
setup_environ(settings)
</code></pre>
<p>This works fine if the script is in the root directory of my project.</p>
<p>I tried the following two hacks to import the <code>settings.py</code> file and then setup the project:</p>
<pre><code>import os
os.chdir("..")
import sys
sys.path = [str(sys.path[0]) + "/../"] + sys.path
</code></pre>
<p>The cruel hack can import <code>settings.py</code>, but then I get the error:</p>
<pre><code>project_module = __import__(project_name, {}, {}, [''])
ValueError: Empty module name
</code></pre>
| 16
|
2009-03-06T20:42:11Z
| 620,364
|
<p>Add the parent directory to your path:</p>
<pre><code>import sys
sys.path.append('../')
import settings
</code></pre>
<p><strong>Update from comments:</strong></p>
<blockquote>
<p>Don't forget the <code>__init__.py</code> file in
the directory that has your
settings.py â S.Lott</p>
</blockquote>
| 2
|
2009-03-06T20:48:27Z
|
[
"python",
"django"
] |
How to import a Django project settings.py Python file from a sub-directory?
| 620,342
|
<p>I created a sub-directory of my Django project called <code>bin</code> where I want to put all command-line run Python scripts. Some of these scripts need to import my Django project <code>settings.py</code> file that is in a parent directory of <code>bin</code>.</p>
<p>How can I import the <code>settings.py</code> file from a sub-directory of the project?</p>
<p>The code that I use in my command-line script to set into the "Django context" of the project is:</p>
<pre><code>from django.core.management import setup_environ
import settings
setup_environ(settings)
</code></pre>
<p>This works fine if the script is in the root directory of my project.</p>
<p>I tried the following two hacks to import the <code>settings.py</code> file and then setup the project:</p>
<pre><code>import os
os.chdir("..")
import sys
sys.path = [str(sys.path[0]) + "/../"] + sys.path
</code></pre>
<p>The cruel hack can import <code>settings.py</code>, but then I get the error:</p>
<pre><code>project_module = __import__(project_name, {}, {}, [''])
ValueError: Empty module name
</code></pre>
| 16
|
2009-03-06T20:42:11Z
| 620,462
|
<p>I think your approach may be over-complicating something that Django 1.x provides for you. As long as your project is in your python path, you can set the environment variable DJANGO_SETTINGS_MODULE at the top of your script like so:</p>
<pre><code>import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
</code></pre>
<p>In your command line script where you need to read your settings, simply import the settings module from 'django.conf' as you would do in your application code:</p>
<pre><code>from django.conf import settings
</code></pre>
<p>And presto, you have your settings and a Django-enabled environment for your script.</p>
<p>I personally prefer to set my DJANGO_SETTINGS_MODULE using '/usr/bin/env' in a bash script called 'proj_env' so I don't have to repeat it </p>
<pre><code>#!/bin/bash
proj_env="DJANGO_SETTINGS_MODULE=myproject.settings"
/usr/bin/env $proj_env ${*}
</code></pre>
<p>With this, now I can run any python script with my Django application in context:</p>
<pre><code>proj_env python -m 'myproject.bin.myscript'
</code></pre>
<p>If you use virtualenv, this also gives you a good place to source the activate script.</p>
<p>etc. etc.</p>
| 14
|
2009-03-06T21:21:17Z
|
[
"python",
"django"
] |
How to import a Django project settings.py Python file from a sub-directory?
| 620,342
|
<p>I created a sub-directory of my Django project called <code>bin</code> where I want to put all command-line run Python scripts. Some of these scripts need to import my Django project <code>settings.py</code> file that is in a parent directory of <code>bin</code>.</p>
<p>How can I import the <code>settings.py</code> file from a sub-directory of the project?</p>
<p>The code that I use in my command-line script to set into the "Django context" of the project is:</p>
<pre><code>from django.core.management import setup_environ
import settings
setup_environ(settings)
</code></pre>
<p>This works fine if the script is in the root directory of my project.</p>
<p>I tried the following two hacks to import the <code>settings.py</code> file and then setup the project:</p>
<pre><code>import os
os.chdir("..")
import sys
sys.path = [str(sys.path[0]) + "/../"] + sys.path
</code></pre>
<p>The cruel hack can import <code>settings.py</code>, but then I get the error:</p>
<pre><code>project_module = __import__(project_name, {}, {}, [''])
ValueError: Empty module name
</code></pre>
| 16
|
2009-03-06T20:42:11Z
| 622,457
|
<p>This is going one level up from your question, but probably the best solution here is to implement your scripts as <a href="http://docs.djangoproject.com/en/dev/howto/custom-management-commands/#howto-custom-management-commands">custom manage.py (django-admin.py) commands</a>. This gives you all of Django's functionality (including settings) for free with no ugly path-hacking, as well as command-line niceties like options parsing. I've never seen a good reason to write Django-related command-line scripts any other way.</p>
| 10
|
2009-03-07T20:38:00Z
|
[
"python",
"django"
] |
How to jump to a particular line in a huge text file?
| 620,367
|
<p>Are there any alternatives to the code below:</p>
<pre><code>startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
</code></pre>
<p>If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.</p>
| 74
|
2009-03-06T20:49:52Z
| 620,397
|
<p><a href="http://docs.python.org/library/linecache.html" rel="nofollow">linecache</a>:</p>
<blockquote>
<p>The <a href="https://docs.python.org/3/library/linecache.html#module-linecache" rel="nofollow"><code>linecache</code></a> module allows one to get any line from a Python source file, while attempting to optimize internally, using a cache, the common case where many lines are read from a single file. This is used by the <a href="https://docs.python.org/3/library/traceback.html#module-traceback" rel="nofollow"><code>traceback</code></a> module to retrieve source lines for inclusion in the formatted traceback...</p>
</blockquote>
| 18
|
2009-03-06T20:58:06Z
|
[
"python",
"text-files"
] |
How to jump to a particular line in a huge text file?
| 620,367
|
<p>Are there any alternatives to the code below:</p>
<pre><code>startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
</code></pre>
<p>If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.</p>
| 74
|
2009-03-06T20:49:52Z
| 620,416
|
<p>If you know in advance the position in the file (rather the line number), you can use <a href="http://docs.python.org/library/stdtypes.html#file.seek" rel="nofollow">file.seek()</a> to go to that position.</p>
<p><strong>Edit</strong>: you can use the <a href="http://docs.python.org/library/linecache.html#linecache.getline" rel="nofollow">linecache.getline(filename, lineno)</a> function, which will return the contents of the line lineno, but only after reading the entire file into memory. Good if you're randomly accessing lines from within the file (as python itself might want to do to print a traceback) but not good for a 15MB file.</p>
| 2
|
2009-03-06T21:06:13Z
|
[
"python",
"text-files"
] |
How to jump to a particular line in a huge text file?
| 620,367
|
<p>Are there any alternatives to the code below:</p>
<pre><code>startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
</code></pre>
<p>If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.</p>
| 74
|
2009-03-06T20:49:52Z
| 620,480
|
<p>I'm probably spoiled by abundant ram, but 15 M is not huge. Reading into memory with <code>readlines()</code> is what I usually do with files of this size. Accessing a line after that is trivial.</p>
| 12
|
2009-03-06T21:25:53Z
|
[
"python",
"text-files"
] |
How to jump to a particular line in a huge text file?
| 620,367
|
<p>Are there any alternatives to the code below:</p>
<pre><code>startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
</code></pre>
<p>If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.</p>
| 74
|
2009-03-06T20:49:52Z
| 620,492
|
<p>You can't jump ahead without reading in the file at least once, since you don't know where the line breaks are. You could do something like:</p>
<pre><code># Read in the file once and build a list of line offsets
line_offset = []
offset = 0
for line in file:
line_offset.append(offset)
offset += len(line)
file.seek(0)
# Now, to skip to line n (with the first line being line 0), just do
file.seek(line_offset[n])
</code></pre>
| 67
|
2009-03-06T21:28:23Z
|
[
"python",
"text-files"
] |
How to jump to a particular line in a huge text file?
| 620,367
|
<p>Are there any alternatives to the code below:</p>
<pre><code>startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
</code></pre>
<p>If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.</p>
| 74
|
2009-03-06T20:49:52Z
| 620,494
|
<p>You don't really have that many options if the lines are of different length... you sadly need to process the line ending characters to know when you've progressed to the next line.</p>
<p>You can, however, dramatically speed this up AND reduce memory usage by changing the last parameter to "open" to something not 0.</p>
<p>0 means the file reading operation is unbuffered, which is very slow and disk intensive. 1 means the file is line buffered, which would be an improvement. Anything above 1 (say 8k.. ie: 8096, or higher) reads chunks of the file into memory. You still access it through <code>for line in open(etc):</code>, but python only goes a bit at a time, discarding each buffered chunk after its processed.</p>
| 19
|
2009-03-06T21:28:28Z
|
[
"python",
"text-files"
] |
How to jump to a particular line in a huge text file?
| 620,367
|
<p>Are there any alternatives to the code below:</p>
<pre><code>startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
</code></pre>
<p>If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.</p>
| 74
|
2009-03-06T20:49:52Z
| 620,502
|
<p>If you don't want to read the entire file in memory .. you may need to come up with some format other than plain text.</p>
<p>of course it all depends on what you're trying to do, and how often you will jump across the file.</p>
<p>For instance, if you're gonna be jumping to lines <em>many times</em> in the same file, and you know that the file does not change while working with it, you can do this:<br />
First, pass through the whole file, and record the "seek-location" of some key-line-numbers (such as, ever 1000 lines),<br />
Then if you want line 12005, jump to the position of 12000 (which you've recorded) then read 5 lines and you'll know you're in line 12005
and so on</p>
| 1
|
2009-03-06T21:31:08Z
|
[
"python",
"text-files"
] |
How to jump to a particular line in a huge text file?
| 620,367
|
<p>Are there any alternatives to the code below:</p>
<pre><code>startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
</code></pre>
<p>If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.</p>
| 74
|
2009-03-06T20:49:52Z
| 620,513
|
<p>Since there is no way to determine the lenght of all lines without reading them, you have no choice but to iterate over all lines before your starting line. All you can do is to make it look nice. If the file is really huge then you might want to use a generator based approach:</p>
<pre><code>from itertools import dropwhile
def iterate_from_line(f, start_from_line):
return (l for i, l in dropwhile(lambda x: x[0] < start_from_line, enumerate(f)))
for line in iterate_from_line(open(filename, "r", 0), 141978):
DoSomethingWithThisLine(line)
</code></pre>
<p>Note: the index is zero based in this approach.</p>
| 4
|
2009-03-06T21:33:41Z
|
[
"python",
"text-files"
] |
How to jump to a particular line in a huge text file?
| 620,367
|
<p>Are there any alternatives to the code below:</p>
<pre><code>startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
</code></pre>
<p>If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.</p>
| 74
|
2009-03-06T20:49:52Z
| 620,712
|
<p>Do the lines themselves contain any index information? If the content of each line was something like "<code><line index>:Data</code>", then the <code>seek()</code> approach could be used to do a binary search through the file, even if the amount of <code>Data</code> is variable. You'd seek to the midpoint of the file, read a line, check whether its index is higher or lower than the one you want, etc.</p>
<p>Otherwise, the best you can do is just <code>readlines()</code>. If you don't want to read all 15MB, you can use the <code>sizehint</code> argument to at least replace a lot of <code>readline()</code>s with a smaller number of calls to <code>readlines()</code>.</p>
| 1
|
2009-03-06T22:33:30Z
|
[
"python",
"text-files"
] |
How to jump to a particular line in a huge text file?
| 620,367
|
<p>Are there any alternatives to the code below:</p>
<pre><code>startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
</code></pre>
<p>If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.</p>
| 74
|
2009-03-06T20:49:52Z
| 621,306
|
<p>Here's an example using 'readlines(sizehint)' to read a chunk of lines at a time. DNS pointed out that solution. I wrote this example because the other examples here are single-line oriented.</p>
<pre><code>def getlineno(filename, lineno):
if lineno < 1:
raise TypeError("First line is line 1")
f = open(filename)
lines_read = 0
while 1:
lines = f.readlines(100000)
if not lines:
return None
if lines_read + len(lines) >= lineno:
return lines[lineno-lines_read-1]
lines_read += len(lines)
print getlineno("nci_09425001_09450000.smi", 12000)
</code></pre>
| 0
|
2009-03-07T04:24:33Z
|
[
"python",
"text-files"
] |
How to jump to a particular line in a huge text file?
| 620,367
|
<p>Are there any alternatives to the code below:</p>
<pre><code>startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
</code></pre>
<p>If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.</p>
| 74
|
2009-03-06T20:49:52Z
| 2,727,585
|
<p>What generates the file you want to process? If it is something under your control, you could generate an index (which line is at which position.) at the time the file is appended to. The index file can be of fixed line size (space padded or 0 padded numbers) and will definitely be smaller. And thus can be read and processed qucikly. </p>
<ul>
<li>Which line do you want?. </li>
<li>Calculate byte offset of corresponding line number in index file(possible because line size of index file is constant).</li>
<li>Use seek or whatever to directly jump to get the line from index file.</li>
<li>Parse to get byte offset for corresponding line of actual file.</li>
</ul>
| 2
|
2010-04-28T07:39:40Z
|
[
"python",
"text-files"
] |
How to jump to a particular line in a huge text file?
| 620,367
|
<p>Are there any alternatives to the code below:</p>
<pre><code>startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
</code></pre>
<p>If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.</p>
| 74
|
2009-03-06T20:49:52Z
| 24,598,751
|
<p>I have had the same problem (need to retrieve from huge file specific line).</p>
<p>Surely, I can every time run through all records in file and stop it when counter will be equal to target line, but it does not work effectively in a case when you want to obtain plural number of specific rows. That caused main issue to be resolved - how handle directly to necessary place of file.</p>
<p>I found out next decision:
Firstly I completed dictionary with start position of each line (key is line number, and value â cumulated length of previous lines).</p>
<pre><code>t = open(file,ârâ)
dict_pos = {}
kolvo = 0
length = 0
for each in t:
dict_pos[kolvo] = length
length = length+len(each)
kolvo = kolvo+1
</code></pre>
<p>ultimately, aim function:</p>
<pre><code>def give_line(line_number):
t.seek(dict_pos.get(line_number))
line = t.readline()
return line
</code></pre>
<p>t.seek(line_number) â command that execute pruning of file up to line inception.
So, if you next commit readline â you obtain your target line.</p>
<p>Using such approach I have saved significant part of time. </p>
| 1
|
2014-07-06T18:03:39Z
|
[
"python",
"text-files"
] |
How to jump to a particular line in a huge text file?
| 620,367
|
<p>Are there any alternatives to the code below:</p>
<pre><code>startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
</code></pre>
<p>If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.</p>
| 74
|
2009-03-06T20:49:52Z
| 31,884,215
|
<p>You may use mmap to find the offset of the lines. MMap seems to be the fastest way to process a file</p>
<p>example:</p>
<pre><code>with open('input_file', "r+b") as f:
mapped = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)
i = 1
for line in iter(mapped.readline, ""):
if i == Line_I_want_to_jump:
offsets = mapped.tell()
i+=1
</code></pre>
<p>then use f.seek(offsets) to move to the line you need</p>
| 0
|
2015-08-07T18:15:27Z
|
[
"python",
"text-files"
] |
How to jump to a particular line in a huge text file?
| 620,367
|
<p>Are there any alternatives to the code below:</p>
<pre><code>startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
</code></pre>
<p>If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.</p>
| 74
|
2009-03-06T20:49:52Z
| 32,673,701
|
<p>Can use this function to return line n:</p>
<pre><code>def skipton(infile, n):
with open(infile,'r') as fi:
for i in range(n-1):
fi.next()
return fi.next()
</code></pre>
| -1
|
2015-09-19T22:05:15Z
|
[
"python",
"text-files"
] |
How to jump to a particular line in a huge text file?
| 620,367
|
<p>Are there any alternatives to the code below:</p>
<pre><code>startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
</code></pre>
<p>If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.</p>
| 74
|
2009-03-06T20:49:52Z
| 36,174,685
|
<p>If you're dealing with a <em>text file</em> & based on <em>linux system</em>, you could use the linux commands. <br>
For me, this worked well!</p>
<pre><code>import commands
def read_line(path, line=1):
return commands.getoutput('head -%s %s | tail -1' % (line, path))
line_to_jump = 141978
read_line("path_to_large_text_file", line_to_jump)
</code></pre>
| 0
|
2016-03-23T09:47:33Z
|
[
"python",
"text-files"
] |
How to jump to a particular line in a huge text file?
| 620,367
|
<p>Are there any alternatives to the code below:</p>
<pre><code>startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
</code></pre>
<p>If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.</p>
| 74
|
2009-03-06T20:49:52Z
| 36,854,340
|
<p>I am suprised no one mentioned islice</p>
<pre><code>line = next(itertools.islice(Fhandle,index_of_interest,index_of_interest+1),None) # just the one line
</code></pre>
<p>or if you want the whole rest of the file</p>
<pre><code>rest_of_file = itertools.islice(Fhandle,index_of_interest)
for line in rest_of_file:
print line
</code></pre>
<p>or if you want every other line from the file</p>
<pre><code>rest_of_file = itertools.islice(Fhandle,index_of_interest,None,2)
for odd_line in rest_of_file:
print odd_line
</code></pre>
| 1
|
2016-04-26T02:36:41Z
|
[
"python",
"text-files"
] |
What's the best way to find the closest matching type to an existing type?
| 620,530
|
<p>I've got a registry of classes and types in Python 2.5, like so:</p>
<pre><code>class ClassA(object):
pass
class ClassB(ClassA):
pass
MY_TYPES = {
basestring : 'A string',
int : 'An integer',
ClassA : 'This is ClassA or a subclass',
}
</code></pre>
<p>I'd like to be able to pass types to a function, and have it look up the closest matching type in the hierarchy. So, looking up <code>str</code> would return <code>"A string"</code> and looking up <code>ClassB</code> would return <code>"This is ClassA or a subclass"</code> The problem is, I don't know how to find the superclass (or, rather, trace the MRO chain) of a type object.</p>
<p>What's the best way of handling this?</p>
| 0
|
2009-03-06T21:37:18Z
| 620,540
|
<p>To get the superclasses of a class, use <code>__bases__</code>:</p>
<pre><code>class ClassA(object):
pass
class ClassB(ClassA):
pass
print ClassB.__bases__
(<class '__main__.ClassA'>,)
</code></pre>
<p>Beware of things like <code>int</code>, though. The base for all of those will be <code><type 'object'></code>. You'll have to do some testing and iteration to match the dict keys you've listed in your example.</p>
<p>Another option would be to use <code>isinstance</code> on any object instance, or <code>issubclass</code> on the parameters, testing each against your dict keys. Some consider <code>isinstance</code> and its ilk to be the mark of the devil, but c'est la vie. Again, though, beware of using <code>issubclass</code> with ints and other such types. You'll probably need to combine a few approaches given your dict keys.</p>
| 2
|
2009-03-06T21:41:28Z
|
[
"python",
"types"
] |
What's the best way to find the closest matching type to an existing type?
| 620,530
|
<p>I've got a registry of classes and types in Python 2.5, like so:</p>
<pre><code>class ClassA(object):
pass
class ClassB(ClassA):
pass
MY_TYPES = {
basestring : 'A string',
int : 'An integer',
ClassA : 'This is ClassA or a subclass',
}
</code></pre>
<p>I'd like to be able to pass types to a function, and have it look up the closest matching type in the hierarchy. So, looking up <code>str</code> would return <code>"A string"</code> and looking up <code>ClassB</code> would return <code>"This is ClassA or a subclass"</code> The problem is, I don't know how to find the superclass (or, rather, trace the MRO chain) of a type object.</p>
<p>What's the best way of handling this?</p>
| 0
|
2009-03-06T21:37:18Z
| 620,547
|
<pre><code>from inspect import getmro
[st for cls, st in MY_TYPES.items() if cls in getmro(ClassB)]
['This is ClassA or a subclass']
</code></pre>
<p>or if you're only interested in first match(es) generator version:</p>
<pre><code>(st for cls, st in MY_TYPES.iteritems() if cls in getmro(ClassB))
</code></pre>
| 4
|
2009-03-06T21:44:48Z
|
[
"python",
"types"
] |
What's the best way to find the closest matching type to an existing type?
| 620,530
|
<p>I've got a registry of classes and types in Python 2.5, like so:</p>
<pre><code>class ClassA(object):
pass
class ClassB(ClassA):
pass
MY_TYPES = {
basestring : 'A string',
int : 'An integer',
ClassA : 'This is ClassA or a subclass',
}
</code></pre>
<p>I'd like to be able to pass types to a function, and have it look up the closest matching type in the hierarchy. So, looking up <code>str</code> would return <code>"A string"</code> and looking up <code>ClassB</code> would return <code>"This is ClassA or a subclass"</code> The problem is, I don't know how to find the superclass (or, rather, trace the MRO chain) of a type object.</p>
<p>What's the best way of handling this?</p>
| 0
|
2009-03-06T21:37:18Z
| 620,577
|
<p>This is really a job for generic functions. See <a href="http://peak.telecommunity.com/DevCenter/RulesReadme" rel="nofollow">PEAK-Rules</a> and <a href="http://www.python.org/dev/peps/pep-3124/" rel="nofollow">PEP 3124</a>. Generic functions will allow you to dispatch arbitrary functions based on argument types, or even more complex expressions.</p>
<p>Or if you're really a sucker for punishment, witness this <a href="http://www.gigamonkeys.com/book/object-reorientation-generic-functions.html" rel="nofollow">chapter</a> from <a href="http://www.gigamonkeys.com/book/" rel="nofollow">Practical Common Lisp</a>.</p>
| 0
|
2009-03-06T21:56:20Z
|
[
"python",
"types"
] |
What's the best way to find the closest matching type to an existing type?
| 620,530
|
<p>I've got a registry of classes and types in Python 2.5, like so:</p>
<pre><code>class ClassA(object):
pass
class ClassB(ClassA):
pass
MY_TYPES = {
basestring : 'A string',
int : 'An integer',
ClassA : 'This is ClassA or a subclass',
}
</code></pre>
<p>I'd like to be able to pass types to a function, and have it look up the closest matching type in the hierarchy. So, looking up <code>str</code> would return <code>"A string"</code> and looking up <code>ClassB</code> would return <code>"This is ClassA or a subclass"</code> The problem is, I don't know how to find the superclass (or, rather, trace the MRO chain) of a type object.</p>
<p>What's the best way of handling this?</p>
| 0
|
2009-03-06T21:37:18Z
| 621,015
|
<blockquote>
<p>(st for cls, st in MY_TYPES.iteritems() if cls in getmro(ClassB))</p>
</blockquote>
<p>The simpler way to write that would be:</p>
<pre><code>(st for cls, st in MY_TYPES.iteritems() if issubclass(ClassB, cls))
</code></pre>
<p>However this does not find the ânearestâ match; if âobjectâ were in the lookup, it could match everything! If you had things that were subclasses of other things in the lookup, or you wanted to support multiple inheritance, you'd have to pick out the one that was the first in MRO:</p>
<pre><code>for cls in inspect.getmro(ClassB):
if cls in MY_TYPES:
print MY_TYPES[cls]
break
else:
print 'Dunno what it is'
</code></pre>
<p>Anyway... I would generally regard type lookups as a little bit of a code smell, is there no nicer way to do what you want?</p>
| 1
|
2009-03-07T00:40:06Z
|
[
"python",
"types"
] |
SQLAlchemy Obtain Primary Key With Autoincrement Before Commit
| 620,610
|
<p>When I have created a table with an auto-incrementing primary key, is there a way to obtain what the primary key would be (that is, do something like reserve the primary key) without actually committing?</p>
<p>I would like to place two operations inside a transaction however one of the operations will depend on what primary key was assigned in the previous operation.</p>
| 32
|
2009-03-06T22:07:19Z
| 620,784
|
<p>You can use multiple transactions and manage it within scope.</p>
| 0
|
2009-03-06T22:57:00Z
|
[
"python",
"sql",
"sqlalchemy"
] |
SQLAlchemy Obtain Primary Key With Autoincrement Before Commit
| 620,610
|
<p>When I have created a table with an auto-incrementing primary key, is there a way to obtain what the primary key would be (that is, do something like reserve the primary key) without actually committing?</p>
<p>I would like to place two operations inside a transaction however one of the operations will depend on what primary key was assigned in the previous operation.</p>
| 32
|
2009-03-06T22:07:19Z
| 620,831
|
<p>You don't need to <code>commit</code>, you just need to <code>flush</code>. Here's some sample code. After the call to <a href="http://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session.flush">flush</a> you can access the primary key that was assigned. Note this is with SA 0.4.8.</p>
<pre><code>from sqlalchemy import *
from sqlalchemy.databases.mysql import *
import sqlalchemy.ext.declarative
Base = sqlalchemy.ext.declarative.declarative_base()
class User(Base):
__tablename__ = 'user'
user_id = Column('user_id', Integer, primary_key=True)
name = Column('name', String)
if __name__ == '__main__':
import unittest
from sqlalchemy.orm import *
import datetime
class Blah(unittest.TestCase):
def setUp(self):
self.engine = create_engine('sqlite:///:memory:', echo=True)
self.sessionmaker = scoped_session(sessionmaker(bind=self.engine))
Base.metadata.bind = self.engine
Base.metadata.create_all()
self.now = datetime.datetime.now()
def test_pkid(self):
user = User(name="Joe")
session = self.sessionmaker()
session.save(user)
session.flush()
print 'user_id', user.user_id
session.commit()
session.close()
unittest.main()
</code></pre>
| 66
|
2009-03-06T23:10:07Z
|
[
"python",
"sql",
"sqlalchemy"
] |
Why do I get unexpected behavior in Python isinstance after pickling?
| 620,844
|
<p>Putting aside whether the use of <a href="http://www.canonical.org/~kragen/isinstance/" rel="nofollow">isinstance is harmful</a>, I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle:</p>
<pre><code>from __future__ import with_statement
import pickle
# Simple class definition
class myclass(object):
def __init__(self, data):
self.data = data
# Create an instance of the class
x = myclass(100)
# Pickle the instance to a file
with open("c:\\pickletest.dat", "wb") as f:
pickle.dump(x, f)
# Replace class with exact same definition
class myclass(object):
def __init__(self, data):
self.data = data
# Read an object from the pickled file
with open("c:\\pickletest.dat", "rb") as f:
x2 = pickle.load(f)
# The class names appear to match
print x.__class__
print x2.__class__
# Uh oh, this fails...(why?)
assert isinstance(x2, x.__class__)
</code></pre>
<p>Can anyone shed some light on why isinstance would fail in this situation? In other words, why does Python think these objects are of two different classes? When I remove the second class definition, <code>isinstance</code> works fine.</p>
| 5
|
2009-03-06T23:17:27Z
| 620,857
|
<p>Change your code to print the <code>id</code> of <code>x.__class__</code> and <code>x2.__class__</code> and you'll see that they are different:</p>
<pre><code>$ python foo4.py
199876736
200015248
</code></pre>
| 2
|
2009-03-06T23:22:08Z
|
[
"python",
"pickle"
] |
Why do I get unexpected behavior in Python isinstance after pickling?
| 620,844
|
<p>Putting aside whether the use of <a href="http://www.canonical.org/~kragen/isinstance/" rel="nofollow">isinstance is harmful</a>, I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle:</p>
<pre><code>from __future__ import with_statement
import pickle
# Simple class definition
class myclass(object):
def __init__(self, data):
self.data = data
# Create an instance of the class
x = myclass(100)
# Pickle the instance to a file
with open("c:\\pickletest.dat", "wb") as f:
pickle.dump(x, f)
# Replace class with exact same definition
class myclass(object):
def __init__(self, data):
self.data = data
# Read an object from the pickled file
with open("c:\\pickletest.dat", "rb") as f:
x2 = pickle.load(f)
# The class names appear to match
print x.__class__
print x2.__class__
# Uh oh, this fails...(why?)
assert isinstance(x2, x.__class__)
</code></pre>
<p>Can anyone shed some light on why isinstance would fail in this situation? In other words, why does Python think these objects are of two different classes? When I remove the second class definition, <code>isinstance</code> works fine.</p>
| 5
|
2009-03-06T23:17:27Z
| 620,866
|
<p>The obvious answer, because its not the same class.</p>
<p>Its a similar class, but not the same.</p>
<pre><code>class myclass(object):
pass
x = myclass()
class myclass(object):
pass
y = myclass()
assert id(x.__class__) == id(y.__class__) # Will fail, not the same object
x.__class__.foo = "bar"
assert y.__class__.foo == "bar" # will raise AttributeError
</code></pre>
| 4
|
2009-03-06T23:24:32Z
|
[
"python",
"pickle"
] |
Why do I get unexpected behavior in Python isinstance after pickling?
| 620,844
|
<p>Putting aside whether the use of <a href="http://www.canonical.org/~kragen/isinstance/" rel="nofollow">isinstance is harmful</a>, I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle:</p>
<pre><code>from __future__ import with_statement
import pickle
# Simple class definition
class myclass(object):
def __init__(self, data):
self.data = data
# Create an instance of the class
x = myclass(100)
# Pickle the instance to a file
with open("c:\\pickletest.dat", "wb") as f:
pickle.dump(x, f)
# Replace class with exact same definition
class myclass(object):
def __init__(self, data):
self.data = data
# Read an object from the pickled file
with open("c:\\pickletest.dat", "rb") as f:
x2 = pickle.load(f)
# The class names appear to match
print x.__class__
print x2.__class__
# Uh oh, this fails...(why?)
assert isinstance(x2, x.__class__)
</code></pre>
<p>Can anyone shed some light on why isinstance would fail in this situation? In other words, why does Python think these objects are of two different classes? When I remove the second class definition, <code>isinstance</code> works fine.</p>
| 5
|
2009-03-06T23:17:27Z
| 620,878
|
<p>This is how the unpickler works (site-packages/pickle.py):</p>
<pre><code>def find_class(self, module, name):
# Subclasses may override this
__import__(module)
mod = sys.modules[module]
klass = getattr(mod, name)
return klass
</code></pre>
<p>To find and instantiate a class.</p>
<p>So of course if you replace a class with an identically named class, the <code>klass = getattr(mod, name)</code> will return the new class, and the instance will be of the new class, and so isinstance will fail.</p>
| 3
|
2009-03-06T23:28:57Z
|
[
"python",
"pickle"
] |
do you know of any python component(s) for syntax highlighting?
| 620,954
|
<p>Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) .</p>
| 1
|
2009-03-07T00:10:37Z
| 620,975
|
<p>Other than pygments? <a href="http://pygments.org/">http://pygments.org/</a></p>
| 9
|
2009-03-07T00:21:01Z
|
[
"python",
"components",
"syntax-highlighting"
] |
do you know of any python component(s) for syntax highlighting?
| 620,954
|
<p>Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) .</p>
| 1
|
2009-03-07T00:10:37Z
| 620,983
|
<p>If you're using gtk+, there's a binding of gtksourceview for Python in <a href="http://ftp.gnome.org/pub/GNOME/sources/gnome-python-extras/2.25/" rel="nofollow">gnome-python-extras</a>. It seems to work well in my experience. The downside: the documentation is less than perfect.</p>
<p>There's also a binding of <a href="http://www.riverbankcomputing.co.uk/software/qscintilla/intro" rel="nofollow">QScintilla</a> for Python if PyQt is your thing.</p>
| 1
|
2009-03-07T00:25:33Z
|
[
"python",
"components",
"syntax-highlighting"
] |
do you know of any python component(s) for syntax highlighting?
| 620,954
|
<p>Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) .</p>
| 1
|
2009-03-07T00:10:37Z
| 621,023
|
<p>You can use <a href="http://www.wxpython.org/docs/api/wx.stc.StyledTextCtrl-class.html" rel="nofollow">StyledTextCtrl</a> in <a href="http://www.wxpython.org" rel="nofollow">wxPython</a>. Check out the official demo for an example (The <em>demo code</em> tab for any demo).</p>
| 1
|
2009-03-07T00:42:14Z
|
[
"python",
"components",
"syntax-highlighting"
] |
do you know of any python component(s) for syntax highlighting?
| 620,954
|
<p>Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) .</p>
| 1
|
2009-03-07T00:10:37Z
| 1,462,099
|
<p>You say "in a GUI app" but don't mention the toolkit.</p>
<p>If you are using PyQt, and need a read-only widget, you can use QWebKit which has a whole HTML widget in it based on WebKit, so it supports pretty much anything, from flash to the ACID2 test.</p>
<p>If you want a read-write widget, Qt's QTextEdit supports syntax highlighting, and I wrote an adapter to let pygments worj with it:</p>
<p><a href="http://lateral.netmanagers.com.ar/weblog/2009/09/21.html#BB831" rel="nofollow">http://lateral.netmanagers.com.ar/weblog/2009/09/21.html#BB831</a></p>
<p>I am sure something similar can be done with other toolkits, but I don't know how.</p>
| 0
|
2009-09-22T19:26:34Z
|
[
"python",
"components",
"syntax-highlighting"
] |
Python function: Find Change from purchase amount
| 621,062
|
<p>I'm looking for the most efficient way to figure out a change amount (Quarters, dimes, nickels, and pennies) from a purchase amount. The purchase amount must be less than $1, and the change is from one dollar. I need to know how many quarters, dimes, nickels, and pennies someone would get back. </p>
<p>Would it be best to set up a dictionary?</p>
| -2
|
2009-03-07T00:58:59Z
| 621,079
|
<p>Your best bet is to probably have a sorted dictionary of coin sizes, and then loop through them checking if your change is greater than the value, add that coin and subtract the value, otherwise move along to the next row in the dictionary. </p>
<p>Eg</p>
<pre><code>Coins = [50, 25, 10, 5, 2, 1]
ChangeDue = 87
CoinsReturned = []
For I in coins:
While I >= ChangeDue:
CoinsReturned.add(I)
ChangeDue = ChangeDue - I
</code></pre>
<p>Forgive my lousy python syntax there. Hope that's enough to go on. </p>
| 0
|
2009-03-07T01:11:34Z
|
[
"python",
"dictionary",
"coin-change"
] |
Python function: Find Change from purchase amount
| 621,062
|
<p>I'm looking for the most efficient way to figure out a change amount (Quarters, dimes, nickels, and pennies) from a purchase amount. The purchase amount must be less than $1, and the change is from one dollar. I need to know how many quarters, dimes, nickels, and pennies someone would get back. </p>
<p>Would it be best to set up a dictionary?</p>
| -2
|
2009-03-07T00:58:59Z
| 621,118
|
<p>Gee, you mean this isn't problem 2b in every programming course any more? Eh, probably not, they don't seem to teach people how to make change any more either. (Or maybe they do: is this a homework assignment?)</p>
<p>If you find someone over about 50 and have them make change for you, it works like this. Say you have a check for $3.52 and you hand the cashier a twnty. They'll make change by saying "three fifty-two" then</p>
<ul>
<li>count back three pennies, saying "three, four, five" (3.55)</li>
<li>count back 2 nickels, (3.60, 3.65)</li>
<li>count back a dime (3.75)</li>
<li>a quarter (4 dollars)</li>
<li>a dollar bill (five dollars)</li>
<li>a $5 bill (ten dollars)</li>
<li>a $10 bill (twenty.)</li>
</ul>
<p>That's at heart a recursive process: you count back the current denomination until the current amount plus the next denomination comes out even. Then move up to the next denomination.</p>
<p>You can, of course, do it iteratively, as above.</p>
| 7
|
2009-03-07T01:36:04Z
|
[
"python",
"dictionary",
"coin-change"
] |
Python function: Find Change from purchase amount
| 621,062
|
<p>I'm looking for the most efficient way to figure out a change amount (Quarters, dimes, nickels, and pennies) from a purchase amount. The purchase amount must be less than $1, and the change is from one dollar. I need to know how many quarters, dimes, nickels, and pennies someone would get back. </p>
<p>Would it be best to set up a dictionary?</p>
| -2
|
2009-03-07T00:58:59Z
| 621,133
|
<p>This is probably pretty fast - just a few operations per denomination:</p>
<pre><code>def change(amount):
money = ()
for coin in [25,10,5,1]
num = amount/coin
money += (coin,) * num
amount -= coin * num
return money
</code></pre>
| 4
|
2009-03-07T01:49:36Z
|
[
"python",
"dictionary",
"coin-change"
] |
Python function: Find Change from purchase amount
| 621,062
|
<p>I'm looking for the most efficient way to figure out a change amount (Quarters, dimes, nickels, and pennies) from a purchase amount. The purchase amount must be less than $1, and the change is from one dollar. I need to know how many quarters, dimes, nickels, and pennies someone would get back. </p>
<p>Would it be best to set up a dictionary?</p>
| -2
|
2009-03-07T00:58:59Z
| 631,502
|
<p>This problem could be solved pretty easy with integer partitions from number theory. I wrote a recursive function that takes a number and a list of partitions and returns the number of possible combinations that would make up the given number.</p>
<p><a href="http://sandboxrichard.blogspot.com/2009/03/integer-partitions-and-wiki-smarts.html" rel="nofollow">http://sandboxrichard.blogspot.com/2009/03/integer-partitions-and-wiki-smarts.html</a></p>
<p>It's not exactly what you want, but it could be easily modified to get your result.</p>
| 0
|
2009-03-10T17:46:29Z
|
[
"python",
"dictionary",
"coin-change"
] |
Python function: Find Change from purchase amount
| 621,062
|
<p>I'm looking for the most efficient way to figure out a change amount (Quarters, dimes, nickels, and pennies) from a purchase amount. The purchase amount must be less than $1, and the change is from one dollar. I need to know how many quarters, dimes, nickels, and pennies someone would get back. </p>
<p>Would it be best to set up a dictionary?</p>
| -2
|
2009-03-07T00:58:59Z
| 26,681,495
|
<p>The above soloution working.</p>
<pre><code>amount=int(input("Please enter amount in pence"))
coins = [50, 25, 10, 5, 2, 1]
coinsReturned = []
for i in coins:
while amount >=i:
coinsReturned.append(i)
amount = amount - i
print(coinsReturned)
</code></pre>
<p>Alternatively a solution can reached by using the floor and mod functions.</p>
<pre><code>amount = int(input( "Please enter amount in pence" ))
# math floor of 50
fifty = amount // 50
# mod of 50 and floor of 20
twenty = amount % 50 // 20
# mod of 50 and 20 and floor of 10
ten = amount % 50 % 20 // 10
# mod of 50 , 20 and 10 and floor of 5
five = amount % 50 % 20 % 10 // 5
# mod of 50 , 20 , 10 and 5 and floor of 2
two = amount % 50 % 20 % 10 % 5 // 2
# mod of 50 , 20 , 10 , 5 and 2 and floor of 1
one = amount % 50 % 20 % 10 % 5 % 2 //1
print("50p>>> " , fifty , " 20p>>> " , twenty , " 10p>>> " , ten , " 5p>>> " , five , " 2p>>> " , two , " 1p>>> " , one )
</code></pre>
<p>Or another solution</p>
<pre><code>amount=int(input("Please enter the change to be given"))
endAmount=amount
coins=[50,25,10,5,2,1]
listOfCoins=["fifty" ,"twenty five", "ten", "five", "two" , "one"]
change = []
for coin in coins:
holdingAmount=amount
amount=amount//coin
change.append(amount)
amount=holdingAmount%coin
print("The minimum coinage to return from " ,endAmount, "p is as follows")
for i in range(len(coins)):
print("There's " , change[i] ,"....", listOfCoins[i] , "pence pieces in your change" )
</code></pre>
| 0
|
2014-10-31T18:47:45Z
|
[
"python",
"dictionary",
"coin-change"
] |
Django Forms Newbie Question
| 621,121
|
<p>Alright, I'm at a loss with the Django Forms, as the documentation just doesn't seem to quite cover what I'm looking for. At least it seems to come to a screeching halt once you get past the most rudimentary of forms. I'm more than willing to take a link to <em>good</em> documentation, or a link to a good book that covers this topic, as an answer. Basically, this is how it breaks down, I have 3 models (quiz, questions, answers). I have 20 questions, with 4 potential answers (multi-choice), per quiz. The numbers can vary, but you get the point. </p>
<p>I need to create a form for these items, much like you'd expect in a multiple choice quiz. However, when I create the form by hand in the templates, rather than using django.forms, I get the following:</p>
<p>invalid literal for int() with base 10: 'test'</p>
<p>So I'm trying to mess with the django.forms, but I guess I'm just not grasping the idea of how to build a proper form out of those. Any help would be greatly appreciated, thanks.</p>
<p>For what it's worth here are the models:</p>
<pre><code>class Quiz(models.Model):
label = models.CharField(blank=True, max_length=400)
slug = models.SlugField()
def __unicode__(self):
return self.label
class Question(models.Model):
label = models.CharField(blank=True, max_length=400)
quiz = models.ForeignKey(Quiz)
def __unicode__(self):
return self.label
class Answer(models.Model):
label = models.CharField(blank=True, max_length=400)
question = models.ForeignKey(Question)
correct = models.BooleanField()
def __unicode__(self):
return self.label
</code></pre>
| 4
|
2009-03-07T01:40:11Z
| 621,254
|
<p>First, you create a ModelForm for a given Model. In this example I'm doing it for Quiz but you can rinse and repeat for your other models. For giggles, I'm making the "label" be a Select box with preset choices:</p>
<pre><code>from django.models import BaseModel
from django import forms
from django.forms import ModelForm
CHOICES_LABEL = (
('label1', 'Label One'),
('label2', 'Label Two')
)
class Quiz(models.Model):
label = models.CharField(blank=True, max_length=400)
slug = models.SlugField()
def __unicode__(self):
return self.label
class QuizForm(ModelForm):
# Change the 'label' widget to a select box.
label = forms.CharField(widget=forms.Select(choices=CHOICES_LABEL))
class Meta:
# This tells django to get attributes from the Quiz model
model=Quiz
</code></pre>
<p>Next, in your views.py you might have something like this:</p>
<pre><code>from django.shortcuts import render_to_response
from forms import *
import my_quiz_model
def displayQuizForm(request, *args, **kwargs):
if request.method == 'GET':
# Create an empty Quiz object.
# Alternately you can run a query to edit an existing object.
quiz = Quiz()
form = QuizForm(instance=Quiz)
# Render the template and pass the form object along to it.
return render_to_response('form_template.html',{'form': form})
elif request.method == 'POST' and request.POST.get('action') == 'Save':
form = Quiz(request.POST, instance=account)
form.save()
return HttpResponseRedirect("http://example.com/myapp/confirmsave")
</code></pre>
<p>Finally your template would look like this:</p>
<pre><code><html>
<title>My Quiz Form</title>
<body>
<form id="form" method="post" action=".">
<ul>
{{ form.as_ul }}
</ul>
<input type="submit" name="action" value="Save">
<input type="submit" name="action" value="Cancel">
</form>
</body>
</html>
</code></pre>
| 2
|
2009-03-07T03:33:42Z
|
[
"python",
"django",
"forms"
] |
Django Forms Newbie Question
| 621,121
|
<p>Alright, I'm at a loss with the Django Forms, as the documentation just doesn't seem to quite cover what I'm looking for. At least it seems to come to a screeching halt once you get past the most rudimentary of forms. I'm more than willing to take a link to <em>good</em> documentation, or a link to a good book that covers this topic, as an answer. Basically, this is how it breaks down, I have 3 models (quiz, questions, answers). I have 20 questions, with 4 potential answers (multi-choice), per quiz. The numbers can vary, but you get the point. </p>
<p>I need to create a form for these items, much like you'd expect in a multiple choice quiz. However, when I create the form by hand in the templates, rather than using django.forms, I get the following:</p>
<p>invalid literal for int() with base 10: 'test'</p>
<p>So I'm trying to mess with the django.forms, but I guess I'm just not grasping the idea of how to build a proper form out of those. Any help would be greatly appreciated, thanks.</p>
<p>For what it's worth here are the models:</p>
<pre><code>class Quiz(models.Model):
label = models.CharField(blank=True, max_length=400)
slug = models.SlugField()
def __unicode__(self):
return self.label
class Question(models.Model):
label = models.CharField(blank=True, max_length=400)
quiz = models.ForeignKey(Quiz)
def __unicode__(self):
return self.label
class Answer(models.Model):
label = models.CharField(blank=True, max_length=400)
question = models.ForeignKey(Question)
correct = models.BooleanField()
def __unicode__(self):
return self.label
</code></pre>
| 4
|
2009-03-07T01:40:11Z
| 622,328
|
<p>Yeah I have to agree the documentation and examples are really lacking here. The is no out of the box solution for the case you are describing because it goes three layers deep: quiz->question->answer.</p>
<p>Django has <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets">model inline formsets</a> which solve the problem for two layers deep. What you will need to do to generate the form you want is:</p>
<ol>
<li>Load up a quiz form (just a label text box from your model)</li>
<li>Load a an question formset: QuestionFormSet(queryset=Question.objects.filter(quiz=quiz))</li>
<li>For each question load up a answer formset in much the same way you load up the question formset</li>
<li>Make sure you save everything in the right order: quiz->question->answer, since each lower level needs the foreign key of the item above it</li>
</ol>
| 6
|
2009-03-07T19:13:19Z
|
[
"python",
"django",
"forms"
] |
Accessing a MySQL database from python
| 621,156
|
<p>I have been trying for the past several hours to find a working method of accessing a mysql database in python. The only thing that I've managed to get to compile and install is <code>pyodbc</code> but the necessary driver is not available for ppc leopard. </p>
<p>I already know about <a href="http://stackoverflow.com/questions/372885/how-to-connect-to-a-mysql-database-from-python">this</a>.</p>
<p>UPDATE:<br />
I've gotten <code>setuptools</code> to install, but now MySQL-python won't build.</p>
<p>UPDATE:
Now I've gotten <code>sqlalchemy</code> to install but while it will show up when called by the command line it won't import when used in my cgi script.</p>
| 0
|
2009-03-07T02:06:35Z
| 621,192
|
<p>Install fink. It includes the MySQLdb package.</p>
| 1
|
2009-03-07T02:33:31Z
|
[
"python",
"mysql",
"database"
] |
Accessing a MySQL database from python
| 621,156
|
<p>I have been trying for the past several hours to find a working method of accessing a mysql database in python. The only thing that I've managed to get to compile and install is <code>pyodbc</code> but the necessary driver is not available for ppc leopard. </p>
<p>I already know about <a href="http://stackoverflow.com/questions/372885/how-to-connect-to-a-mysql-database-from-python">this</a>.</p>
<p>UPDATE:<br />
I've gotten <code>setuptools</code> to install, but now MySQL-python won't build.</p>
<p>UPDATE:
Now I've gotten <code>sqlalchemy</code> to install but while it will show up when called by the command line it won't import when used in my cgi script.</p>
| 0
|
2009-03-07T02:06:35Z
| 621,284
|
<p>Try SQL Alchemy.</p>
<p>It is awesome.</p>
| 2
|
2009-03-07T04:06:18Z
|
[
"python",
"mysql",
"database"
] |
Accessing a MySQL database from python
| 621,156
|
<p>I have been trying for the past several hours to find a working method of accessing a mysql database in python. The only thing that I've managed to get to compile and install is <code>pyodbc</code> but the necessary driver is not available for ppc leopard. </p>
<p>I already know about <a href="http://stackoverflow.com/questions/372885/how-to-connect-to-a-mysql-database-from-python">this</a>.</p>
<p>UPDATE:<br />
I've gotten <code>setuptools</code> to install, but now MySQL-python won't build.</p>
<p>UPDATE:
Now I've gotten <code>sqlalchemy</code> to install but while it will show up when called by the command line it won't import when used in my cgi script.</p>
| 0
|
2009-03-07T02:06:35Z
| 709,942
|
<blockquote>
<p>UPDATE: Now I've gotten sqlalchemy to
install but while it will show up when
called by the command line it won't
import when used in my cgi script.</p>
</blockquote>
<p>Can you verify that the Python being invoked from your CGI script is the same as the one you get when you run Python interactively? Check <code>which python</code> and compare it to your webserver CGI settings. That's the only thing I can think of that would cause this - getting it installed in one Python but not the other.</p>
<p>What OS are you on? If you're on something like Ubuntu, <code>sudo apt-get install python-mysqldb</code> is much more reliable than trying to build it yourself.</p>
<p>Also, unless I'm mistaken, SQLAlchemy won't actually help you make the connection itself if you don't have a DB-API2 module (like python-mysqldb) installed - SQLAlchemy sits at the next level up, using the DB-API2 connection and making access to it more Pythonic.</p>
| 0
|
2009-04-02T14:30:53Z
|
[
"python",
"mysql",
"database"
] |
Another Django Forms : Foreign Key in Hidden Field
| 621,212
|
<p>Another Django Form question.</p>
<p>My form :</p>
<pre><code>class PlanForm(forms.ModelForm):
owner = forms.ModelChoiceField(label="",
queryset=Profile.objects.all(),
widget=forms.HiddenInput())
etc...
class Meta:
model = Plan
</code></pre>
<p>Owner, in the model, is a ForeignKey to a Profile.</p>
<p>When I set this form, I set the value of "owner" to be a Profile object.</p>
<p>But when this comes out on the form, it seems to contain the <em>name</em> of the Profile like this :</p>
<pre><code><input type="hidden" name="owner" value="phil" id="id_owner" />
</code></pre>
<p>When the form is submitted and gets back to my views.py I try to handle it like this :</p>
<pre><code> form = PlanForm(request.POST)
...
if form.is_valid():
plan = form.save()
return HttpResponseRedirect('/plans/%s'%plan.id) # Redirect after POST
</code></pre>
<p>However, what I get is a type-conversion error as it fails to turn the string "phil" (the user's name that was saved into the "owner" field) into an Int to turn it into the ForeignKey.</p>
<p>So what is going on here. Should a ModelForm represent a foreign key as a number and transparently handle it? Or do I need to extract the id myself into the owner field of the form? And if so, how and when do I map it back BEFORE I try to validate the form? </p>
| 8
|
2009-03-07T02:59:08Z
| 621,651
|
<p>There's usually no need to put related object into form field. There's a better way and this is specifying parent id in form URL.</p>
<p>Let's assume you need to render a form for new Plan object and then create one when form is bubmitted. Here's how your urlconf would look like:</p>
<pre><code>(r"/profile/(?P<profile_id>\d+)/plan/new", view.new_plan), # uses profile_id to define proper form action
(r"/profile/(?P<profile_id>\d+)/plan/create", view.create_plan) # uses profile_id as a Plan field
</code></pre>
<p>And if you're changing existing object, all you need is plan_id, you can deduce any related record from it.</p>
| 1
|
2009-03-07T10:37:24Z
|
[
"python",
"django",
"forms"
] |
Another Django Forms : Foreign Key in Hidden Field
| 621,212
|
<p>Another Django Form question.</p>
<p>My form :</p>
<pre><code>class PlanForm(forms.ModelForm):
owner = forms.ModelChoiceField(label="",
queryset=Profile.objects.all(),
widget=forms.HiddenInput())
etc...
class Meta:
model = Plan
</code></pre>
<p>Owner, in the model, is a ForeignKey to a Profile.</p>
<p>When I set this form, I set the value of "owner" to be a Profile object.</p>
<p>But when this comes out on the form, it seems to contain the <em>name</em> of the Profile like this :</p>
<pre><code><input type="hidden" name="owner" value="phil" id="id_owner" />
</code></pre>
<p>When the form is submitted and gets back to my views.py I try to handle it like this :</p>
<pre><code> form = PlanForm(request.POST)
...
if form.is_valid():
plan = form.save()
return HttpResponseRedirect('/plans/%s'%plan.id) # Redirect after POST
</code></pre>
<p>However, what I get is a type-conversion error as it fails to turn the string "phil" (the user's name that was saved into the "owner" field) into an Int to turn it into the ForeignKey.</p>
<p>So what is going on here. Should a ModelForm represent a foreign key as a number and transparently handle it? Or do I need to extract the id myself into the owner field of the form? And if so, how and when do I map it back BEFORE I try to validate the form? </p>
| 8
|
2009-03-07T02:59:08Z
| 621,804
|
<p>When you assign a Profile object to the form, Django stringifies it and uses the output as the value in the form. What you would except though, is for Django to use the ID of the object instead. </p>
<p>Luckily, the workaround is simple: Just give the form primary key values of the Profile objects instead:</p>
<pre><code>form = PlanForm(initial={'profile': profile.pk})
</code></pre>
<p>On the other end, when you're working with bound forms, however, they work much more sensibly:</p>
<pre><code>form = PlanForm(request.POST)
if form.is_valid():
print form.cleaned_data['profile'] # the appropriate Profile object
</code></pre>
| 6
|
2009-03-07T12:57:27Z
|
[
"python",
"django",
"forms"
] |
Another Django Forms : Foreign Key in Hidden Field
| 621,212
|
<p>Another Django Form question.</p>
<p>My form :</p>
<pre><code>class PlanForm(forms.ModelForm):
owner = forms.ModelChoiceField(label="",
queryset=Profile.objects.all(),
widget=forms.HiddenInput())
etc...
class Meta:
model = Plan
</code></pre>
<p>Owner, in the model, is a ForeignKey to a Profile.</p>
<p>When I set this form, I set the value of "owner" to be a Profile object.</p>
<p>But when this comes out on the form, it seems to contain the <em>name</em> of the Profile like this :</p>
<pre><code><input type="hidden" name="owner" value="phil" id="id_owner" />
</code></pre>
<p>When the form is submitted and gets back to my views.py I try to handle it like this :</p>
<pre><code> form = PlanForm(request.POST)
...
if form.is_valid():
plan = form.save()
return HttpResponseRedirect('/plans/%s'%plan.id) # Redirect after POST
</code></pre>
<p>However, what I get is a type-conversion error as it fails to turn the string "phil" (the user's name that was saved into the "owner" field) into an Int to turn it into the ForeignKey.</p>
<p>So what is going on here. Should a ModelForm represent a foreign key as a number and transparently handle it? Or do I need to extract the id myself into the owner field of the form? And if so, how and when do I map it back BEFORE I try to validate the form? </p>
| 8
|
2009-03-07T02:59:08Z
| 621,917
|
<p>I suspect that the <code>__unicode__</code> method for the Profile model instance, or the <code>repr</code> thereof is set to return a value other than <code>self.id</code>. For example, I just set this up:</p>
<pre><code># models.py
class Profile(models.Model):
name = models.CharField('profile name', max_length=10)
def __unicode__(self):
return u'%d' % self.id
class Plan(models.Model):
name = models.CharField('plan name', max_length=10)
profile = models.ForeignKey(Profile, related_name='profiles')
def __unicode__(self):
return self.name
# forms.py
class PlanForm(forms.ModelForm):
profile = forms.ModelChoiceField(queryset=Profile.objects.all(),
widget=forms.HiddenInput())
class Meta:
model = Plan
# views.py
def add_plan(request):
if request.method == 'POST':
return HttpResponse(request.POST['profile'])
profile = Profile.objects.all()[0]
form = PlanForm(initial={'profile':profile})
return render_to_response('add_plan.html',
{
'form':form,
},
context_instance=RequestContext(request))
</code></pre>
<p>With that, I see PlanForm.profile rendered thus in the template:</p>
<pre><code><input type="hidden" name="profile" value="1" id="id_profile" />
</code></pre>
| 15
|
2009-03-07T14:40:39Z
|
[
"python",
"django",
"forms"
] |
Another Django Forms : Foreign Key in Hidden Field
| 621,212
|
<p>Another Django Form question.</p>
<p>My form :</p>
<pre><code>class PlanForm(forms.ModelForm):
owner = forms.ModelChoiceField(label="",
queryset=Profile.objects.all(),
widget=forms.HiddenInput())
etc...
class Meta:
model = Plan
</code></pre>
<p>Owner, in the model, is a ForeignKey to a Profile.</p>
<p>When I set this form, I set the value of "owner" to be a Profile object.</p>
<p>But when this comes out on the form, it seems to contain the <em>name</em> of the Profile like this :</p>
<pre><code><input type="hidden" name="owner" value="phil" id="id_owner" />
</code></pre>
<p>When the form is submitted and gets back to my views.py I try to handle it like this :</p>
<pre><code> form = PlanForm(request.POST)
...
if form.is_valid():
plan = form.save()
return HttpResponseRedirect('/plans/%s'%plan.id) # Redirect after POST
</code></pre>
<p>However, what I get is a type-conversion error as it fails to turn the string "phil" (the user's name that was saved into the "owner" field) into an Int to turn it into the ForeignKey.</p>
<p>So what is going on here. Should a ModelForm represent a foreign key as a number and transparently handle it? Or do I need to extract the id myself into the owner field of the form? And if so, how and when do I map it back BEFORE I try to validate the form? </p>
| 8
|
2009-03-07T02:59:08Z
| 621,973
|
<p>Hmm... </p>
<p>This might actually be a security hole.</p>
<p>Suppose a malicious attacker crafted a POST (say, by using XmlHttpRequest from FireBug) and set the profile term to some wacky value, like, your profile ID. Probably not what you wanted?</p>
<p>If possible, you may want to get the profile from the request object itself, rather than what's being submitted from the POST values.</p>
<pre><code>form = PlanForm(request.POST)
if form.is_valid():
plan = form.save(commit=False)
plan.owner = request.user.get_profile()
plan.save()
form.save_m2m() # if neccesary
</code></pre>
| 7
|
2009-03-07T15:14:33Z
|
[
"python",
"django",
"forms"
] |
Another Django Forms : Foreign Key in Hidden Field
| 621,212
|
<p>Another Django Form question.</p>
<p>My form :</p>
<pre><code>class PlanForm(forms.ModelForm):
owner = forms.ModelChoiceField(label="",
queryset=Profile.objects.all(),
widget=forms.HiddenInput())
etc...
class Meta:
model = Plan
</code></pre>
<p>Owner, in the model, is a ForeignKey to a Profile.</p>
<p>When I set this form, I set the value of "owner" to be a Profile object.</p>
<p>But when this comes out on the form, it seems to contain the <em>name</em> of the Profile like this :</p>
<pre><code><input type="hidden" name="owner" value="phil" id="id_owner" />
</code></pre>
<p>When the form is submitted and gets back to my views.py I try to handle it like this :</p>
<pre><code> form = PlanForm(request.POST)
...
if form.is_valid():
plan = form.save()
return HttpResponseRedirect('/plans/%s'%plan.id) # Redirect after POST
</code></pre>
<p>However, what I get is a type-conversion error as it fails to turn the string "phil" (the user's name that was saved into the "owner" field) into an Int to turn it into the ForeignKey.</p>
<p>So what is going on here. Should a ModelForm represent a foreign key as a number and transparently handle it? Or do I need to extract the id myself into the owner field of the form? And if so, how and when do I map it back BEFORE I try to validate the form? </p>
| 8
|
2009-03-07T02:59:08Z
| 13,479,147
|
<p>Since ModelChoiceField inherits from ChoiceFIeld, you should use the <a href="https://docs.djangoproject.com/en/1.4/ref/forms/widgets/#multiplehiddeninput" rel="nofollow">MultipleHiddenInput</a> widget for this:</p>
<pre class="lang-python prettyprint-override"><code>class PlanForm(forms.ModelForm):
owner = forms.ModelChoiceField(
queryset=Profile.objects.all(),
widget=forms.MultipleHiddenInput())
class Meta:
model = Plan
</code></pre>
| 2
|
2012-11-20T17:54:01Z
|
[
"python",
"django",
"forms"
] |
How to print tuples of unicode strings in original language (not u'foo' form)
| 621,321
|
<p>I have a list of tuples of unicode objects:</p>
<pre><code>>>> t = [('äº',), ('ç¬',)]
</code></pre>
<p>Printing this out, I get:</p>
<pre><code>>>> print t
[('\xe4\xba\x80',), ('\xe7\x8a\xac',)]
</code></pre>
<p>which I guess is a list of the utf-8 byte-code representation of those strings?</p>
<p>but what I want to see printed out is, surprise:</p>
<pre><code>[('äº',), ('ç¬',)]
</code></pre>
<p>but I'm having an inordinate amount of trouble getting the bytecode back into a human-readable form. </p>
| 10
|
2009-03-07T04:44:52Z
| 621,329
|
<p>Try:</p>
<pre><code>import codecs, sys
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
</code></pre>
| 0
|
2009-03-07T04:53:25Z
|
[
"python",
"unicode"
] |
How to print tuples of unicode strings in original language (not u'foo' form)
| 621,321
|
<p>I have a list of tuples of unicode objects:</p>
<pre><code>>>> t = [('äº',), ('ç¬',)]
</code></pre>
<p>Printing this out, I get:</p>
<pre><code>>>> print t
[('\xe4\xba\x80',), ('\xe7\x8a\xac',)]
</code></pre>
<p>which I guess is a list of the utf-8 byte-code representation of those strings?</p>
<p>but what I want to see printed out is, surprise:</p>
<pre><code>[('äº',), ('ç¬',)]
</code></pre>
<p>but I'm having an inordinate amount of trouble getting the bytecode back into a human-readable form. </p>
| 10
|
2009-03-07T04:44:52Z
| 621,332
|
<p>Python source code files are strictly ASCII, so you must use the <code>\u</code> escape sequences unless you specify an encoding. See <a href="http://www.python.org/dev/peps/pep-0263/" rel="nofollow">PEP 0263</a>.</p>
<pre><code>#!/usr/bin/python
# coding=utf-8
t = [u'äº', u'ç¬']
print t
</code></pre>
<p>When you pass an array to <a href="http://docs.python.org/reference/simple%5Fstmts.html#the-print-statement" rel="nofollow"><code>print</code></a>, Python converts the object into a string using Python's <a href="http://docs.python.org/reference/expressions.html#id4" rel="nofollow">rules for string conversions</a>. The output of such conversions are designed for <code>eval()</code>, which is why you see those <code>\u</code> sequences. Here's a hack to get around that based on bobince's solution. The console must accept Unicode or this will throw an exception.</p>
<pre><code>t = [(u'äº',), (u'ç¬',)]
print repr(t).decode('raw_unicode_escape')
</code></pre>
| 2
|
2009-03-07T04:55:28Z
|
[
"python",
"unicode"
] |
How to print tuples of unicode strings in original language (not u'foo' form)
| 621,321
|
<p>I have a list of tuples of unicode objects:</p>
<pre><code>>>> t = [('äº',), ('ç¬',)]
</code></pre>
<p>Printing this out, I get:</p>
<pre><code>>>> print t
[('\xe4\xba\x80',), ('\xe7\x8a\xac',)]
</code></pre>
<p>which I guess is a list of the utf-8 byte-code representation of those strings?</p>
<p>but what I want to see printed out is, surprise:</p>
<pre><code>[('äº',), ('ç¬',)]
</code></pre>
<p>but I'm having an inordinate amount of trouble getting the bytecode back into a human-readable form. </p>
| 10
|
2009-03-07T04:44:52Z
| 621,351
|
<p>So this appears to do what I want:</p>
<pre><code>print '[%s]' % ', '.join([', '.join('(%s,)' % ', '.join(ti) for ti in t)])
>>> t = [('äº',), ('ç¬',)]
>>> print t
[('\xe4\xba\x80',), ('\xe7\x8a\xac',)]
>>> print '[%s]' % ', '.join([', '.join('(%s,)' % ', '.join(ti) for ti in t)])
[(äº,), (ç¬,)]
</code></pre>
<p><em>Surely</em> there's a better way to do it.</p>
<p>(but other two answers thus far don't result in the original string being printed out as desired).</p>
| 0
|
2009-03-07T05:12:18Z
|
[
"python",
"unicode"
] |
How to print tuples of unicode strings in original language (not u'foo' form)
| 621,321
|
<p>I have a list of tuples of unicode objects:</p>
<pre><code>>>> t = [('äº',), ('ç¬',)]
</code></pre>
<p>Printing this out, I get:</p>
<pre><code>>>> print t
[('\xe4\xba\x80',), ('\xe7\x8a\xac',)]
</code></pre>
<p>which I guess is a list of the utf-8 byte-code representation of those strings?</p>
<p>but what I want to see printed out is, surprise:</p>
<pre><code>[('äº',), ('ç¬',)]
</code></pre>
<p>but I'm having an inordinate amount of trouble getting the bytecode back into a human-readable form. </p>
| 10
|
2009-03-07T04:44:52Z
| 621,792
|
<p>First, there's a slight misunderstanding in your post. If you define a list like this:</p>
<pre><code>>>> t = [('äº',), ('ç¬',)]
</code></pre>
<p>...those are not <code>unicode</code>s you define, but <code>str</code>s. If you want to have <code>unicode</code> types, you have to add a <code>u</code> before the character:</p>
<pre><code>>>> t = [(u'äº',), (u'ç¬',)]
</code></pre>
<p>But let's assume you actually want <code>str</code>s, not <code>unicode</code>s. The main problem is, <code>__str__</code> method of a list (or a tuple) is practically equal to its <code>__repr__</code> method (which returns a string that, when evaluated, would create exactly the same object). Because <code>__repr__</code> method should be encoding-independent, strings are represented in the safest mode possible, i.e. each character outside of ASCII range is represented as a hex character (<code>\xe4</code>, for example).</p>
<p>Unfortunately, as far as I know, there's no library method for printing a list that is locale-aware. You could use an almost-general-purpose function like this:</p>
<pre><code>def collection_str(collection):
if isinstance(collection, list):
brackets = '[%s]'
single_add = ''
elif isinstance(collection, tuple):
brackets = '(%s)'
single_add =','
else:
return str(collection)
items = ', '.join([collection_str(x) for x in collection])
if len(collection) == 1:
items += single_add
return brackets % items
>>> print collection_str(t)
[('äº',), ('ç¬',)]
</code></pre>
<p>Note that this won't work for all possible collections (sets and dictionaries, for example), but it's easy to extend it to handle those.</p>
| 3
|
2009-03-07T12:45:51Z
|
[
"python",
"unicode"
] |
How to print tuples of unicode strings in original language (not u'foo' form)
| 621,321
|
<p>I have a list of tuples of unicode objects:</p>
<pre><code>>>> t = [('äº',), ('ç¬',)]
</code></pre>
<p>Printing this out, I get:</p>
<pre><code>>>> print t
[('\xe4\xba\x80',), ('\xe7\x8a\xac',)]
</code></pre>
<p>which I guess is a list of the utf-8 byte-code representation of those strings?</p>
<p>but what I want to see printed out is, surprise:</p>
<pre><code>[('äº',), ('ç¬',)]
</code></pre>
<p>but I'm having an inordinate amount of trouble getting the bytecode back into a human-readable form. </p>
| 10
|
2009-03-07T04:44:52Z
| 621,798
|
<blockquote>
<p>but what I want to see printed out is, surprise:</p>
<p>[('äº',), ('ç¬',)]</p>
</blockquote>
<p>What do you want to see it printed out on? Because if it's the console, it's not at all guaranteed your console can display those characters. This is why Python's ârepr()â representation of objects goes for the safe option of \-escapes, which you will always be able to see on-screen and type in easily.</p>
<p>As a prerequisite you should be using Unicode strings (u''). And, as mentioned by Matthew, if you want to be able to write u'äº' directly in source you need to make sure Python can read the file's encoding. For occasional use of non-ASCII characters it is best to stick with the escaped version u'\u4e80', but when you have a lot of East Asian text you want to be able to read, â# coding=utf-8â is definitely the way to go.</p>
<blockquote>
<p>print '[%s]' % ', '.join([', '.join('(%s,)' % ', '.join(ti) for ti in t)])</p>
</blockquote>
<p>That would print the characters unwrapped by quotes. Really you'd want:</p>
<pre><code>def reprunicode(u):
return repr(u).decode('raw_unicode_escape')
print u'[%s]' % u', '.join([u'(%s,)' % reprunicode(ti[0]) for ti in t])
</code></pre>
<p>This would work, but if the console didn't support Unicode (and this is especially troublesome on Windows), you'll get a big old UnicodeError.</p>
<p>In any case, this rarely matters because the repr() of an object, which is what you're seeing here, doesn't usually make it to the public user interface of an application; it's really for the coder only.</p>
<p>However, you'll be pleased to know that Python 3.0 behaves exactly as you want:</p>
<ul>
<li>plain '' strings without the âuâ prefix are now Unicode strings</li>
<li>repr() shows most Unicode characters verbatim</li>
<li>Unicode in the Windows console is better supported (you can still get UnicodeError on Unix if your environment isn't UTF-8)</li>
</ul>
<p>Python 3.0 is a little bit new and not so well-supported by libraries, but it might well suit your needs better.</p>
| 6
|
2009-03-07T12:49:29Z
|
[
"python",
"unicode"
] |
How to print tuples of unicode strings in original language (not u'foo' form)
| 621,321
|
<p>I have a list of tuples of unicode objects:</p>
<pre><code>>>> t = [('äº',), ('ç¬',)]
</code></pre>
<p>Printing this out, I get:</p>
<pre><code>>>> print t
[('\xe4\xba\x80',), ('\xe7\x8a\xac',)]
</code></pre>
<p>which I guess is a list of the utf-8 byte-code representation of those strings?</p>
<p>but what I want to see printed out is, surprise:</p>
<pre><code>[('äº',), ('ç¬',)]
</code></pre>
<p>but I'm having an inordinate amount of trouble getting the bytecode back into a human-readable form. </p>
| 10
|
2009-03-07T04:44:52Z
| 23,022,825
|
<p>It seems people are missing what people want here. When I print unicode from a tuple, I just want to get rid of the 'u' '[' '(' and quotes. What we want is a function like below.
After scouring the Net it seems to be the cleanest way to get atomic displayable data.
If the data is not in a tuple or list, I don't think this problem exists.</p>
<pre><code>def Plain(self, U_String) :
P_String = str(U_String)
m=re.search("^\(\u?\'(.*)\'\,\)$", P_String)
if (m) : #Typical unicode
P_String = m.group(1).decode("utf8")
return P_String
</code></pre>
| 0
|
2014-04-11T21:23:08Z
|
[
"python",
"unicode"
] |
How to slice a list from an element n to the end in python?
| 621,354
|
<p>I'm having some trouble figuring out how to slice python lists, it is illustrated as follows:</p>
<pre><code>>>> test = range(10)
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test[3:-1]
[3, 4, 5, 6, 7, 8]
>>> test[3:0]
[]
>>> test[3:1]
[]
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>To my understanding, python slice means lst[start:end], and including start, excluding end. So how would i go about finding the "rest" of a list starting from an element n?</p>
<p>Thanks a lot for all your help!</p>
| 14
|
2009-03-07T05:17:34Z
| 621,357
|
<p>You can leave one end of the slice open by not specifying the value.</p>
<pre><code>test[3:] = [3, 4, 5, 6, 7, 8, 9]
test[:3] = [0, 1, 2]
</code></pre>
| 33
|
2009-03-07T05:19:31Z
|
[
"python"
] |
How to slice a list from an element n to the end in python?
| 621,354
|
<p>I'm having some trouble figuring out how to slice python lists, it is illustrated as follows:</p>
<pre><code>>>> test = range(10)
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test[3:-1]
[3, 4, 5, 6, 7, 8]
>>> test[3:0]
[]
>>> test[3:1]
[]
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>To my understanding, python slice means lst[start:end], and including start, excluding end. So how would i go about finding the "rest" of a list starting from an element n?</p>
<p>Thanks a lot for all your help!</p>
| 14
|
2009-03-07T05:17:34Z
| 621,358
|
<p>Simply omit the end.</p>
<pre><code>test[n:]
</code></pre>
| 6
|
2009-03-07T05:19:40Z
|
[
"python"
] |
How to slice a list from an element n to the end in python?
| 621,354
|
<p>I'm having some trouble figuring out how to slice python lists, it is illustrated as follows:</p>
<pre><code>>>> test = range(10)
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test[3:-1]
[3, 4, 5, 6, 7, 8]
>>> test[3:0]
[]
>>> test[3:1]
[]
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>To my understanding, python slice means lst[start:end], and including start, excluding end. So how would i go about finding the "rest" of a list starting from an element n?</p>
<p>Thanks a lot for all your help!</p>
| 14
|
2009-03-07T05:17:34Z
| 621,521
|
<p>If you're using a variable as the range endpoint, you can use <code>None</code>.</p>
<pre><code> start = 4
end = None
test[start:end]
</code></pre>
| 19
|
2009-03-07T08:15:31Z
|
[
"python"
] |
How to slice a list from an element n to the end in python?
| 621,354
|
<p>I'm having some trouble figuring out how to slice python lists, it is illustrated as follows:</p>
<pre><code>>>> test = range(10)
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test[3:-1]
[3, 4, 5, 6, 7, 8]
>>> test[3:0]
[]
>>> test[3:1]
[]
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>To my understanding, python slice means lst[start:end], and including start, excluding end. So how would i go about finding the "rest" of a list starting from an element n?</p>
<p>Thanks a lot for all your help!</p>
| 14
|
2009-03-07T05:17:34Z
| 35,066,475
|
<p>Leaving out the end still works when you want to skip some:</p>
<pre><code>range(10)[3::2] = [4, 6, 8]
</code></pre>
| 1
|
2016-01-28T16:14:17Z
|
[
"python"
] |
What does re.compile(r'[[]]') match?
| 621,560
|
<p>With Python's re module, why do the following act differently:</p>
<pre><code>>>> r = re.compile(r'[][]')
>>> r.findall(r'[]')
['[', ']']
>>> r = re.compile(r'[[]]')
>>> r.findall(r'[]')
['[]']
>>> r.findall(r'][')
[]
</code></pre>
| 4
|
2009-03-07T08:59:27Z
| 621,568
|
<p>The regular expression "[[]]" matches the substring "[]". The first [ in the expression begins a character class, and the first ] ends it. There is only one character ([) in the class, and then it has to be followed by the second ]. So the expression is "any of the characters in "[", followed by a "]".</p>
| 16
|
2009-03-07T09:11:20Z
|
[
"python",
"regex"
] |
What does re.compile(r'[[]]') match?
| 621,560
|
<p>With Python's re module, why do the following act differently:</p>
<pre><code>>>> r = re.compile(r'[][]')
>>> r.findall(r'[]')
['[', ']']
>>> r = re.compile(r'[[]]')
>>> r.findall(r'[]')
['[]']
>>> r.findall(r'][')
[]
</code></pre>
| 4
|
2009-03-07T08:59:27Z
| 621,602
|
<p>and r'[][]' forms a character class {'[',']'}, and match either '[' or ']'.</p>
| 0
|
2009-03-07T09:47:53Z
|
[
"python",
"regex"
] |
What does re.compile(r'[[]]') match?
| 621,560
|
<p>With Python's re module, why do the following act differently:</p>
<pre><code>>>> r = re.compile(r'[][]')
>>> r.findall(r'[]')
['[', ']']
>>> r = re.compile(r'[[]]')
>>> r.findall(r'[]')
['[]']
>>> r.findall(r'][')
[]
</code></pre>
| 4
|
2009-03-07T08:59:27Z
| 621,608
|
<p>Character classes begin with a <strong><code>[</code></strong> and end with the first <strong><code>]</code></strong>.</p>
<p>So the expression <code>[][]</code> is a character class with the characters <code>]</code> and <code>[</code> as character classes must not be empty: <strong><code>[</code></strong><code>][</code><strong><code>]</code></strong><br />
And the expression <code>[[]]</code> is a character class with just <code>[</code> and the single character <code>]</code> after that: <strong><code>[</code></strong><code>[</code><strong><code>]</code></strong><code>]</code></p>
| 4
|
2009-03-07T09:56:40Z
|
[
"python",
"regex"
] |
Python and random keys of 21 char max
| 621,649
|
<p>I am using an api which takes a name of 21 char max to represent an internal session which has a lifetime of around "two days". I would like the name not to be meaningfull using some kind of hasing ? md5 generates 40 chars, is there something else i could use ?</p>
<p>For now i use 'userid[:10]' + creation time: ddhhmmss + random 3 chars.</p>
<p>Thanks,</p>
| 7
|
2009-03-07T10:36:54Z
| 621,653
|
<p>Why not take first 21 chars from md5 or SHA1 hash?</p>
| 2
|
2009-03-07T10:38:26Z
|
[
"python",
"encryption",
"key"
] |
Python and random keys of 21 char max
| 621,649
|
<p>I am using an api which takes a name of 21 char max to represent an internal session which has a lifetime of around "two days". I would like the name not to be meaningfull using some kind of hasing ? md5 generates 40 chars, is there something else i could use ?</p>
<p>For now i use 'userid[:10]' + creation time: ddhhmmss + random 3 chars.</p>
<p>Thanks,</p>
| 7
|
2009-03-07T10:36:54Z
| 621,658
|
<p>The hexadecimal representation of MD5 has very poor randomness: you only get 4 bits of entropy per character.</p>
<p>Use random characters, something like:</p>
<pre><code>import random
import string
"".join([random.choice(string.ascii_letters + string.digits + ".-")
for i in xrange(21)])
</code></pre>
<p>In the choice put all the acceptable characters.</p>
<p>While using a real hash function such as SHA1 will also get you nice results <em>if used correctly</em>, the added complexity and CPU consumption seems not justified for your needs. You only want a random string.</p>
| 4
|
2009-03-07T10:45:36Z
|
[
"python",
"encryption",
"key"
] |
Python and random keys of 21 char max
| 621,649
|
<p>I am using an api which takes a name of 21 char max to represent an internal session which has a lifetime of around "two days". I would like the name not to be meaningfull using some kind of hasing ? md5 generates 40 chars, is there something else i could use ?</p>
<p>For now i use 'userid[:10]' + creation time: ddhhmmss + random 3 chars.</p>
<p>Thanks,</p>
| 7
|
2009-03-07T10:36:54Z
| 621,668
|
<p>Characters, or bytes? If it takes arbitrary strings, you can just use the bytes and not worry about expanding to readable characters (for which base64 would be better than hex anyway).</p>
<p>MD5 generates 16 chars if you don't use the hexadecimal expansion of it. SHA1 generates 20 under the same condition.</p>
<pre><code>>>> import hashlib
>>> len(hashlib.md5('foobar').digest())
16
>>> len(hashlib.sha1('foobar').digest())
20
</code></pre>
<p>Few extra bytes are needed after that.</p>
| 0
|
2009-03-07T10:54:19Z
|
[
"python",
"encryption",
"key"
] |
Python and random keys of 21 char max
| 621,649
|
<p>I am using an api which takes a name of 21 char max to represent an internal session which has a lifetime of around "two days". I would like the name not to be meaningfull using some kind of hasing ? md5 generates 40 chars, is there something else i could use ?</p>
<p>For now i use 'userid[:10]' + creation time: ddhhmmss + random 3 chars.</p>
<p>Thanks,</p>
| 7
|
2009-03-07T10:36:54Z
| 621,770
|
<p>If I read your question correctly, you want to generate some arbitrary identifier token which must be 21 characters max. Does it need to be highly resistant to guessing? The example you gave isn't "crytographically strong" in that it can be guessed by searching well less than 1/2 of the entire possible keyspace. </p>
<p>You don't say if the characters can be all 256 ASCII characters, or if it needs to be limited to, say, printable ASCII (33-127, inclusive), or some smaller range.</p>
<p>There is a Python module designed for <a href="http://docs.python.org/library/uuid.html">UUID</a>s (Universals Unique IDentifiers). You likely want uuid4 which generates a random UUID, and uses OS support if available (on Linux, Mac, FreeBSD, and likely others).</p>
<pre><code>>>> import uuid
>>> u = uuid.uuid4()
>>> u
UUID('d94303e7-1be4-49ef-92f2-472bc4b4286d')
>>> u.bytes
'\xd9C\x03\xe7\x1b\xe4I\xef\x92\xf2G+\xc4\xb4(m'
>>> len(u.bytes)
16
>>>
</code></pre>
<p>16 random bytes is very unguessable, and there's no need to use the full 21 bytes your API allows, if all you want is to have an unguessable opaque identifier.</p>
<p>If you can't use raw bytes like that, which is probably a bad idea because it's harder to use in logs and other debug messages and harder to compare by eye, then convert the bytes into something a bit more readable, like using base-64 encoding, with the result chopped down to 21 (or whatever) bytes:</p>
<pre><code>>>> u.bytes.encode("base64")
'2UMD5xvkSe+S8kcrxLQobQ==\n'
>>> len(u.bytes.encode("base64"))
25
>>> u.bytes.encode("base64")[:21]
'2UMD5xvkSe+S8kcrxLQob'
>>>
</code></pre>
<p>This gives you an extremely high quality random string of length 21.</p>
<p>You might not like the '+' or '/' which can be in a base-64 string, since without proper escaping that might interfere with URLs. Since you already think to use "random 3 chars", I don't think this is a worry of yours. If it is, you could replace those characters with something else ('-' and '.' might work), or remove them if present.</p>
<p>As others have pointed out, you could use .encode("hex") and get the hex equivalent, but that's only 4 bits of randomness/character * 21 characters max gives you 84 bits of randomness instead of twice that. Every bit doubles your keyspace, making the theoretical search space much, much smaller. By a factor of 2E24 smaller.</p>
<p>Your keyspace is still 2E24 in size, even with hex encoding, so I think it's more a theoretical concern. I wouldn't worry about people doing brute force attacks against your system.</p>
<p><strong>Edit</strong>:</p>
<p>P.S.: The uuid.uuid4 function uses libuuid if available. That gets its entropy from os.urandom (if available) otherwise from the current time and the local ethernet MAC address. If libuuid is not available then the uuid.uuid4 function gets the bytes directly from os.urandom (if available) otherwise it uses the random module. The random module uses a default seed based on os.urandom (if available) otherwise a value based on the current time. Probing takes place for every function call, so if you don't have os.urandom then the overhead is a bit bigger than you might expect.</p>
<p>Take home message? If you know you have os.urandom then you could do </p>
<pre><code>os.urandom(16).encode("base64")[:21]
</code></pre>
<p>but if you don't want to worry about its availability then use the uuid module.</p>
| 23
|
2009-03-07T12:26:47Z
|
[
"python",
"encryption",
"key"
] |
Python and random keys of 21 char max
| 621,649
|
<p>I am using an api which takes a name of 21 char max to represent an internal session which has a lifetime of around "two days". I would like the name not to be meaningfull using some kind of hasing ? md5 generates 40 chars, is there something else i could use ?</p>
<p>For now i use 'userid[:10]' + creation time: ddhhmmss + random 3 chars.</p>
<p>Thanks,</p>
| 7
|
2009-03-07T10:36:54Z
| 1,567,663
|
<p>The base64 module can do URL-safe encoding. So, if needed, instead of </p>
<pre><code>u.bytes.encode("base64")
</code></pre>
<p>you could do</p>
<pre><code>import base64
token = base64.urlsafe_b64encode(u.bytes)
</code></pre>
<p>and, conveniently, to convert back</p>
<pre><code>u = uuid.UUID(bytes=base64.urlsafe_b64decode(token))
</code></pre>
| 2
|
2009-10-14T17:03:44Z
|
[
"python",
"encryption",
"key"
] |
Choosing and deploying a comet server
| 621,802
|
<p>I want to push data to the browser over HTTP without killing my django/python application.</p>
<p>I decided to use a comet server, to proxy requests between my application and the client (though I still haven't really figured it out properly).</p>
<p>I've looked into the following engines:
orbited
cometd
ejabberd
jetty</p>
<p>Has anyone had any experience working with these servers and deploying them? Any insight and links regarding the topics would be great. Thank you.</p>
| 13
|
2009-03-07T12:51:53Z
| 622,013
|
<p>I need to do something very similar. I found this, but haven't had the time to look at it properly yet:</p>
<blockquote>
<p>django_evserver is simple http server
for Django applications. It's based on
libevent library. The main advantage
of django_evserver is that it provides
methods of preempting django views.
You can render a site in several
chunks, each of them can be handled by
different django view.</p>
<p>Using this idea it's possible to use
django_evserver as comet server for
django applications.</p>
</blockquote>
<p><a href="http://code.google.com/p/django-evserver/" rel="nofollow">http://code.google.com/p/django-evserver/</a></p>
| 2
|
2009-03-07T15:44:34Z
|
[
"python",
"django",
"comet",
"daemon"
] |
Choosing and deploying a comet server
| 621,802
|
<p>I want to push data to the browser over HTTP without killing my django/python application.</p>
<p>I decided to use a comet server, to proxy requests between my application and the client (though I still haven't really figured it out properly).</p>
<p>I've looked into the following engines:
orbited
cometd
ejabberd
jetty</p>
<p>Has anyone had any experience working with these servers and deploying them? Any insight and links regarding the topics would be great. Thank you.</p>
| 13
|
2009-03-07T12:51:53Z
| 622,509
|
<p>I would recommend looking into Twisted, their twisted.web server, and the comet work done on top of it at Divmod. They can handle far more concurrent connections than traditional thread or process based servers, which is exactly what you need for something like this. And, yes, I've architected systems using Twisted for COMET stuff, while using other things for the more front-facing web applications beside it. It works out well with each part doing what it does best.</p>
| 5
|
2009-03-07T21:06:49Z
|
[
"python",
"django",
"comet",
"daemon"
] |
Choosing and deploying a comet server
| 621,802
|
<p>I want to push data to the browser over HTTP without killing my django/python application.</p>
<p>I decided to use a comet server, to proxy requests between my application and the client (though I still haven't really figured it out properly).</p>
<p>I've looked into the following engines:
orbited
cometd
ejabberd
jetty</p>
<p>Has anyone had any experience working with these servers and deploying them? Any insight and links regarding the topics would be great. Thank you.</p>
| 13
|
2009-03-07T12:51:53Z
| 1,159,813
|
<p>If you can run Java I would recommend <a href="http://www.stream-hub.com/" rel="nofollow">StreamHub Comet Server</a>. </p>
<p>Firstly, regarding your need not to 'kill' your existing application, the JavaScript include has a really low footprint at less than 10K. I use it for pushing user updates and chat on the social networking site I'm building. I tested with a 1000+ hits a day and there was no noticeable effect on the CPU.</p>
<p>Secondly, on deploying, I followed some of the examples and was up and running really quickly compared to banging my head against a wall with CometD. There is a good <a href="http://streamhub.blogspot.com/2009/07/getting-started-with-streamhub-and.html" rel="nofollow">Comet Hello World</a> getting started guide and a <a href="http://groups.google.co.uk/group/streamhub-comet-server-community" rel="nofollow">Google Group</a> if you get stuck on anything.</p>
| 2
|
2009-07-21T15:09:20Z
|
[
"python",
"django",
"comet",
"daemon"
] |
Choosing and deploying a comet server
| 621,802
|
<p>I want to push data to the browser over HTTP without killing my django/python application.</p>
<p>I decided to use a comet server, to proxy requests between my application and the client (though I still haven't really figured it out properly).</p>
<p>I've looked into the following engines:
orbited
cometd
ejabberd
jetty</p>
<p>Has anyone had any experience working with these servers and deploying them? Any insight and links regarding the topics would be great. Thank you.</p>
| 13
|
2009-03-07T12:51:53Z
| 1,167,542
|
<p>One option is Netty, client-server socket framework based on Java NIO from JBoss. For a comparison and discussion <a href="http://amix.dk/blog/viewEntry/19456" rel="nofollow">see here</a>. It reportedly handles 100000 simultaneous open connections on a quad-core server. </p>
| 2
|
2009-07-22T19:14:58Z
|
[
"python",
"django",
"comet",
"daemon"
] |
Choosing and deploying a comet server
| 621,802
|
<p>I want to push data to the browser over HTTP without killing my django/python application.</p>
<p>I decided to use a comet server, to proxy requests between my application and the client (though I still haven't really figured it out properly).</p>
<p>I've looked into the following engines:
orbited
cometd
ejabberd
jetty</p>
<p>Has anyone had any experience working with these servers and deploying them? Any insight and links regarding the topics would be great. Thank you.</p>
| 13
|
2009-03-07T12:51:53Z
| 1,689,258
|
<p>If you're running IIS, you can check out WebSync (http://www.frozenmountain.com/websync), a standards-compliant (bayeux) comet server and client for .NET/IIS. If you don't want the additional load, the On-Demand version is a SaaS option that offloads the heavy lifting.</p>
| 2
|
2009-11-06T17:59:01Z
|
[
"python",
"django",
"comet",
"daemon"
] |
Choosing and deploying a comet server
| 621,802
|
<p>I want to push data to the browser over HTTP without killing my django/python application.</p>
<p>I decided to use a comet server, to proxy requests between my application and the client (though I still haven't really figured it out properly).</p>
<p>I've looked into the following engines:
orbited
cometd
ejabberd
jetty</p>
<p>Has anyone had any experience working with these servers and deploying them? Any insight and links regarding the topics would be great. Thank you.</p>
| 13
|
2009-03-07T12:51:53Z
| 1,818,372
|
<p>If you're looking to combine Django with a Comet server (Orbited), check this project I have going to integrate Django and Orbited in as "clean" and "real-world" as possible here: <a href="http://github.com/clemesha/hotdot" rel="nofollow">http://github.com/clemesha/hotdot</a></p>
<p>The project addresses "real-world" problems like security and logging/filtering/modifying the in-transit Comet messages, etc - but is still a work in progress. </p>
| 2
|
2009-11-30T07:45:54Z
|
[
"python",
"django",
"comet",
"daemon"
] |
.cgi problem with web server
| 621,874
|
<p><a href="http://www.djangobook.com/en/2.0/chapter01/" rel="nofollow">The code</a></p>
<pre><code>#!/usr/bin/env python
import MySQLdb
print "Content-Type: text/html"
print
print "<html><head><title>Books</title></head>"
print "<body>" print "<h1>Books</h1>"
print "<ul>"
connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db') cursor = connection.cursor() cursor.execute(âSELECT name FROM books ORDER BY pub_date DESC LIMIT 10â)
for row in cursor.fetchall():
print "<li>%s</li>" % row[0]
print "</ul>"
print "</body></html>"
connection.close()
</code></pre>
<p>I saved it as test.cgi to my web server. I run it by www.mysite.com/test.cgi unsuccessfully</p>
<pre><code>Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
</code></pre>
<p>How can you solve the problem?</p>
<p><strong>[edit]</strong> after the first answer</p>
<ol>
<li>test.cgi is executable (I run $ chmod +x test.cgi)</li>
<li>I use Apache. </li>
<li>I have this in .bashrc export PATH=${PATH}:~/bin </li>
<li>Python module MySQLdb is installed.</li>
<li>The code does not have smart quotes.</li>
</ol>
<p><strong>[edit]</strong> after the second answer</p>
<blockquote>
<p>you're getting that error because you
haven't installed the MySQLdb module
that Python needs to talk to a MySQL
database</p>
</blockquote>
<p>I installed MySQLdb to my system. The module works, since I can import them.
However, I still get the same error whet I go to the www.[mysite].com/test.cgi.</p>
<p><strong>[edit]</strong></p>
<p>I am not sure about the questions</p>
<blockquote>
<p>Are the connect() parameters correct? Is MySQL running on localhost
at the default port?</p>
</blockquote>
<p>I run MySQL on my server. Is the question about the connect() parameters relevant here?</p>
<blockquote>
<p>Is the SELECT statement correct?</p>
</blockquote>
<p>You mean whether I have my SQL statements such as SELECT statement correct?
I have not used any SQL queries yet.
Do I need them here?</p>
| 1
|
2009-03-07T14:01:33Z
| 621,885
|
<p>I've tidied up the code a bit by inserting linebreaks where necessary and replacing smart quotes with <code>"</code> and <code>'</code>. Do you have any more luck with the following? Can you run it from a terminal just by typing <code>python test.cgi</code>?</p>
<pre><code>#!/usr/bin/env python
import MySQLdb
print "Content-Type: text/html"
print
print "<html><head><title>Books</title></head>"
print "<body>"
print "<h1>Books</h1>"
print "<ul>"
connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db')
cursor = connection.cursor()
cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10")
for row in cursor.fetchall():
print "<li>%s</li>" % row[0]
print "</ul>"
print "</body></html>"
connection.close()
</code></pre>
| 2
|
2009-03-07T14:12:58Z
|
[
"python",
"cgi"
] |
.cgi problem with web server
| 621,874
|
<p><a href="http://www.djangobook.com/en/2.0/chapter01/" rel="nofollow">The code</a></p>
<pre><code>#!/usr/bin/env python
import MySQLdb
print "Content-Type: text/html"
print
print "<html><head><title>Books</title></head>"
print "<body>" print "<h1>Books</h1>"
print "<ul>"
connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db') cursor = connection.cursor() cursor.execute(âSELECT name FROM books ORDER BY pub_date DESC LIMIT 10â)
for row in cursor.fetchall():
print "<li>%s</li>" % row[0]
print "</ul>"
print "</body></html>"
connection.close()
</code></pre>
<p>I saved it as test.cgi to my web server. I run it by www.mysite.com/test.cgi unsuccessfully</p>
<pre><code>Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
</code></pre>
<p>How can you solve the problem?</p>
<p><strong>[edit]</strong> after the first answer</p>
<ol>
<li>test.cgi is executable (I run $ chmod +x test.cgi)</li>
<li>I use Apache. </li>
<li>I have this in .bashrc export PATH=${PATH}:~/bin </li>
<li>Python module MySQLdb is installed.</li>
<li>The code does not have smart quotes.</li>
</ol>
<p><strong>[edit]</strong> after the second answer</p>
<blockquote>
<p>you're getting that error because you
haven't installed the MySQLdb module
that Python needs to talk to a MySQL
database</p>
</blockquote>
<p>I installed MySQLdb to my system. The module works, since I can import them.
However, I still get the same error whet I go to the www.[mysite].com/test.cgi.</p>
<p><strong>[edit]</strong></p>
<p>I am not sure about the questions</p>
<blockquote>
<p>Are the connect() parameters correct? Is MySQL running on localhost
at the default port?</p>
</blockquote>
<p>I run MySQL on my server. Is the question about the connect() parameters relevant here?</p>
<blockquote>
<p>Is the SELECT statement correct?</p>
</blockquote>
<p>You mean whether I have my SQL statements such as SELECT statement correct?
I have not used any SQL queries yet.
Do I need them here?</p>
| 1
|
2009-03-07T14:01:33Z
| 621,928
|
<p>Any number of issues can cause the error you are seeing:</p>
<ol>
<li>Is <code>test.cgi</code> executable (chmod 755) on the server?</li>
<li>Is the directory in which you placed <code>test.cgi</code> designated as a <a href="http://httpd.apache.org/docs/2.2/mod/mod%5Falias.html#scriptalias" rel="nofollow">ScriptAlias</a> location or have the <a href="http://httpd.apache.org/docs/2.2/howto/cgi.html" rel="nofollow">ExecCGI</a> option enabled (or equivalent if you're not using Apache)?</li>
<li>Is <code>python</code> in the system <code>PATH</code> or in the <code>PATH</code> in the Web server's startup environment?</li>
<li>Is the <a href="http://mysql-python.sourceforge.net/" rel="nofollow">MySQLdb</a> Python library installed?</li>
<li>Are the <code>connect()</code> parameters correct? Is MySQL running on localhost at the default port?</li>
<li>Is the <code>SELECT</code> statement correct?</li>
</ol>
<p>If you're sure that <code>python</code> is found (test using the simplest possible script or by logging into the Web server if you can and typing <code>which python</code>) then you can get much better debug output by adding the following to the top of your script just below the shebang:</p>
<pre><code>import cgitb
cgitb.enable()
</code></pre>
<p>More details: <a href="http://docs.python.org/library/cgitb.html" rel="nofollow">http://docs.python.org/library/cgitb.html</a></p>
<p>Additionally, if you have shell access to the Web server, try running python and just typing:</p>
<pre><code>>>> import MySQLdb
</code></pre>
<p>If the command returns with no error, you have your answer for #4 above. If an error is printed, you will need to get MySQLdb installed into the Web server's Python installation.</p>
<p><strong>EDIT:</strong> Looking more closely at the top of your question, I see that the code was scraped from an illustrative example at the very beginning of the Django Book. As such, I might expand #5 above to include the caveat that, of course, the requisite database, tables, user, and permissions need to be set up on the MySQL installation available to the Web server.</p>
| 2
|
2009-03-07T14:49:48Z
|
[
"python",
"cgi"
] |
.cgi problem with web server
| 621,874
|
<p><a href="http://www.djangobook.com/en/2.0/chapter01/" rel="nofollow">The code</a></p>
<pre><code>#!/usr/bin/env python
import MySQLdb
print "Content-Type: text/html"
print
print "<html><head><title>Books</title></head>"
print "<body>" print "<h1>Books</h1>"
print "<ul>"
connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db') cursor = connection.cursor() cursor.execute(âSELECT name FROM books ORDER BY pub_date DESC LIMIT 10â)
for row in cursor.fetchall():
print "<li>%s</li>" % row[0]
print "</ul>"
print "</body></html>"
connection.close()
</code></pre>
<p>I saved it as test.cgi to my web server. I run it by www.mysite.com/test.cgi unsuccessfully</p>
<pre><code>Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
</code></pre>
<p>How can you solve the problem?</p>
<p><strong>[edit]</strong> after the first answer</p>
<ol>
<li>test.cgi is executable (I run $ chmod +x test.cgi)</li>
<li>I use Apache. </li>
<li>I have this in .bashrc export PATH=${PATH}:~/bin </li>
<li>Python module MySQLdb is installed.</li>
<li>The code does not have smart quotes.</li>
</ol>
<p><strong>[edit]</strong> after the second answer</p>
<blockquote>
<p>you're getting that error because you
haven't installed the MySQLdb module
that Python needs to talk to a MySQL
database</p>
</blockquote>
<p>I installed MySQLdb to my system. The module works, since I can import them.
However, I still get the same error whet I go to the www.[mysite].com/test.cgi.</p>
<p><strong>[edit]</strong></p>
<p>I am not sure about the questions</p>
<blockquote>
<p>Are the connect() parameters correct? Is MySQL running on localhost
at the default port?</p>
</blockquote>
<p>I run MySQL on my server. Is the question about the connect() parameters relevant here?</p>
<blockquote>
<p>Is the SELECT statement correct?</p>
</blockquote>
<p>You mean whether I have my SQL statements such as SELECT statement correct?
I have not used any SQL queries yet.
Do I need them here?</p>
| 1
|
2009-03-07T14:01:33Z
| 622,085
|
<p>The error in <a href="http://dpaste.com/8866/" rel="nofollow">http://dpaste.com/8866/</a> is occurring because you are using "curly quotes" instead of standard ASCII quotation marks.</p>
<p>You'll want to replace the â and â with ". Just use find and replace in your text editor.</p>
| 1
|
2009-03-07T16:30:45Z
|
[
"python",
"cgi"
] |
.cgi problem with web server
| 621,874
|
<p><a href="http://www.djangobook.com/en/2.0/chapter01/" rel="nofollow">The code</a></p>
<pre><code>#!/usr/bin/env python
import MySQLdb
print "Content-Type: text/html"
print
print "<html><head><title>Books</title></head>"
print "<body>" print "<h1>Books</h1>"
print "<ul>"
connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db') cursor = connection.cursor() cursor.execute(âSELECT name FROM books ORDER BY pub_date DESC LIMIT 10â)
for row in cursor.fetchall():
print "<li>%s</li>" % row[0]
print "</ul>"
print "</body></html>"
connection.close()
</code></pre>
<p>I saved it as test.cgi to my web server. I run it by www.mysite.com/test.cgi unsuccessfully</p>
<pre><code>Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
</code></pre>
<p>How can you solve the problem?</p>
<p><strong>[edit]</strong> after the first answer</p>
<ol>
<li>test.cgi is executable (I run $ chmod +x test.cgi)</li>
<li>I use Apache. </li>
<li>I have this in .bashrc export PATH=${PATH}:~/bin </li>
<li>Python module MySQLdb is installed.</li>
<li>The code does not have smart quotes.</li>
</ol>
<p><strong>[edit]</strong> after the second answer</p>
<blockquote>
<p>you're getting that error because you
haven't installed the MySQLdb module
that Python needs to talk to a MySQL
database</p>
</blockquote>
<p>I installed MySQLdb to my system. The module works, since I can import them.
However, I still get the same error whet I go to the www.[mysite].com/test.cgi.</p>
<p><strong>[edit]</strong></p>
<p>I am not sure about the questions</p>
<blockquote>
<p>Are the connect() parameters correct? Is MySQL running on localhost
at the default port?</p>
</blockquote>
<p>I run MySQL on my server. Is the question about the connect() parameters relevant here?</p>
<blockquote>
<p>Is the SELECT statement correct?</p>
</blockquote>
<p>You mean whether I have my SQL statements such as SELECT statement correct?
I have not used any SQL queries yet.
Do I need them here?</p>
| 1
|
2009-03-07T14:01:33Z
| 622,295
|
<p>Make sure you're saving the file with correct line endings. i.e. LF only on unix, or CR/LF for Windows. I just recently had the exact same problem...</p>
| 0
|
2009-03-07T18:50:47Z
|
[
"python",
"cgi"
] |
Unable to import python-mysqldb
| 621,968
|
<p>I installed python-mysqldb using </p>
<pre><code>sudo apt-get install python-mysqldb
</code></pre>
<p>I have tried to use it unsuccessfully. The following commands do not work in Python prompt:</p>
<pre><code>import python-mysqldb
</code></pre>
<p>Or</p>
<pre><code>import mysqldb
</code></pre>
<p>How can I solve this problem?</p>
| 2
|
2009-03-07T15:12:02Z
| 621,972
|
<p>The package name is "MySQLdb". Case counts.</p>
| 10
|
2009-03-07T15:13:48Z
|
[
"python",
"import",
"mysql"
] |
Python Reflection and Type Conversion
| 622,161
|
<p>In Python, functions like str(), int(), float(), etc. are generally used to perform type conversions. However, these require you to know at development time what type you want to convert to. A subproblem of some Python code I'm trying to write is as follows:</p>
<p>Given two variables, <code>foo</code> and <code>bar</code>, find the type of <code>foo</code>. (It is not known at development time, as this is generic code.) Then, attempt to convert <code>bar</code> to whatever type <code>foo</code> is. If this cannot be done, throw an exception.</p>
<p>For example, let's say you call the function that does this <code>conv</code>. Its signature would look like</p>
<pre><code>def conv(foo, bar) :
# Do stuff.
</code></pre>
<p>It would be called something like:</p>
<pre><code>result = conv(3.14, "2.718") # result is now 2.718, as a float.
</code></pre>
| 7
|
2009-03-07T17:15:41Z
| 622,173
|
<p>Use <code>foo.__class__</code> to get the type of <code>foo</code>. Then call it to convert bar to the type of foo:</p>
<pre><code>def conv(foo, bar) :
return foo.__class__(bar)
</code></pre>
<p>Of course, this only works if the type of <code>foo</code> has a constructor that knows how to convert bar.</p>
| 11
|
2009-03-07T17:21:42Z
|
[
"python",
"reflection",
"type-conversion",
"introspection",
"python-datamodel"
] |
Python Reflection and Type Conversion
| 622,161
|
<p>In Python, functions like str(), int(), float(), etc. are generally used to perform type conversions. However, these require you to know at development time what type you want to convert to. A subproblem of some Python code I'm trying to write is as follows:</p>
<p>Given two variables, <code>foo</code> and <code>bar</code>, find the type of <code>foo</code>. (It is not known at development time, as this is generic code.) Then, attempt to convert <code>bar</code> to whatever type <code>foo</code> is. If this cannot be done, throw an exception.</p>
<p>For example, let's say you call the function that does this <code>conv</code>. Its signature would look like</p>
<pre><code>def conv(foo, bar) :
# Do stuff.
</code></pre>
<p>It would be called something like:</p>
<pre><code>result = conv(3.14, "2.718") # result is now 2.718, as a float.
</code></pre>
| 7
|
2009-03-07T17:15:41Z
| 622,217
|
<p>that would be best:</p>
<pre><code>type(foo)(bar)
</code></pre>
| 16
|
2009-03-07T17:57:32Z
|
[
"python",
"reflection",
"type-conversion",
"introspection",
"python-datamodel"
] |
Python Reflection and Type Conversion
| 622,161
|
<p>In Python, functions like str(), int(), float(), etc. are generally used to perform type conversions. However, these require you to know at development time what type you want to convert to. A subproblem of some Python code I'm trying to write is as follows:</p>
<p>Given two variables, <code>foo</code> and <code>bar</code>, find the type of <code>foo</code>. (It is not known at development time, as this is generic code.) Then, attempt to convert <code>bar</code> to whatever type <code>foo</code> is. If this cannot be done, throw an exception.</p>
<p>For example, let's say you call the function that does this <code>conv</code>. Its signature would look like</p>
<pre><code>def conv(foo, bar) :
# Do stuff.
</code></pre>
<p>It would be called something like:</p>
<pre><code>result = conv(3.14, "2.718") # result is now 2.718, as a float.
</code></pre>
| 7
|
2009-03-07T17:15:41Z
| 8,390,964
|
<pre><code>type(foo)
</code></pre>
<p>is definitely the best, if you want to check a type then "type" is the best method, and I am on <code>python 2.7 - 3.2.2, type()</code> works perfectly.</p>
| 0
|
2011-12-05T19:50:20Z
|
[
"python",
"reflection",
"type-conversion",
"introspection",
"python-datamodel"
] |
How to change cursor position of wxRichTextCtrl in event handler?
| 622,417
|
<p>I have a RichTextCtrl in my application, that has a handler for <code>EVT_KEY_DOWN</code>. The code that is executed is the following :</p>
<pre><code>
def move_caret(self):
pdb.set_trace()
self.rich.GetCaret().Move((0,0))
self.Refresh()
def onClick(self,event):
self.move_caret()
event.Skip()
</code></pre>
<p><strong>rich</strong> is my RichTextCtrl. </p>
<p>Here is what I would like it to do :</p>
<ul>
<li><p>on each key press, add the key to the control ( which is default behaviour )</p></li>
<li><p>move the cursor at the beginning of the control, first position </p></li>
</ul>
<p>Here's what it actually does :</p>
<ul>
<li><p>it adds the key to the control</p></li>
<li><p>I inspected the caret position, and the debugger reports it's located at 0,0 but on the control, it blinks at the current position ( which is position before I pressed a key + 1 )</p></li>
</ul>
<p>Do you see anything wrong here? There must be something I'm doing wrong.</p>
| 1
|
2009-03-07T20:18:27Z
| 623,292
|
<p>Apparently, there are two problems with your code:</p>
<ol>
<li><p>You listen on <code>EVT_KEY_DOWN</code>, which is probably handled before <code>EVT_TEXT</code>, whose default handler sets the cursor position.</p></li>
<li><p>You modify the <code>Caret</code> object instead of using <code>SetInsertionPoint</code> method, which both moves the caret and makes the next character appear in given place.</p></li>
</ol>
<p>So the working example (I tested it and it works as you would like it to) would be:</p>
<pre><code># Somewhere in __init__:
self.rich.Bind(wx.EVT_TEXT, self.onClick)
def onClick(self, event):
self.rich.SetInsertionPoint(0) # No refresh necessary.
event.Skip()
</code></pre>
<p><hr /></p>
<p><strong>EDIT</strong>: if you want the text to be added at the end, but the cursor to remain at the beginning (see comments), you can take advantage of the fact that <code>EVT_KEY_DOWN</code> is handled before <code>EVT_TEXT</code> (which in turn is handled after character addition). So the order of events is:</p>
<ol>
<li>handle <code>EVT_KEY_DOWN</code></li>
<li>add character at current insertion point</li>
<li>handle <code>EVT_TEXT</code></li>
</ol>
<p>Adding a handler of <code>EVT_KEY_DOWN</code> that moves the insertion point to the end just before actually adding the character does the job quite nicely. So, in addition to the code mentioned earlier, write:</p>
<pre><code># Somewhere in __init__:
self.rich.Bind(wx.EVT_KEY_DOWN, self.onKeyDown)
def onKeyDown(self, event):
self.rich.SetInsertionPointEnd()
event.Skip()
</code></pre>
<p>By the way, <code>event.Skip()</code> does not immediately invoke next event handler, it justs sets a flag in the <code>event</code> object, so that event processor knows whether to stop propagating the event after this handler.</p>
| 3
|
2009-03-08T09:00:18Z
|
[
"python",
"events",
"wxpython",
"wxwidgets"
] |
Increment Page Hit Count in Django
| 622,652
|
<p>I have a table with an <code>IntegerField</code> (<code>hit_count</code>), and when a page is visited (for example, <code>http://site/page/3</code>) I want record ID 3's <code>hit_count</code> column in the database to increment by 1.</p>
<p>The query should be like:</p>
<pre class="lang-sql prettyprint-override"><code>update table set hit_count = hit_count + 1 where id = 3
</code></pre>
<p>Can I do this with the standard Django Model conventions? Or should I just write the query by hand?</p>
| 16
|
2009-03-07T22:42:05Z
| 622,676
|
<p>The model conventions won't be atomic; write it by hand:</p>
<pre><code>BEGIN
SELECT * FROM table WHERE id=3 FOR UPDATE
UPDATE table SET hit_count=hit_count+1 WHERE id=3
COMMIT
</code></pre>
| 0
|
2009-03-07T22:59:17Z
|
[
"python",
"django",
"django-models"
] |
Increment Page Hit Count in Django
| 622,652
|
<p>I have a table with an <code>IntegerField</code> (<code>hit_count</code>), and when a page is visited (for example, <code>http://site/page/3</code>) I want record ID 3's <code>hit_count</code> column in the database to increment by 1.</p>
<p>The query should be like:</p>
<pre class="lang-sql prettyprint-override"><code>update table set hit_count = hit_count + 1 where id = 3
</code></pre>
<p>Can I do this with the standard Django Model conventions? Or should I just write the query by hand?</p>
| 16
|
2009-03-07T22:42:05Z
| 622,780
|
<p>I would start by looking at the documentation for <a href="http://docs.djangoproject.com/en/dev/topics/http/middleware/#topics-http-middleware" rel="nofollow">middleware</a>. Ignacio's comment about the lack of atomic transactions is true, but this is a problem with the entire Django framework. Unless you're concerned about having a 100% accurate counter I wouldn't worry about it.</p>
| 0
|
2009-03-08T00:04:07Z
|
[
"python",
"django",
"django-models"
] |
Increment Page Hit Count in Django
| 622,652
|
<p>I have a table with an <code>IntegerField</code> (<code>hit_count</code>), and when a page is visited (for example, <code>http://site/page/3</code>) I want record ID 3's <code>hit_count</code> column in the database to increment by 1.</p>
<p>The query should be like:</p>
<pre class="lang-sql prettyprint-override"><code>update table set hit_count = hit_count + 1 where id = 3
</code></pre>
<p>Can I do this with the standard Django Model conventions? Or should I just write the query by hand?</p>
| 16
|
2009-03-07T22:42:05Z
| 622,859
|
<p>As gerdemb says, you should write it into a middleware to make it really reusable. Or (simpler) write a function decorator. In fact, there are adaptors to use a middleware as a decorator and viceversa.</p>
<p>But if you're worried about performance and want to keep the DB queries per page hit low, you can use memcached's atomic increment operation. of course, in this case, you have to take care of persistence yourself.</p>
| 4
|
2009-03-08T01:24:07Z
|
[
"python",
"django",
"django-models"
] |
Increment Page Hit Count in Django
| 622,652
|
<p>I have a table with an <code>IntegerField</code> (<code>hit_count</code>), and when a page is visited (for example, <code>http://site/page/3</code>) I want record ID 3's <code>hit_count</code> column in the database to increment by 1.</p>
<p>The query should be like:</p>
<pre class="lang-sql prettyprint-override"><code>update table set hit_count = hit_count + 1 where id = 3
</code></pre>
<p>Can I do this with the standard Django Model conventions? Or should I just write the query by hand?</p>
| 16
|
2009-03-07T22:42:05Z
| 623,860
|
<p>If you use Django 1.1+, just use <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model">F expressions</a>:</p>
<pre><code>from django.db.models import F
...
MyModel.objects.filter(id=...).update(hit_count=F('hit_count')+1)
</code></pre>
<p>This will perform a single atomic database query.</p>
<p>As gerdemb says, you should consider putting this in a middleware to make it easily reusable so it doesn't clutter up all your views.</p>
<hr>
| 31
|
2009-03-08T16:46:13Z
|
[
"python",
"django",
"django-models"
] |
Unable to install Python without sudo access
| 622,744
|
<p>I extracted, configured and used make for the installation package in my server.</p>
<p>However, I could not use <em>make install</em>. I get the error</p>
<pre><code>[~/wepapps/python/Python-2.6.1]# make install
/usr/bin/install -c python /usr/local/bin/python2.6
/usr/bin/install: cannot create regular file `/usr/local/bin/python2.6': Permission denied
make: *** [altbininstall] Error 1
</code></pre>
<p>I run the folder with</p>
<pre><code>chmod +x Python-2.6.1
</code></pre>
<p>I get still the same error.</p>
<p>How can I run <em>make install</em> without sudo access?</p>
| 29
|
2009-03-07T23:42:54Z
| 622,753
|
<p>You can't; not to <code>/usr</code>, anyway. Only superusers can write to those directories. Try installing Python to a path under your home directory instead.</p>
| 2
|
2009-03-07T23:46:53Z
|
[
"python",
"installation",
"sudo"
] |
Unable to install Python without sudo access
| 622,744
|
<p>I extracted, configured and used make for the installation package in my server.</p>
<p>However, I could not use <em>make install</em>. I get the error</p>
<pre><code>[~/wepapps/python/Python-2.6.1]# make install
/usr/bin/install -c python /usr/local/bin/python2.6
/usr/bin/install: cannot create regular file `/usr/local/bin/python2.6': Permission denied
make: *** [altbininstall] Error 1
</code></pre>
<p>I run the folder with</p>
<pre><code>chmod +x Python-2.6.1
</code></pre>
<p>I get still the same error.</p>
<p>How can I run <em>make install</em> without sudo access?</p>
| 29
|
2009-03-07T23:42:54Z
| 622,810
|
<blockquote>
<p>How can I install to a path under my home directory?</p>
</blockquote>
<pre><code>mkdir /home/masi/.local
cd Python-2.6.1
make clean
./configure --prefix=/home/masi/.local
make
make install
</code></pre>
<p>Then run using:</p>
<pre><code>/home/masi/.local/bin/python
</code></pre>
<p>Similarly if you have scripts (eg. CGI) that require your own user version of Python you have to tell them explicitly:</p>
<pre><code>#!/home/masi/.local/bin/python
</code></pre>
<p>instead of using the default system Python which â#!/usr/bin/env pythonâ will choose.</p>
<p>You can alter your PATH setting to make just typing âpythonâ from the console run that version, but it won't help for web apps being run under a different user.</p>
<p>If you compile something that links to Python (eg. mod_wsgi) you have to tell it where to find your Python or it will use the system one instead. This is often done something like:</p>
<pre><code>./configure --prefix=/home/masi/.local --with-python=/home/masi/.local
</code></pre>
<p>For other setup.py-based extensions like MySQLdb you simply have to run the setup.py script with the correct version of Python:</p>
<pre><code>/home/masi/.local/bin/python setup.py install
</code></pre>
| 84
|
2009-03-08T00:33:25Z
|
[
"python",
"installation",
"sudo"
] |
Unable to install Python without sudo access
| 622,744
|
<p>I extracted, configured and used make for the installation package in my server.</p>
<p>However, I could not use <em>make install</em>. I get the error</p>
<pre><code>[~/wepapps/python/Python-2.6.1]# make install
/usr/bin/install -c python /usr/local/bin/python2.6
/usr/bin/install: cannot create regular file `/usr/local/bin/python2.6': Permission denied
make: *** [altbininstall] Error 1
</code></pre>
<p>I run the folder with</p>
<pre><code>chmod +x Python-2.6.1
</code></pre>
<p>I get still the same error.</p>
<p>How can I run <em>make install</em> without sudo access?</p>
| 29
|
2009-03-07T23:42:54Z
| 16,740,313
|
<p>Extending bobince answer, there is an issue if you don't have the readline development package installed in your system, and you don't have root access. </p>
<p>When Python is compiled without readline, your arrow keys won't work in the interpreter. However, you can install the readline standalone package as follows: <a href="http://stackoverflow.com/questions/3764730/adding-readline-functionality-without-recompiling-python">Adding Readline Functionality Without Recompiling Python</a></p>
<p>On the other hand, if you prefer to compile python using a local installation of readline, here's how.</p>
<p>Before doing as bobince was telling, compile and install readline. These are the steps to do so:</p>
<ul>
<li>wget <a href="ftp://ftp.cwru.edu/pub/bash/readline-6.2.tar.gz" rel="nofollow">ftp://ftp.cwru.edu/pub/bash/readline-6.2.tar.gz</a> </li>
<li>tar -zxvf readline-6.2.tar.gz</li>
<li>cd readline-6.2</li>
<li>./configure --with-prefix=$HOME/.local</li>
<li>make</li>
<li>make install</li>
</ul>
<p>Then, add this line to your .bash_profile script:</p>
<pre><code>export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/.local/lib
</code></pre>
<p>Last, but not least, execute the following command</p>
<pre><code>export LDFLAGS="-L$HOME/.local"
</code></pre>
<p>I hope this helps someone! </p>
| 1
|
2013-05-24T17:13:04Z
|
[
"python",
"installation",
"sudo"
] |
Python, PIL, crop problem
| 622,783
|
<p>Can't seem to get crop working correctly, problem is, it crops a region of correct dimensions, but always from top left corner (0, 0), instead of from my passed coordinates.</p>
<pre><code>image = Image.open(input)
region = image.crop((1000,400,2000,600)
region.save(output)
</code></pre>
<p>In image.py from PIL, method _ImageCrop I've printed out.. :</p>
<pre><code>print x0, y0, x1, y1
self.__crop = x0, y0, x1, y1
</code></pre>
<p>Values seem to be correct.</p>
<p>Input is a JPEG image of size 1600x2390.</p>
<p>Python version: 2.5,
PIL version: 1.1.6</p>
<p>Any suggestions? Thanks</p>
| 0
|
2009-03-08T00:07:03Z
| 622,821
|
<p>Works For Me: Python 2.6.1, PIL 1.1.6, JPEG of size 2020x1338 pixels.</p>
<p>Are you sure you mean a JPEG of 1600x2390 and not 2390x1600? The (1000,400,2000,600) box dimensions are outside the size of a 1600-wide image; if I try this I get garbage data outside the intersecting area.</p>
| 1
|
2009-03-08T00:42:38Z
|
[
"python",
"python-imaging-library",
"crop"
] |
Python, PIL, crop problem
| 622,783
|
<p>Can't seem to get crop working correctly, problem is, it crops a region of correct dimensions, but always from top left corner (0, 0), instead of from my passed coordinates.</p>
<pre><code>image = Image.open(input)
region = image.crop((1000,400,2000,600)
region.save(output)
</code></pre>
<p>In image.py from PIL, method _ImageCrop I've printed out.. :</p>
<pre><code>print x0, y0, x1, y1
self.__crop = x0, y0, x1, y1
</code></pre>
<p>Values seem to be correct.</p>
<p>Input is a JPEG image of size 1600x2390.</p>
<p>Python version: 2.5,
PIL version: 1.1.6</p>
<p>Any suggestions? Thanks</p>
| 0
|
2009-03-08T00:07:03Z
| 2,674,199
|
<p>I`m do next:</p>
<pre><code>cover=Image.open(path_to_cover+"/shablon1.jpg")
</code></pre>
<p>....</p>
<pre><code>def generit_nomer_proekt(self,nomer):
size_box=(160,40)
font=ImageFont.truetype('/home/vintello/workspace/mpg_to_dvd/src/cover/ttf/aricyr.ttf',int(30))
im = Image.new ( "RGB", size_box , "white" )
draw = ImageDraw.Draw ( im )
draw.text ( (20,0), unicode(nomer,"utf-8"), fill="#74716f", font=font )
return im
</code></pre>
<p>.....</p>
<pre><code>nazv_vert=self.generit_nomer_proekt(nomer)
coo=nazv_vert.size
left_x=1575
left_y=383
box_vert_nazv=(left_x,left_y,left_x+coo[0],left_y+coo[1])
cover.paste(nazv_vert,box_vert_nazv)
</code></pre>
<p>or if you wont as PNG past use:</p>
<pre><code>cover.paste(nazv_vert,box_vert_nazv,nazv_vert)
</code></pre>
| 0
|
2010-04-20T10:15:13Z
|
[
"python",
"python-imaging-library",
"crop"
] |
Django Passing Custom Form Parameters to Formset
| 622,982
|
<blockquote>
<p>This was fixed in Django 1.9 with <a href="https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms">form_kwargs</a>.</p>
</blockquote>
<p>I have a Django Form that looks like this:</p>
<pre><code>class ServiceForm(forms.Form):
option = forms.ModelChoiceField(queryset=ServiceOption.objects.none())
rate = forms.DecimalField(widget=custom_widgets.SmallField())
units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField())
def __init__(self, *args, **kwargs):
affiliate = kwargs.pop('affiliate')
super(ServiceForm, self).__init__(*args, **kwargs)
self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate)
</code></pre>
<p>I call this form with something like this:</p>
<pre><code>form = ServiceForm(affiliate=request.affiliate)
</code></pre>
<p>Where <code>request.affiliate</code> is the logged in user. This works as intended.</p>
<p>My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this:</p>
<pre><code>ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3)
</code></pre>
<p>And then I need to create it like this:</p>
<pre><code>formset = ServiceFormSet()
</code></pre>
<p>Now how can I pass affiliate=request.affiliate to the individual forms this way?</p>
| 113
|
2009-03-08T03:36:08Z
| 623,030
|
<p>I would build the form class dynamically in a function, so that it has access to the affiliate via closure:</p>
<pre><code>def make_service_form(affiliate):
class ServiceForm(forms.Form):
option = forms.ModelChoiceField(
queryset=ServiceOption.objects.filter(affiliate=affiliate))
rate = forms.DecimalField(widget=custom_widgets.SmallField())
units = forms.IntegerField(min_value=1,
widget=custom_widgets.SmallField())
return ServiceForm
</code></pre>
<p>As a bonus, you don't have to rewrite the queryset in the option field. The downside is that subclassing is a little funky. (Any subclass has to be made in a similar way.)</p>
<p><strong>edit:</strong></p>
<p>In response to a comment, you can call this function about any place you would use the class name:</p>
<pre><code>def view(request):
affiliate = get_object_or_404(id=request.GET.get('id'))
formset_cls = formset_factory(make_service_form(affiliate))
formset = formset_cls(request.POST)
...
</code></pre>
| 43
|
2009-03-08T04:24:10Z
|
[
"python",
"django",
"forms",
"django-forms"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.