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
sequence |
---|---|---|---|---|---|---|---|---|---|
How can I reboot a Windows XP64 Machine in a Python Script? | 341,138 | <p>How can I reboot a Windows XP64 Machine in a Python Script? This machine does not have the "shutdown" or "restart" executables available.</p>
| 4 | 2008-12-04T16:06:52Z | 341,329 | <p>You can use win32api module and call WinApi functions.
<a href="http://code.activestate.com/recipes/360649/" rel="nofollow">Recipe at code.activestate.com</a></p>
| 2 | 2008-12-04T17:01:18Z | [
"python",
"windows"
] |
How can I reboot a Windows XP64 Machine in a Python Script? | 341,138 | <p>How can I reboot a Windows XP64 Machine in a Python Script? This machine does not have the "shutdown" or "restart" executables available.</p>
| 4 | 2008-12-04T16:06:52Z | 341,369 | <p>found it </p>
<p>win32api.InitiateSystemShutdown("localhost", "Maintenance Reboot", 60, 1, 1)</p>
| 4 | 2008-12-04T17:10:04Z | [
"python",
"windows"
] |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | <p>I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?</p>
<p>I want to play with Python 3 while still being able to run 2.x scripts on the same machine.</p>
| 69 | 2008-12-04T16:18:57Z | 341,216 | <p>As far as I know Python runs off of the commandline using the PATH variable as opposed to a registry setting.</p>
<p>So if you point to the correct version on your PATH you will use that. Remember to restart your command prompt to use the new PATH settings.</p>
| 2 | 2008-12-04T16:29:01Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | <p>I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?</p>
<p>I want to play with Python 3 while still being able to run 2.x scripts on the same machine.</p>
| 69 | 2008-12-04T16:18:57Z | 341,218 | <p>You can have both installed.</p>
<p>You should write in front of your script :</p>
<pre><code>#!/bin/env python2.6
</code></pre>
<p>or eventually..</p>
<pre><code>#!/bin/env python3.0
</code></pre>
<h2>Update</h2>
<p>My solution work perfectly with Unix, after a quick search on <a href="http://news.softpedia.com/news/Your-First-Python-Script-on-Windows-81974.shtml">Google</a>, here is the Windows solution:</p>
<pre><code>#!c:/Python/python3_0.exe -u
</code></pre>
<p>Same thing... in front of your script</p>
| 28 | 2008-12-04T16:29:38Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | <p>I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?</p>
<p>I want to play with Python 3 while still being able to run 2.x scripts on the same machine.</p>
| 69 | 2008-12-04T16:18:57Z | 341,231 | <p>I think there is an option to setup the windows file association for .py files in the installer. Uncheck it and you should be fine.</p>
<p>If not, you can easily re-associate .py files with the previous version. The simplest way is to right click on a .py file, select "open with" / "choose program". On the dialog that appears, select or browse to the version of python you want to use by default, and check the "always use this program to open this kind of file" checkbox. </p>
| 1 | 2008-12-04T16:33:47Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | <p>I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?</p>
<p>I want to play with Python 3 while still being able to run 2.x scripts on the same machine.</p>
| 69 | 2008-12-04T16:18:57Z | 341,444 | <p>I would assume so, I have Python 2.4, 2.5 and 2.6 installed side-by-side on the same computer.</p>
| 0 | 2008-12-04T17:31:33Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | <p>I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?</p>
<p>I want to play with Python 3 while still being able to run 2.x scripts on the same machine.</p>
| 69 | 2008-12-04T16:18:57Z | 436,455 | <p>I'm using 2.5, 2.6, and 3.0 from the shell with one line batch scripts of the form:</p>
<pre><code>:: The @ symbol at the start turns off the prompt from displaying the command.
:: The % represents an argument, while the * means all of them.
@c:\programs\pythonX.Y\python.exe %*
</code></pre>
<p>Name them <code>pythonX.Y.bat</code> and put them somewhere in your PATH. Copy the file for the preferred minor version (i.e. the latest) to <code>pythonX.bat</code>. (E.g. <code>copy python2.6.bat python2.bat</code>.) Then you can use <code>python2 file.py</code> from anywhere.</p>
<p>However, this doesn't help or even affect the Windows file association situation. For that you'll need a launcher program that reads the <code>#!</code> line, and then associate that with .py and .pyw files.</p>
| 9 | 2009-01-12T18:26:55Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | <p>I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?</p>
<p>I want to play with Python 3 while still being able to run 2.x scripts on the same machine.</p>
| 69 | 2008-12-04T16:18:57Z | 453,580 | <p>You should make sure that the PATH environment variable doesn't contain both python.exe files ( add the one you're currently using to run scripts on a day to day basis ) , or do as Kniht suggested with the batch files .
Aside from that , I don't see why not .</p>
<p>P.S : I have 2.6 installed as my <strong>"primary"</strong> python and 3.0 as my <strong>"play"</strong> python . The 2.6 is included in the <strong>PATH</strong> . Everything works fine .</p>
| 1 | 2009-01-17T16:53:19Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | <p>I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?</p>
<p>I want to play with Python 3 while still being able to run 2.x scripts on the same machine.</p>
| 69 | 2008-12-04T16:18:57Z | 604,714 | <p>The Python installation normally associates <code>.py</code>, <code>.pyw</code> and <code>.pyc</code> files with the Python interpreter. So you can run a Python script either by double-clicking it in Explorer or by typing its name in a command-line window (so no need to type <code>python scriptname.py</code>, just <code>scriptname.py</code> will do).</p>
<p>If you want to manually change this association, you can edit these keys in the Windows registry:</p>
<pre><code>HKEY_CLASSES_ROOT\Python.File\shell\open\command
HKEY_CLASSES_ROOT\Python.NoConFile\shell\open\command
HKEY_CLASSES_ROOT\Python.CompiledFile\shell\open\command
</code></pre>
<h2>Python Launcher</h2>
<p>People have been working on a Python launcher for Windows: a lightweight program associated with <code>.py</code> and <code>.pyw</code> files which would look for a "shebang" line (similar to Linux et al) on the first line, and launch Python 2.x or 3.x as required. See <a href="http://blog.python.org/2011/07/python-launcher-for-windows_11.html" rel="nofollow">"A Python Launcher for Windows"</a> blog post for details.</p>
| 3 | 2009-03-03T00:57:41Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | <p>I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?</p>
<p>I want to play with Python 3 while still being able to run 2.x scripts on the same machine.</p>
| 69 | 2008-12-04T16:18:57Z | 762,725 | <p>Here you go...</p>
<p><strong>winpylaunch.py</strong></p>
<pre><code>#
# Looks for a directive in the form: #! C:\Python30\python.exe
# The directive must start with #! and contain ".exe".
# This will be assumed to be the correct python interpreter to
# use to run the script ON WINDOWS. If no interpreter is
# found then the script will be run with 'python.exe'.
# ie: whatever one is found on the path.
# For example, in a script which is saved as utf-8 and which
# runs on Linux and Windows and uses the Python 2.6 interpreter...
#
# #!/usr/bin/python
# #!C:\Python26\python.exe
# # -*- coding: utf-8 -*-
#
# When run on Linux, Linux uses the /usr/bin/python. When run
# on Windows using winpylaunch.py it uses C:\Python26\python.exe.
#
# To set up the association add this to the registry...
#
# HKEY_CLASSES_ROOT\Python.File\shell\open\command
# (Default) REG_SZ = "C:\Python30\python.exe" S:\usr\bin\winpylaunch.py "%1" %*
#
# NOTE: winpylaunch.py itself works with either 2.6 and 3.0. Once
# this entry has been added python files can be run on the
# commandline and the use of winpylaunch.py will be transparent.
#
import subprocess
import sys
USAGE = """
USAGE: winpylaunch.py <script.py> [arg1] [arg2...]
"""
if __name__ == "__main__":
if len(sys.argv) > 1:
script = sys.argv[1]
args = sys.argv[2:]
if script.endswith(".py"):
interpreter = "python.exe" # Default to wherever it is found on the path.
lines = open(script).readlines()
for line in lines:
if line.startswith("#!") and line.find(".exe") != -1:
interpreter = line[2:].strip()
break
process = subprocess.Popen([interpreter] + [script] + args)
process.wait()
sys.exit()
print(USAGE)
</code></pre>
<p>I've just knocked this up on reading this thread (because it's what I was needing too). I have Pythons 2.6.1 and 3.0.1 on both Ubuntu and Windows. If it doesn't work for you post fixes here.</p>
| 7 | 2009-04-18T01:45:53Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | <p>I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?</p>
<p>I want to play with Python 3 while still being able to run 2.x scripts on the same machine.</p>
| 69 | 2008-12-04T16:18:57Z | 13,297,878 | <p>The official solution for coexistence seems to be the <a href="http://blog.python.org/2011/07/python-launcher-for-windows_11.html">Python Launcher for Windows</a>, PEP 397 which was included in <a href="http://www.python.org/download/releases/3.3.0/">Python 3.3.0</a>. Installing the release dumps <code>py.exe</code> and <code>pyw.exe</code> launchers into <code>%SYSTEMROOT%</code> (<code>C:\Windows</code>) which is then associated with <code>py</code> and <code>pyw</code> scripts, respectively.</p>
<p>In order to use the new launcher (without manually setting up your own associations to it), leave the "Register Extensions" option enabled. I'm not quite sure why, but on my machine it left Py 2.7 as the "default" (of the launcher).</p>
<p>Running scripts by calling them directly from the command line will route them through the launcher and parse the shebang (if it exists). You can also explicitly call the launcher and use switches: <code>py -3 mypy2script.py</code>. </p>
<p>All manner of shebangs seem to work</p>
<ul>
<li><code>#!C:\Python33\python.exe</code></li>
<li><code>#!python3</code></li>
<li><code>#!/usr/bin/env python3</code></li>
</ul>
<p>as well as wanton abuses</p>
<ul>
<li><code>#! notepad.exe</code></li>
</ul>
| 35 | 2012-11-08T21:11:48Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | <p>I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?</p>
<p>I want to play with Python 3 while still being able to run 2.x scripts on the same machine.</p>
| 69 | 2008-12-04T16:18:57Z | 32,195,996 | <p>Here's my setup:</p>
<ol>
<li>Install both Python 2.7 and 3.4 with the <a href="https://www.python.org/downloads/">windows installers</a>.</li>
<li>Go to <code>C:\Python34</code> (the default install path) and change python.exe to python3.exe</li>
<li><strong>Edit</strong> <a href="https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/sysdm_advancd_environmnt_addchange_variable.mspx?mfr=true">your environment variables</a> to include <code>C:\Python27\;C:\Python27\Scripts\;C:\Python34\;C:\Python34\Scripts\;</code></li>
</ol>
<p>Now in command line you can use <code>python</code> for 2.7 and <code>python3</code> for 3.4.</p>
| 7 | 2015-08-25T05:15:42Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | <p>I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?</p>
<p>I want to play with Python 3 while still being able to run 2.x scripts on the same machine.</p>
| 69 | 2008-12-04T16:18:57Z | 34,572,947 | <p><H3>Here is how to run Python 2 and 3 on the same machine</H3></p>
<ol>
<li> install Python 2.x </li>
<li>install Python 3.x </li>
<li>Start Powershell </li>
<li>Type <b>Python -2</b> to launch Python 2.x </li>
<li>Type <b>Python -3</b> to launch Python 2.x </li>
</ol>
<p>The <i>Python Launcher for Windows</i> was embedded into Python since Version 3.3, as promised in 2011 when the Stand alone first made its debut:</p>
<p><a href="https://docs.python.org/3/using/windows.html%0A" rel="nofollow">Python Launcher for Windows</a></p>
| 1 | 2016-01-03T03:10:43Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | <p>I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?</p>
<p>I want to play with Python 3 while still being able to run 2.x scripts on the same machine.</p>
| 69 | 2008-12-04T16:18:57Z | 38,094,030 | <p>From version 3.3 Python introduced Launcher for Windows utility <a href="https://docs.python.org/3/using/windows.html#python-launcher-for-windows" rel="nofollow">https://docs.python.org/3/using/windows.html#python-launcher-for-windows</a>.</p>
<p>So to be able to use multiple versions of Python:</p>
<ol>
<li>install Python 2.x (x is any version you need)</li>
<li>install Python 3.x (x is any version you need also you have to have one version 3.x >= 3.3) </li>
<li>open <strong>Command Prompt</strong> </li>
<li>type <strong>py -2.x</strong> to launch Python 2.x</li>
<li>type <strong>py -3.x</strong> to launch Python 3.x</li>
</ol>
| 2 | 2016-06-29T08:18:41Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] |
Python Decorators run before function it is decorating is called? | 341,379 | <p>As an example,</p>
<pre><code>def get_booking(f=None):
print "Calling get_booking Decorator"
def wrapper(request, **kwargs):
booking = _get_booking_from_session(request)
if booking == None:
# we don't have a booking in our session.
return HttpRedirect('/')
else:
return f(request=request, booking=booking, **kwargs)
return wrapper
@get_booking
def do_stuff(request, booking):
# do stuff here
</code></pre>
<p>The problem I am having is, the @get_booking decorator is being called even before I called the function that I am decorating.</p>
<p>Output on start:</p>
<pre><code>Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
[26/Oct/2008 19:54:04] "GET /onlinebooking/?id=1,2 HTTP/1.1" 302 0
[26/Oct/2008 19:54:05] "GET /onlinebooking/ HTTP/1.1" 200 2300
[26/Oct/2008 19:54:05] "GET /site-media/css/style.css HTTP/1.1" 200 800
[26/Oct/2008 19:54:05] "GET /site-media/css/jquery-ui-themeroller.css HTTP/1.1" 200 25492
</code></pre>
<p>I haven't even made a call to a function that is decorated at this point.</p>
<p>I am just getting started with decorators, so maybe I am missing something. Any help?</p>
| 4 | 2008-12-04T17:13:32Z | 341,389 | <p>I believe python decorators are just syntactic sugar.</p>
<pre><code>@foo
def bar ():
pass
</code></pre>
<p>is the same thing as</p>
<pre><code>def bar ():
pass
bar = foo(bar)
</code></pre>
<p>As you can see, <em>foo</em> is being called even though <em>bar</em> has not been called. This is why you see the output from your decorator function. Your output should contain a single line for every function you applied your decorator to.</p>
| 19 | 2008-12-04T17:17:27Z | [
"python",
"django",
"decorator"
] |
Python Decorators run before function it is decorating is called? | 341,379 | <p>As an example,</p>
<pre><code>def get_booking(f=None):
print "Calling get_booking Decorator"
def wrapper(request, **kwargs):
booking = _get_booking_from_session(request)
if booking == None:
# we don't have a booking in our session.
return HttpRedirect('/')
else:
return f(request=request, booking=booking, **kwargs)
return wrapper
@get_booking
def do_stuff(request, booking):
# do stuff here
</code></pre>
<p>The problem I am having is, the @get_booking decorator is being called even before I called the function that I am decorating.</p>
<p>Output on start:</p>
<pre><code>Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
[26/Oct/2008 19:54:04] "GET /onlinebooking/?id=1,2 HTTP/1.1" 302 0
[26/Oct/2008 19:54:05] "GET /onlinebooking/ HTTP/1.1" 200 2300
[26/Oct/2008 19:54:05] "GET /site-media/css/style.css HTTP/1.1" 200 800
[26/Oct/2008 19:54:05] "GET /site-media/css/jquery-ui-themeroller.css HTTP/1.1" 200 25492
</code></pre>
<p>I haven't even made a call to a function that is decorated at this point.</p>
<p>I am just getting started with decorators, so maybe I am missing something. Any help?</p>
| 4 | 2008-12-04T17:13:32Z | 341,391 | <p>A decorator is called as soon as the decorated function is defined. It is equivalent to writing something like this:</p>
<pre><code>def __do_stuff(...):
...
do_stuff = get_booking(__do_stuff)
</code></pre>
| 0 | 2008-12-04T17:18:22Z | [
"python",
"django",
"decorator"
] |
Python Decorators run before function it is decorating is called? | 341,379 | <p>As an example,</p>
<pre><code>def get_booking(f=None):
print "Calling get_booking Decorator"
def wrapper(request, **kwargs):
booking = _get_booking_from_session(request)
if booking == None:
# we don't have a booking in our session.
return HttpRedirect('/')
else:
return f(request=request, booking=booking, **kwargs)
return wrapper
@get_booking
def do_stuff(request, booking):
# do stuff here
</code></pre>
<p>The problem I am having is, the @get_booking decorator is being called even before I called the function that I am decorating.</p>
<p>Output on start:</p>
<pre><code>Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
[26/Oct/2008 19:54:04] "GET /onlinebooking/?id=1,2 HTTP/1.1" 302 0
[26/Oct/2008 19:54:05] "GET /onlinebooking/ HTTP/1.1" 200 2300
[26/Oct/2008 19:54:05] "GET /site-media/css/style.css HTTP/1.1" 200 800
[26/Oct/2008 19:54:05] "GET /site-media/css/jquery-ui-themeroller.css HTTP/1.1" 200 25492
</code></pre>
<p>I haven't even made a call to a function that is decorated at this point.</p>
<p>I am just getting started with decorators, so maybe I am missing something. Any help?</p>
| 4 | 2008-12-04T17:13:32Z | 341,406 | <p>python decorators are functions applied to a function to transform it:</p>
<pre><code>@my_decorator
def function (): ...
</code></pre>
<p>is like doing this: </p>
<pre><code>def function():...
function = my_decorator(function)
</code></pre>
<p>What you want to do is:</p>
<pre><code>def get_booking(f=None):
def wrapper(request, **kwargs):
print "Calling get_booking Decorator"
booking = _get_booking_from_session(request)
if booking == None:
# we don't have a booking in our session.
return HttpRedirect('/')
else:
return f(request=request, booking=booking, **kwargs)
return wrapper
</code></pre>
| 0 | 2008-12-04T17:20:57Z | [
"python",
"django",
"decorator"
] |
Python Decorators run before function it is decorating is called? | 341,379 | <p>As an example,</p>
<pre><code>def get_booking(f=None):
print "Calling get_booking Decorator"
def wrapper(request, **kwargs):
booking = _get_booking_from_session(request)
if booking == None:
# we don't have a booking in our session.
return HttpRedirect('/')
else:
return f(request=request, booking=booking, **kwargs)
return wrapper
@get_booking
def do_stuff(request, booking):
# do stuff here
</code></pre>
<p>The problem I am having is, the @get_booking decorator is being called even before I called the function that I am decorating.</p>
<p>Output on start:</p>
<pre><code>Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
[26/Oct/2008 19:54:04] "GET /onlinebooking/?id=1,2 HTTP/1.1" 302 0
[26/Oct/2008 19:54:05] "GET /onlinebooking/ HTTP/1.1" 200 2300
[26/Oct/2008 19:54:05] "GET /site-media/css/style.css HTTP/1.1" 200 800
[26/Oct/2008 19:54:05] "GET /site-media/css/jquery-ui-themeroller.css HTTP/1.1" 200 25492
</code></pre>
<p>I haven't even made a call to a function that is decorated at this point.</p>
<p>I am just getting started with decorators, so maybe I am missing something. Any help?</p>
| 4 | 2008-12-04T17:13:32Z | 341,513 | <p>Since you are starting with decorators, I think reading these will be helpful, so that you know the pitfalls and workarounds beforehand.</p>
<p>Here are two links to earlier discussions on decorators.</p>
<p><a href="http://stackoverflow.com/questions/306130/python-decorator-makes-function-forget-that-it-belongs-to-a-class#306277">http://stackoverflow.com/questions/306130/python-decorator-makes-function-forget-that-it-belongs-to-a-class#306277</a>
<a href="http://stackoverflow.com/questions/308999/what-does-functoolswraps-do">http://stackoverflow.com/questions/308999/what-does-functoolswraps-do</a></p>
<p>Moreover the second link mentions 'functools' a module for higher-order functions, that act on or return other functions. Use of functools.wraps is advised since it preserves the doc string of the original function(decorated one).</p>
<p>Another issue was wrong method signatures while generating automatic docs for my project.
but there is a workaround:
<a href="http://stackoverflow.com/questions/147816/preserving-signatures-of-decorated-functions">http://stackoverflow.com/questions/147816/preserving-signatures-of-decorated-functions</a></p>
<p>Hope this helps.</p>
| 2 | 2008-12-04T17:50:05Z | [
"python",
"django",
"decorator"
] |
Best way of sharing/managing our internal python library between applications | 342,425 | <p>Our company (xyz) is moving a lot of our Flash code to Python.</p>
<p>In Flash, we have a shared library between our Flash apps - package xyz. We can make changes to the package without fear of breaking other apps when they are deployed because Flash compiles their code and includes the contents of the library. We deploy the final SWF via RPM, and we're done. Updates to App1 and App2 won't ever break App3.</p>
<p>How would you approach this in Python, the shared library dependency. </p>
<p>App1, App2 and App3, could all require xyz-lib.rpm, and all use the same library files, but an updated xyz-lib.rpm would have to be explicitly tested against App1,2,3 <em>every time</em> there was a new library, and this is just onerous.</p>
<p>My current favorite solution - I could make app1.rpm include the library from when it was packaged - effectively some sort of static linking of the library. This, however, feels inelegant. (although the only additional cost is hard drive space == cheap.)</p>
<p>I know that solid management of the shared library is probably the best solution, but I keep trying to factor in that all the developers are human, and will make mistakes. We're going to make mistakes, and I don't want a deployment of app1 to break app2 and app3 - it's just a lot more to test and debug for.</p>
| 3 | 2008-12-04T23:16:44Z | 342,442 | <p>"explicitly tested against App1,2,3 every time there was a new library" actually isn't that onerous.</p>
<p>Two things.</p>
<ul>
<li><p>You need a formal set of API unit tests that the library <em>must</em> pass. This is just the API, not every nuance of functionality. If this passes, then your changes are good to go. If this fails, your changes broke the API.</p></li>
<li><p>You also need a set of unit tests for functionality, separate from the API. This is bigger, and might be classified as "onerous".</p></li>
</ul>
<p>Once you start unit testing, you get addicted. Once you have reasonably complete tests, this problem is easy to manage.</p>
| 4 | 2008-12-04T23:30:12Z | [
"python",
"deployment",
"shared-libraries",
"projects-and-solutions"
] |
Best way of sharing/managing our internal python library between applications | 342,425 | <p>Our company (xyz) is moving a lot of our Flash code to Python.</p>
<p>In Flash, we have a shared library between our Flash apps - package xyz. We can make changes to the package without fear of breaking other apps when they are deployed because Flash compiles their code and includes the contents of the library. We deploy the final SWF via RPM, and we're done. Updates to App1 and App2 won't ever break App3.</p>
<p>How would you approach this in Python, the shared library dependency. </p>
<p>App1, App2 and App3, could all require xyz-lib.rpm, and all use the same library files, but an updated xyz-lib.rpm would have to be explicitly tested against App1,2,3 <em>every time</em> there was a new library, and this is just onerous.</p>
<p>My current favorite solution - I could make app1.rpm include the library from when it was packaged - effectively some sort of static linking of the library. This, however, feels inelegant. (although the only additional cost is hard drive space == cheap.)</p>
<p>I know that solid management of the shared library is probably the best solution, but I keep trying to factor in that all the developers are human, and will make mistakes. We're going to make mistakes, and I don't want a deployment of app1 to break app2 and app3 - it's just a lot more to test and debug for.</p>
| 3 | 2008-12-04T23:16:44Z | 342,449 | <p>I've used variations of this <a href="http://code.activestate.com/recipes/497000/" rel="nofollow">cookbook entry</a> to distribute python apps. Basically it involves zipping all your python sources up into a zip file, then concatenating it with a shell script to import the source files.</p>
<p>This can be helpful if you need to give an app its own version of the library.</p>
| 1 | 2008-12-04T23:34:10Z | [
"python",
"deployment",
"shared-libraries",
"projects-and-solutions"
] |
Best way of sharing/managing our internal python library between applications | 342,425 | <p>Our company (xyz) is moving a lot of our Flash code to Python.</p>
<p>In Flash, we have a shared library between our Flash apps - package xyz. We can make changes to the package without fear of breaking other apps when they are deployed because Flash compiles their code and includes the contents of the library. We deploy the final SWF via RPM, and we're done. Updates to App1 and App2 won't ever break App3.</p>
<p>How would you approach this in Python, the shared library dependency. </p>
<p>App1, App2 and App3, could all require xyz-lib.rpm, and all use the same library files, but an updated xyz-lib.rpm would have to be explicitly tested against App1,2,3 <em>every time</em> there was a new library, and this is just onerous.</p>
<p>My current favorite solution - I could make app1.rpm include the library from when it was packaged - effectively some sort of static linking of the library. This, however, feels inelegant. (although the only additional cost is hard drive space == cheap.)</p>
<p>I know that solid management of the shared library is probably the best solution, but I keep trying to factor in that all the developers are human, and will make mistakes. We're going to make mistakes, and I don't want a deployment of app1 to break app2 and app3 - it's just a lot more to test and debug for.</p>
| 3 | 2008-12-04T23:16:44Z | 343,594 | <p>I also favour the solution of packing everything together and limit the dependency on the OS libraries to the minimal (glibc and that's it). Hard drive is cheap, customer and support time is not.</p>
<p>On windows, it's trivial with py2exe + InnoSetup.</p>
<p>On Linux, it looks like <a href="http://pypi.python.org/pypi/bbfreeze/0.95.4" rel="nofollow">bbfreeze</a> is the right way to handle this. Quoting from the homepage, it offers:</p>
<ul>
<li>zip/egg file import tracking :
bbfreeze tracks imports from zip files and includes whole egg files if some module is used from an eggfile. Packages using setuputils' pkg_resources module will now work (new in 0.95.0)</li>
<li>binary dependency tracking :
bbfreeze will track binary dependencies and will include DLLs and shared libraries needed by a frozen program.</li>
</ul>
| 1 | 2008-12-05T11:41:39Z | [
"python",
"deployment",
"shared-libraries",
"projects-and-solutions"
] |
Python logging in Django | 342,434 | <p>I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.</p>
<p>I have the root logger going to sys.stderr, and I have configured another logger to write to a file. This is in my settings.py file:</p>
<pre><code>sviewlog = logging.getLogger('MyApp.views.scans')
view_log_handler = logging.FileHandler('C:\\MyApp\\logs\\scan_log.log')
view_log_handler.setLevel(logging.INFO)
view_log_handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s'))
sviewlog.addHandler(view_log_handler)
</code></pre>
<p>Seems pretty simple. Here's the problem, though: whatever I write to the sviewlog gets written to the log file twice. The root logger only prints it once. It's like addHandler() is being called twice. And when I put my code through a debugger, this is exactly what I see. The code in settings.py is getting executed twice, so two FileHandlers are created and added to the same logger instance. But why? And how do I get around this?</p>
<p>Can anyone tell me what's going on here? I've tried moving the sviewlog logger/handler instantiation code to the file where it's used (since that actually seems like the appropriate place to me), but I have the same problem there. Most of the examples I've seen online use only the root logger, and I'd prefer to have multiple loggers.</p>
| 39 | 2008-12-04T23:24:26Z | 342,517 | <p>Why using python logger instead of django-logging? Give it a try it might just solve your problem. </p>
<p><a href="http://code.google.com/p/django-logging/wiki/Overview" rel="nofollow">http://code.google.com/p/django-logging/wiki/Overview</a> </p>
<p>At the moment it would only allow to view the root logger, but you can sure write to multiple loggers.</p>
| 1 | 2008-12-05T00:21:05Z | [
"python",
"django",
"logging"
] |
Python logging in Django | 342,434 | <p>I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.</p>
<p>I have the root logger going to sys.stderr, and I have configured another logger to write to a file. This is in my settings.py file:</p>
<pre><code>sviewlog = logging.getLogger('MyApp.views.scans')
view_log_handler = logging.FileHandler('C:\\MyApp\\logs\\scan_log.log')
view_log_handler.setLevel(logging.INFO)
view_log_handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s'))
sviewlog.addHandler(view_log_handler)
</code></pre>
<p>Seems pretty simple. Here's the problem, though: whatever I write to the sviewlog gets written to the log file twice. The root logger only prints it once. It's like addHandler() is being called twice. And when I put my code through a debugger, this is exactly what I see. The code in settings.py is getting executed twice, so two FileHandlers are created and added to the same logger instance. But why? And how do I get around this?</p>
<p>Can anyone tell me what's going on here? I've tried moving the sviewlog logger/handler instantiation code to the file where it's used (since that actually seems like the appropriate place to me), but I have the same problem there. Most of the examples I've seen online use only the root logger, and I'd prefer to have multiple loggers.</p>
| 39 | 2008-12-04T23:24:26Z | 343,575 | <p>Difficult to comment on your specific case. If settings.py is executed twice, then it's normal that you get two lines for every log sent.</p>
<p>The way we set it up in our projects is to have one module dedicated to logging. That modules has a "module singleton" pattern, so that we only execute the interesting code once.</p>
<p>It looks like this:</p>
<pre><code>def init_logging():
stdoutHandler = logging.StreamHandler( sys.stdout )
stdoutHandler.setLevel( DEBUG )
stdoutHandler.setFormatter( logging.Formatter( LOG_FORMAT_WITH_TIME ) )
logging.getLogger( LOG_AREA1 ).addHandler( stdoutHandler )
logInitDone=False
if not logInitDone:
logInitDone = True
init_logging()
</code></pre>
<p>Importing the log.py the first time will configure the logging correctly.</p>
| 13 | 2008-12-05T11:35:08Z | [
"python",
"django",
"logging"
] |
Python logging in Django | 342,434 | <p>I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.</p>
<p>I have the root logger going to sys.stderr, and I have configured another logger to write to a file. This is in my settings.py file:</p>
<pre><code>sviewlog = logging.getLogger('MyApp.views.scans')
view_log_handler = logging.FileHandler('C:\\MyApp\\logs\\scan_log.log')
view_log_handler.setLevel(logging.INFO)
view_log_handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s'))
sviewlog.addHandler(view_log_handler)
</code></pre>
<p>Seems pretty simple. Here's the problem, though: whatever I write to the sviewlog gets written to the log file twice. The root logger only prints it once. It's like addHandler() is being called twice. And when I put my code through a debugger, this is exactly what I see. The code in settings.py is getting executed twice, so two FileHandlers are created and added to the same logger instance. But why? And how do I get around this?</p>
<p>Can anyone tell me what's going on here? I've tried moving the sviewlog logger/handler instantiation code to the file where it's used (since that actually seems like the appropriate place to me), but I have the same problem there. Most of the examples I've seen online use only the root logger, and I'd prefer to have multiple loggers.</p>
| 39 | 2008-12-04T23:24:26Z | 343,701 | <p>A hackish way, but you can try to put the logging code inside an admin.py. It is supposed to be imported only once.</p>
<p>Alternatively; can you first check if <code>MyApp.views.scans</code> log exists? If it exists (maybe an error is raised) you can simply skip creation (and therefore not add the handler again). A cleaner way but I haven't tried this though.</p>
<p>Also there must be a more appropriate place to put this code (<code>__init__.py</code>?). <code>settings.py</code> is for settings.</p>
| 0 | 2008-12-05T12:42:52Z | [
"python",
"django",
"logging"
] |
Python logging in Django | 342,434 | <p>I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.</p>
<p>I have the root logger going to sys.stderr, and I have configured another logger to write to a file. This is in my settings.py file:</p>
<pre><code>sviewlog = logging.getLogger('MyApp.views.scans')
view_log_handler = logging.FileHandler('C:\\MyApp\\logs\\scan_log.log')
view_log_handler.setLevel(logging.INFO)
view_log_handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s'))
sviewlog.addHandler(view_log_handler)
</code></pre>
<p>Seems pretty simple. Here's the problem, though: whatever I write to the sviewlog gets written to the log file twice. The root logger only prints it once. It's like addHandler() is being called twice. And when I put my code through a debugger, this is exactly what I see. The code in settings.py is getting executed twice, so two FileHandlers are created and added to the same logger instance. But why? And how do I get around this?</p>
<p>Can anyone tell me what's going on here? I've tried moving the sviewlog logger/handler instantiation code to the file where it's used (since that actually seems like the appropriate place to me), but I have the same problem there. Most of the examples I've seen online use only the root logger, and I'd prefer to have multiple loggers.</p>
| 39 | 2008-12-04T23:24:26Z | 345,669 | <p>Allow me to answer my own question. The underlying problem here is that settings.py gets imported twice, or maybe even more (See <a href="http://www.mail-archive.com/[email protected]/msg39059.html">here</a>). (I still don't understand why this is. Maybe some Django expert could explain that to me.) This seems to be true of some other modules as well. At this point I don't think it's wise to make assumptions about how many times settings.py will be imported. For that matter, such assumptions aren't safe in general. I've had this code in places other than settings.py, and the results are similar.</p>
<p>You have to code around this. That is, you have to check your logger for existing handlers before adding additional handlers to it. This is a bit ugly because it's perfectly reasonable to have multiple handlers -- even of the same type -- attached to one logger. There are a few solutions to dealing with this. One is check the handlers property of your logger object. If you only want one handler and your length > 0, then don't add it. Personally I don't love this solution, because it gets messy with more handlers.</p>
<p>I prefer something like this (thanks to Thomas Guettler):</p>
<pre><code># file logconfig.py
if not hasattr(logging, "set_up_done"):
logging.set_up_done=False
def set_up(myhome):
if logging.set_up_done:
return
# set up your logging here
# ...
logging.set_up_done=True
</code></pre>
<p>I must say, I wish the fact that Django imports settings.py multiple times were better documented. And I would imagine that my configuration is somehow cause this multiple import, but I'm having trouble finding out what is causing the problem and why. Maybe I just couldn't find that in their documents, but I would think that's the sort of thing you need to warn your users about.</p>
| 28 | 2008-12-06T01:06:01Z | [
"python",
"django",
"logging"
] |
Python logging in Django | 342,434 | <p>I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.</p>
<p>I have the root logger going to sys.stderr, and I have configured another logger to write to a file. This is in my settings.py file:</p>
<pre><code>sviewlog = logging.getLogger('MyApp.views.scans')
view_log_handler = logging.FileHandler('C:\\MyApp\\logs\\scan_log.log')
view_log_handler.setLevel(logging.INFO)
view_log_handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s'))
sviewlog.addHandler(view_log_handler)
</code></pre>
<p>Seems pretty simple. Here's the problem, though: whatever I write to the sviewlog gets written to the log file twice. The root logger only prints it once. It's like addHandler() is being called twice. And when I put my code through a debugger, this is exactly what I see. The code in settings.py is getting executed twice, so two FileHandlers are created and added to the same logger instance. But why? And how do I get around this?</p>
<p>Can anyone tell me what's going on here? I've tried moving the sviewlog logger/handler instantiation code to the file where it's used (since that actually seems like the appropriate place to me), but I have the same problem there. Most of the examples I've seen online use only the root logger, and I'd prefer to have multiple loggers.</p>
| 39 | 2008-12-04T23:24:26Z | 346,474 | <p>You could get around your problem by checking for the number of handlers when you are doing your init.</p>
<pre><code>def init_logging():
stdoutHandler = logging.StreamHandler( sys.stdout )
stdoutHandler.setLevel( DEBUG )
stdoutHandler.setFormatter( logging.Formatter( LOG_FORMAT_WITH_TIME ) )
logger = logging.getLogger( LOG_AREA1 )
if len(logger.handlers) < 1:
logger.addHandler( stdoutHandler )
</code></pre>
<p>I don't think this is a great way to handle it. Personally, for logging in django with the python logging module, I create a logger in views.py for each application I'm interested in, then grab the logger in each view function.</p>
<pre><code>from django.http import HttpResponse
from magic import makeLogger
from magic import getLogger
makeLogger('myLogName', '/path/to/myLogName.log')
def testLogger(request):
logger = getLogger('myLogName')
logger.debug('this worked')
return HttpResponse('TEXT, HTML or WHATEVER')
</code></pre>
<p>This is a pretty good article about debugging django and covers some logging:
<a href="http://simonwillison.net/2008/May/22/debugging/" rel="nofollow">http://simonwillison.net/2008/May/22/debugging/</a></p>
| 3 | 2008-12-06T16:55:42Z | [
"python",
"django",
"logging"
] |
Python logging in Django | 342,434 | <p>I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.</p>
<p>I have the root logger going to sys.stderr, and I have configured another logger to write to a file. This is in my settings.py file:</p>
<pre><code>sviewlog = logging.getLogger('MyApp.views.scans')
view_log_handler = logging.FileHandler('C:\\MyApp\\logs\\scan_log.log')
view_log_handler.setLevel(logging.INFO)
view_log_handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s'))
sviewlog.addHandler(view_log_handler)
</code></pre>
<p>Seems pretty simple. Here's the problem, though: whatever I write to the sviewlog gets written to the log file twice. The root logger only prints it once. It's like addHandler() is being called twice. And when I put my code through a debugger, this is exactly what I see. The code in settings.py is getting executed twice, so two FileHandlers are created and added to the same logger instance. But why? And how do I get around this?</p>
<p>Can anyone tell me what's going on here? I've tried moving the sviewlog logger/handler instantiation code to the file where it's used (since that actually seems like the appropriate place to me), but I have the same problem there. Most of the examples I've seen online use only the root logger, and I'd prefer to have multiple loggers.</p>
| 39 | 2008-12-04T23:24:26Z | 1,099,037 | <p>To answer the question about why does "Django imports settings.py multiple times": it does not. </p>
<p>You are probably running a multiprocess/multithread web server which creates several python sub-interpreters, where each of those imports the code from your django app once.</p>
<p>Test that on the django test server and you should see that settings are not imported many times.</p>
<p>Some time ago, I had designed a nice singleton (python borg idiom version to be more precise) with my first django/apache app, before I quickly realised that yes, I had more than one instances of my singleton created...</p>
| 2 | 2009-07-08T16:05:30Z | [
"python",
"django",
"logging"
] |
Python logging in Django | 342,434 | <p>I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.</p>
<p>I have the root logger going to sys.stderr, and I have configured another logger to write to a file. This is in my settings.py file:</p>
<pre><code>sviewlog = logging.getLogger('MyApp.views.scans')
view_log_handler = logging.FileHandler('C:\\MyApp\\logs\\scan_log.log')
view_log_handler.setLevel(logging.INFO)
view_log_handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s'))
sviewlog.addHandler(view_log_handler)
</code></pre>
<p>Seems pretty simple. Here's the problem, though: whatever I write to the sviewlog gets written to the log file twice. The root logger only prints it once. It's like addHandler() is being called twice. And when I put my code through a debugger, this is exactly what I see. The code in settings.py is getting executed twice, so two FileHandlers are created and added to the same logger instance. But why? And how do I get around this?</p>
<p>Can anyone tell me what's going on here? I've tried moving the sviewlog logger/handler instantiation code to the file where it's used (since that actually seems like the appropriate place to me), but I have the same problem there. Most of the examples I've seen online use only the root logger, and I'd prefer to have multiple loggers.</p>
| 39 | 2008-12-04T23:24:26Z | 2,657,466 | <p>``To answer the question about why does "Django imports settings.py multiple times": it does not.''</p>
<p>Actually, it does get imported twice (skip past the first code chunk to get right into it but a good read if you've got the time):</p>
<p><a href="http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html" rel="nofollow">http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html</a></p>
<p>PS-- Sorry to revive an old thread.</p>
| 5 | 2010-04-17T06:12:37Z | [
"python",
"django",
"logging"
] |
Python logging in Django | 342,434 | <p>I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.</p>
<p>I have the root logger going to sys.stderr, and I have configured another logger to write to a file. This is in my settings.py file:</p>
<pre><code>sviewlog = logging.getLogger('MyApp.views.scans')
view_log_handler = logging.FileHandler('C:\\MyApp\\logs\\scan_log.log')
view_log_handler.setLevel(logging.INFO)
view_log_handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s'))
sviewlog.addHandler(view_log_handler)
</code></pre>
<p>Seems pretty simple. Here's the problem, though: whatever I write to the sviewlog gets written to the log file twice. The root logger only prints it once. It's like addHandler() is being called twice. And when I put my code through a debugger, this is exactly what I see. The code in settings.py is getting executed twice, so two FileHandlers are created and added to the same logger instance. But why? And how do I get around this?</p>
<p>Can anyone tell me what's going on here? I've tried moving the sviewlog logger/handler instantiation code to the file where it's used (since that actually seems like the appropriate place to me), but I have the same problem there. Most of the examples I've seen online use only the root logger, and I'd prefer to have multiple loggers.</p>
| 39 | 2008-12-04T23:24:26Z | 3,983,086 | <p>As of version 1.3, Django uses standard python logging, configured with the <code>LOGGING</code> setting (documented here: <a href="http://docs.djangoproject.com/en/1.3/ref/settings/#std%3asetting-LOGGING">1.3</a>, <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std%3asetting-LOGGING">dev</a>).</p>
<p>Django logging reference: <a href="http://docs.djangoproject.com/en/1.3/topics/logging/">1.3</a>, <a href="http://docs.djangoproject.com/en/dev/topics/logging/">dev</a>.</p>
| 23 | 2010-10-20T23:23:54Z | [
"python",
"django",
"logging"
] |
Python logging in Django | 342,434 | <p>I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.</p>
<p>I have the root logger going to sys.stderr, and I have configured another logger to write to a file. This is in my settings.py file:</p>
<pre><code>sviewlog = logging.getLogger('MyApp.views.scans')
view_log_handler = logging.FileHandler('C:\\MyApp\\logs\\scan_log.log')
view_log_handler.setLevel(logging.INFO)
view_log_handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s'))
sviewlog.addHandler(view_log_handler)
</code></pre>
<p>Seems pretty simple. Here's the problem, though: whatever I write to the sviewlog gets written to the log file twice. The root logger only prints it once. It's like addHandler() is being called twice. And when I put my code through a debugger, this is exactly what I see. The code in settings.py is getting executed twice, so two FileHandlers are created and added to the same logger instance. But why? And how do I get around this?</p>
<p>Can anyone tell me what's going on here? I've tried moving the sviewlog logger/handler instantiation code to the file where it's used (since that actually seems like the appropriate place to me), but I have the same problem there. Most of the examples I've seen online use only the root logger, and I'd prefer to have multiple loggers.</p>
| 39 | 2008-12-04T23:24:26Z | 4,933,153 | <p>You can also use a run-once Middleware to get a similar effect, without the private variables. Note that this will only configure the logging for web-requests - you'll need to find a different solution if you want logging in your shell or command runs.</p>
<pre><code>from django.conf import settings
from django.core.exceptions import MiddlewareNotUsed
import logging
import logging.handlers
import logging.config
__all__ = ('LoggingConfigMiddleware',)
class LoggingConfigMiddleware:
def __init__(self):
'''Initialise the logging setup from settings, called on first request.'''
if hasattr(settings, 'LOGGING'):
logging.config.dictConfig(settings.LOGGING)
elif getattr(settings, 'DEBUG', False):
print 'No logging configured.'
raise MiddlewareNotUsed('Logging setup only.')
</code></pre>
| 2 | 2011-02-08T12:43:34Z | [
"python",
"django",
"logging"
] |
Python logging in Django | 342,434 | <p>I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.</p>
<p>I have the root logger going to sys.stderr, and I have configured another logger to write to a file. This is in my settings.py file:</p>
<pre><code>sviewlog = logging.getLogger('MyApp.views.scans')
view_log_handler = logging.FileHandler('C:\\MyApp\\logs\\scan_log.log')
view_log_handler.setLevel(logging.INFO)
view_log_handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s'))
sviewlog.addHandler(view_log_handler)
</code></pre>
<p>Seems pretty simple. Here's the problem, though: whatever I write to the sviewlog gets written to the log file twice. The root logger only prints it once. It's like addHandler() is being called twice. And when I put my code through a debugger, this is exactly what I see. The code in settings.py is getting executed twice, so two FileHandlers are created and added to the same logger instance. But why? And how do I get around this?</p>
<p>Can anyone tell me what's going on here? I've tried moving the sviewlog logger/handler instantiation code to the file where it's used (since that actually seems like the appropriate place to me), but I have the same problem there. Most of the examples I've seen online use only the root logger, and I'd prefer to have multiple loggers.</p>
| 39 | 2008-12-04T23:24:26Z | 5,889,904 | <p>Reviving an old thread, but I was experiencing duplicate messages while using Django 1.3 Python logging with the <a href="http://docs.python.org/library/logging.config.html#configuration-dictionary-schema">dictConfig format</a>. </p>
<p>The <code>disable_existing_loggers</code> gets rid of the duplicate handler/logging problem with multiple settings.py loads, but you can still get duplicate log messages if you don't specify the <code>propagate</code> boolean appropriately on the specific <code>logger</code>. Namely, make sure you set <code>propagate=False</code> for child loggers. E.g.,</p>
<pre><code>'loggers': {
'django': {
'handlers':['null'],
'propagate': True,
'level':'INFO',
},
'django.request': {
'handlers': ['console'],
'level': 'ERROR',
'propagate': False,
},
'project': {
'handlers': ['console', 'project-log-file'],
'level': 'DEBUG',
'propagate': True,
},
'project.customapp': {
'handlers': ['console', 'customapp-log-file'],
'level': 'DEBUG',
'propagate': False,
},
}
</code></pre>
<p>Here, <code>project.customapp</code> sets <code>propagate=False</code> so that it won't be caught by the <code>project</code> logger as well. The <a href="http://docs.djangoproject.com/en/dev/topics/logging/">Django logging docs</a> are excellent, as always.</p>
| 9 | 2011-05-04T21:09:10Z | [
"python",
"django",
"logging"
] |
Python logging in Django | 342,434 | <p>I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.</p>
<p>I have the root logger going to sys.stderr, and I have configured another logger to write to a file. This is in my settings.py file:</p>
<pre><code>sviewlog = logging.getLogger('MyApp.views.scans')
view_log_handler = logging.FileHandler('C:\\MyApp\\logs\\scan_log.log')
view_log_handler.setLevel(logging.INFO)
view_log_handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s'))
sviewlog.addHandler(view_log_handler)
</code></pre>
<p>Seems pretty simple. Here's the problem, though: whatever I write to the sviewlog gets written to the log file twice. The root logger only prints it once. It's like addHandler() is being called twice. And when I put my code through a debugger, this is exactly what I see. The code in settings.py is getting executed twice, so two FileHandlers are created and added to the same logger instance. But why? And how do I get around this?</p>
<p>Can anyone tell me what's going on here? I've tried moving the sviewlog logger/handler instantiation code to the file where it's used (since that actually seems like the appropriate place to me), but I have the same problem there. Most of the examples I've seen online use only the root logger, and I'd prefer to have multiple loggers.</p>
| 39 | 2008-12-04T23:24:26Z | 7,658,823 | <p>To add to <strong>A Lee</strong> post, python logging documentation states this about propagate:</p>
<blockquote>
<p><strong>Logger.propagate</strong></p>
<p>If this evaluates to false, logging messages are not passed by this logger or by its child loggers to the handlers of higher level (ancestor) loggers. The constructor sets this attribute to 1.</p>
</blockquote>
<p>This means that if <code>propagate == False</code> then <strong>child logger</strong> will NOT pass logging message to its <strong>parent logger</strong></p>
| 0 | 2011-10-05T08:52:58Z | [
"python",
"django",
"logging"
] |
Best way to import version-specific python modules | 342,437 | <p>Which method makes the most sense for importing a module in python that is version specific? My use case is that I'm writing code that will be deployed into a python 2.3 environment and in a few months be upgraded to python 2.5. This:</p>
<pre><code>if sys.version_info[:2] >= (2, 5):
from string import Template
else:
from our.compat.string import Template
</code></pre>
<p>or this</p>
<pre><code>try:
from string import Template
except ImportError:
from our.compat.string import Template
</code></pre>
<p>I know that either case is equally correct and works correctly but which one is preferable?</p>
| 13 | 2008-12-04T23:28:10Z | 342,465 | <p>I would probably argue that the second one would be preferable. Sometimes, you can install a module from a newer version of python into an older one. For example, wsgiref comes with Python 2.5, but it isn't entirely uncommon for it to be installed into older versions (I think it will work with python 2.3 up).</p>
| 2 | 2008-12-04T23:40:20Z | [
"python",
"migration",
"module",
"code-migration"
] |
Best way to import version-specific python modules | 342,437 | <p>Which method makes the most sense for importing a module in python that is version specific? My use case is that I'm writing code that will be deployed into a python 2.3 environment and in a few months be upgraded to python 2.5. This:</p>
<pre><code>if sys.version_info[:2] >= (2, 5):
from string import Template
else:
from our.compat.string import Template
</code></pre>
<p>or this</p>
<pre><code>try:
from string import Template
except ImportError:
from our.compat.string import Template
</code></pre>
<p>I know that either case is equally correct and works correctly but which one is preferable?</p>
| 13 | 2008-12-04T23:28:10Z | 342,484 | <p>Always the second way - you never know what different Python installations will have installed. <code>Template</code> is a specific case where it matters less, but when you test for the capability instead of the versioning you're always more robust.</p>
<p>That's how I make <a href="http://www.testoob.org">Testoob</a> support Python 2.2 - 2.6: I try to import a module in different ways until it works. It's also relevant to 3rd-party libraries.</p>
<p>Here's an extreme case - supporting different options for ElementTree to appear:</p>
<pre><code>try: import elementtree.ElementTree as ET
except ImportError:
try: import cElementTree as ET
except ImportError:
try: import lxml.etree as ET
except ImportError:
import xml.etree.ElementTree as ET # Python 2.5 and up
</code></pre>
| 27 | 2008-12-04T23:57:33Z | [
"python",
"migration",
"module",
"code-migration"
] |
Python 2.6 multiprocessing.Queue compatible with threads? | 342,556 | <p>I am experimenting with the new multiprocessing module in Python 2.6. I am creating several processes each with its own multiprocessor.JoinableQueue instance. Each process spawns one or more worker threads (subclasses of threading.Thread) which share the JoinableQueue instance (passed in through each Thread's <code>__init__</code> method). It seems to generally work but occasionally and unpredictably fails with the following error:</p>
<pre><code> File "C:\Documents and Settings\Brian\Desktop\testscript.py", line 49, in run
self.queue.task_done()
File "C:\Python26\lib\multiprocessing\queues.py", line 293, in task_done
raise ValueError('task_done() called too many times')
ValueError: task_done() called too many times
</code></pre>
<p>My Queue get() and task_done() calls are right after each other so they should be equal. Anecdotally this seems to occur only when the work done between the get() and the task_done() is VERY quick. Inserting a small <code>time.sleep(0.01)</code> seems to alleviate the problem.</p>
<p>Any ideas what is going on? Can I use a multiprocessor Queue with threads instead of the more traditional (Queue.Queue)?</p>
<p>Thanks!</p>
<p>-brian</p>
| 7 | 2008-12-05T00:45:04Z | 342,586 | <p>You should pass Queue objects as target's arguments.</p>
<p>Example from <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing's documentation</a>:</p>
<pre><code>from multiprocessing import Process, Queue
def f(q):
q.put([42, None, 'hello'])
if __name__ == '__main__':
q = Queue()
p = Process(target=f, args=(q,))
p.start()
print q.get() # prints "[42, None, 'hello']"
p.join()
</code></pre>
<blockquote>
<p>Queues are thread and process safe.</p>
</blockquote>
| 2 | 2008-12-05T00:59:29Z | [
"python",
"multiprocessing",
"python-2.6"
] |
Python 2.6 multiprocessing.Queue compatible with threads? | 342,556 | <p>I am experimenting with the new multiprocessing module in Python 2.6. I am creating several processes each with its own multiprocessor.JoinableQueue instance. Each process spawns one or more worker threads (subclasses of threading.Thread) which share the JoinableQueue instance (passed in through each Thread's <code>__init__</code> method). It seems to generally work but occasionally and unpredictably fails with the following error:</p>
<pre><code> File "C:\Documents and Settings\Brian\Desktop\testscript.py", line 49, in run
self.queue.task_done()
File "C:\Python26\lib\multiprocessing\queues.py", line 293, in task_done
raise ValueError('task_done() called too many times')
ValueError: task_done() called too many times
</code></pre>
<p>My Queue get() and task_done() calls are right after each other so they should be equal. Anecdotally this seems to occur only when the work done between the get() and the task_done() is VERY quick. Inserting a small <code>time.sleep(0.01)</code> seems to alleviate the problem.</p>
<p>Any ideas what is going on? Can I use a multiprocessor Queue with threads instead of the more traditional (Queue.Queue)?</p>
<p>Thanks!</p>
<p>-brian</p>
| 7 | 2008-12-05T00:45:04Z | 342,608 | <p>Thanks for the quick response. I am passing the multiprocessing.Queue instances as arguments to each Process as you illustrate. The failure seems to occur in the threads. I am creating them by subclassing threading.Thread and passing the queue to the '<strong>init</strong>' method of each thread instance. This seems to be the accepted way to pass in Queues to thread subclasses. My only thought it that multiprocessing Queues may not be compatible with threads (although they are supposedly thread-safe).</p>
| -1 | 2008-12-05T01:12:12Z | [
"python",
"multiprocessing",
"python-2.6"
] |
Python 2.6 multiprocessing.Queue compatible with threads? | 342,556 | <p>I am experimenting with the new multiprocessing module in Python 2.6. I am creating several processes each with its own multiprocessor.JoinableQueue instance. Each process spawns one or more worker threads (subclasses of threading.Thread) which share the JoinableQueue instance (passed in through each Thread's <code>__init__</code> method). It seems to generally work but occasionally and unpredictably fails with the following error:</p>
<pre><code> File "C:\Documents and Settings\Brian\Desktop\testscript.py", line 49, in run
self.queue.task_done()
File "C:\Python26\lib\multiprocessing\queues.py", line 293, in task_done
raise ValueError('task_done() called too many times')
ValueError: task_done() called too many times
</code></pre>
<p>My Queue get() and task_done() calls are right after each other so they should be equal. Anecdotally this seems to occur only when the work done between the get() and the task_done() is VERY quick. Inserting a small <code>time.sleep(0.01)</code> seems to alleviate the problem.</p>
<p>Any ideas what is going on? Can I use a multiprocessor Queue with threads instead of the more traditional (Queue.Queue)?</p>
<p>Thanks!</p>
<p>-brian</p>
| 7 | 2008-12-05T00:45:04Z | 342,713 | <p>I didn't experiment with multi-processing in 2.6 yet, but I played a lot with pyprocessing (as it was called in 2.5).</p>
<p>I can see that you are looking for a number of processes with each spawning a set of threads respectively.</p>
<p>Since you are using the multiprocessing module, I will suggest use multi process and not multi thread approach, you will hit less problems like deadlocks, etc.</p>
<p>Create a queue object. <a href="http://pyprocessing.berlios.de/doc/queue-objects.html" rel="nofollow">http://pyprocessing.berlios.de/doc/queue-objects.html</a></p>
<p>For creating a multi process environment use a pool: <a href="http://pyprocessing.berlios.de/doc/pool-objects.html" rel="nofollow">http://pyprocessing.berlios.de/doc/pool-objects.html</a> which will manage the worker processes for you. You can then apply asynchronous/synchronous to the workers and can also add a callback for each worker if required. But remember call back is a common code block and it should return immediately (as mentioned in documentation)</p>
<p>Some additional info:
If required create a manager <a href="http://pyprocessing.berlios.de/doc/manager-objects.html" rel="nofollow">http://pyprocessing.berlios.de/doc/manager-objects.html</a> to manage the the access to the queue object. You will have to make the queue object shared for this. But the advantage is that, once shared and managed you can access this shared queue all over the network by creating proxy objects. This will enable you to call methods of a centralized shared queue object as (apparently) native methods on any network node.</p>
<p><strong>here is a code example from the documentation</strong></p>
<p><em>It is possible to run a manager server on one machine and have clients use it from other machines (assuming that the firewalls involved allow it).
Running the following commands creates a server for a shared queue which remote clients can use:</em></p>
<pre><code>>>> from processing.managers import BaseManager, CreatorMethod
>>> import Queue
>>> queue = Queue.Queue()
>>> class QueueManager(BaseManager):
... get_proxy = CreatorMethod(callable=lambda:queue, typeid='get_proxy')
...
>>> m = QueueManager(address=('foo.bar.org', 50000), authkey='none')
>>> m.serve_forever()
</code></pre>
<p><em>One client can access the server as follows:</em></p>
<pre><code>>>> from processing.managers import BaseManager, CreatorMethod
>>> class QueueManager(BaseManager):
... get_proxy = CreatorMethod(typeid='get_proxy')
...
>>> m = QueueManager.from_address(address=('foo.bar.org', 50000), authkey='none')
>>> queue = m.get_proxy()
>>> queue.put('hello')
</code></pre>
<p>If you insist on safe threaded stuff, PEP371 (multiprocessing) references this <a href="http://code.google.com/p/python-safethread/" rel="nofollow">http://code.google.com/p/python-safethread/</a></p>
| 4 | 2008-12-05T02:08:18Z | [
"python",
"multiprocessing",
"python-2.6"
] |
Python 2.6 multiprocessing.Queue compatible with threads? | 342,556 | <p>I am experimenting with the new multiprocessing module in Python 2.6. I am creating several processes each with its own multiprocessor.JoinableQueue instance. Each process spawns one or more worker threads (subclasses of threading.Thread) which share the JoinableQueue instance (passed in through each Thread's <code>__init__</code> method). It seems to generally work but occasionally and unpredictably fails with the following error:</p>
<pre><code> File "C:\Documents and Settings\Brian\Desktop\testscript.py", line 49, in run
self.queue.task_done()
File "C:\Python26\lib\multiprocessing\queues.py", line 293, in task_done
raise ValueError('task_done() called too many times')
ValueError: task_done() called too many times
</code></pre>
<p>My Queue get() and task_done() calls are right after each other so they should be equal. Anecdotally this seems to occur only when the work done between the get() and the task_done() is VERY quick. Inserting a small <code>time.sleep(0.01)</code> seems to alleviate the problem.</p>
<p>Any ideas what is going on? Can I use a multiprocessor Queue with threads instead of the more traditional (Queue.Queue)?</p>
<p>Thanks!</p>
<p>-brian</p>
| 7 | 2008-12-05T00:45:04Z | 2,218,036 | <p>You may be running into this bug:</p>
<p><a href="http://bugs.python.org/issue4660" rel="nofollow">http://bugs.python.org/issue4660</a></p>
| 1 | 2010-02-07T19:43:37Z | [
"python",
"multiprocessing",
"python-2.6"
] |
How should I learn to use the Windows API with Python? | 342,729 | <p>I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. So, how should I go about learning to use the Windows API with Python?</p>
| 17 | 2008-12-05T02:20:30Z | 342,740 | <p>Honestly, no. The Windows API is an 800 pound monster covered with hair. <a href="http://www.charlespetzold.com/faq.html" rel="nofollow">Charlie Petzold's 15 pound book</a> was the canonical reference once upon a time.</p>
<p>That said, the <a href="http://python.net/crew/mhammond/win32/" rel="nofollow">Python for Windows</a> folks have some good material. Microsoft has the <a href="http://msdn.microsoft.com/en-us/library/aa383749(VS.85).aspx" rel="nofollow">whole API online</a>, including some sample code and such. And the <a href="http://en.wikipedia.org/wiki/Win32" rel="nofollow">Wikipedia article</a> is a good overview.</p>
| 28 | 2008-12-05T02:26:44Z | [
"python",
"winapi"
] |
How should I learn to use the Windows API with Python? | 342,729 | <p>I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. So, how should I go about learning to use the Windows API with Python?</p>
| 17 | 2008-12-05T02:20:30Z | 342,831 | <p>Learning Win32 API is 5% of initial understanding of concepts and the patterns used and 95% of RTFM. </p>
<p>For those initial 5% the Petzold book is really good but I suspect that there ought to be some online tutorials which you can find in google as good as I can to find.</p>
<p>Really, once you get the hang of it it's really straight forward do to be able to do anything. Once you get there it would probably be time to move on to something better like QT and never touch Win32 API ever again. Nowadays no one really uses bare Win32 API for anything more than trivial due to the sheer overhead it involves and the extreme lack of comfort.</p>
| 3 | 2008-12-05T03:34:01Z | [
"python",
"winapi"
] |
How should I learn to use the Windows API with Python? | 342,729 | <p>I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. So, how should I go about learning to use the Windows API with Python?</p>
| 17 | 2008-12-05T02:20:30Z | 342,852 | <p>As <a href="http://stackoverflow.com/questions/342729/learning-the-win32-api#342740">Charlie</a> says : "this Api is an 800 pound monster covered with hair". </p>
<p>Consider using the express version (free) of visual studio for vb or c# (<a href="http://www.microsoft.com/express/" rel="nofollow">http://www.microsoft.com/express/</a>) along with the msdn library (<a href="http://msdn.microsoft.com/en-us/library/default.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/default.aspx</a>). this will give you as much exposure to the api as you want.</p>
| 1 | 2008-12-05T03:43:44Z | [
"python",
"winapi"
] |
How should I learn to use the Windows API with Python? | 342,729 | <p>I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. So, how should I go about learning to use the Windows API with Python?</p>
| 17 | 2008-12-05T02:20:30Z | 342,863 | <p>Once upon a time I read over some Win32 API tutorials at <a href="http://www.relisoft.com" rel="nofollow">www.relisoft.com</a></p>
<p>They are an anti-MFC and pro-Win32 API shop and have a manifesto of sorts explaining practical reasons for why.</p>
<p>They also have a general C++ tutorial. 99% of the time I like their programming style for what it's worth.</p>
| 0 | 2008-12-05T03:51:10Z | [
"python",
"winapi"
] |
How should I learn to use the Windows API with Python? | 342,729 | <p>I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. So, how should I go about learning to use the Windows API with Python?</p>
| 17 | 2008-12-05T02:20:30Z | 342,867 | <p>All you need is completely free on MSDN.COM. Win32 is easily programed using C/C++, C#, and Visual Basic. I recommend C/C++. YOu can download the Visual Studio Express editions <a href="http://www.microsoft.com/express/product/default.aspx" rel="nofollow">here</a>.</p>
<p>All the documentation (not an abbreviated form) is on the web <a href="http://msdn.microsoft.com/en-us/library/aa139672.aspx" rel="nofollow">here</a>. </p>
<p>Note that Win32 is often loosely used to mean "all the programming interface for Windows". More cannonically, it is the base native set of APIs for user mode applications. There a similar set of APIs for drivers and kernel components. You can learn about that <a href="http://www.microsoft.com/whdc/devtools/WDK/default.mspx" rel="nofollow">here</a>.</p>
<p>Microsoft has many other windows programming interfaces as well: The <a href="http://msdn.microsoft.com/en-us/library/w0x726c2.aspx" rel="nofollow">Common Language Run time and .NET frame work</a> is a manged layer on top of windows. There are many other API families as well such as <a href="http://msdn.microsoft.com/en-us/library/bb219737(VS.85).aspx" rel="nofollow">DX9 and DX10</a> (good link to game programming <a href="http://blogs.msdn.com/coding4fun/archive/2006/11/02/938703.aspx" rel="nofollow">here</a>). </p>
| 0 | 2008-12-05T03:54:35Z | [
"python",
"winapi"
] |
How should I learn to use the Windows API with Python? | 342,729 | <p>I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. So, how should I go about learning to use the Windows API with Python?</p>
| 17 | 2008-12-05T02:20:30Z | 342,876 | <p>I strongly recommend <a href="http://www.winprog.org/tutorial/">theForger's Win32 API Tutorial</a>. Its a C tutorial, but he pretty much holds your hand and shows you the basics. Its also pretty short, which is nice in a tutorial.</p>
| 5 | 2008-12-05T04:01:34Z | [
"python",
"winapi"
] |
How should I learn to use the Windows API with Python? | 342,729 | <p>I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. So, how should I go about learning to use the Windows API with Python?</p>
| 17 | 2008-12-05T02:20:30Z | 343,020 | <p>Since you've asked about Python, why do you need the Win32 API ? That's used for writing small, fast C/C++ programs. If your tool is Python, just download wxPython which runs wonderfully on Windows and produces sleek native GUIs with 1% the code and the effort.</p>
| 2 | 2008-12-05T06:06:53Z | [
"python",
"winapi"
] |
How should I learn to use the Windows API with Python? | 342,729 | <p>I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. So, how should I go about learning to use the Windows API with Python?</p>
| 17 | 2008-12-05T02:20:30Z | 343,372 | <p>" > free resource to learn how to use the windows API (preferably with python)</p>
<ol>
<li><p>You may refer <a href="http://books.google.co.in/books?id=ns1WMyLVnRMC" rel="nofollow">Python Programming on Win32 by Mark Hammond and Andy Robinson</a> along with <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32</a>.</p></li>
<li><p>If you are not interested to use <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32</a>, you can use <a href="http://docs.python.org/library/ctypes.html" rel="nofollow">ctypes â A foreign function library for Python</a> and <a href="http://www.winprog.org/tutorial/" rel="nofollow">the Forger's Win32 API Programming Tutorial</a>.</p></li>
<li><p>Refer <a href="http://mail.python.org/pipermail/python-list/2005-April/315719.html" rel="nofollow">Example Code : Shared Memory with Mutex (pywin32 and ctypes)</a></p></li>
</ol>
| 1 | 2008-12-05T10:02:57Z | [
"python",
"winapi"
] |
How should I learn to use the Windows API with Python? | 342,729 | <p>I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. So, how should I go about learning to use the Windows API with Python?</p>
| 17 | 2008-12-05T02:20:30Z | 343,804 | <p>Avoid tutorials (written by kids, for kids, newbie level)
Read the Petzold, Richter, Pietrek, Russinovich and Adv. Win32 api newsgroup
news://comp.os.ms-windows.programmer.win32</p>
| 7 | 2008-12-05T13:19:43Z | [
"python",
"winapi"
] |
How should I learn to use the Windows API with Python? | 342,729 | <p>I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. So, how should I go about learning to use the Windows API with Python?</p>
| 17 | 2008-12-05T02:20:30Z | 350,143 | <p>About 4 years ago I set out to truly understand the Windows API. I was coding in C# at the time, but I felt like the framework was abstracting me too much from the API (which it was). So I switched to Delphi (C++ or C would have also been good choices). </p>
<p>In my opinion, it is important that you start working in a language that creates native code and talks directly to the Windows API and makes you care about buffers, pointers, structures, and real constructs that Windows uses directly. C# is a great language, but not the best choice for learning the Windows API.</p>
<p>Next, buy Mark Russinovich's book "Windows Internals" <a href="http://amzn.to/xdu4Br">Amazon link</a>. This is the 5th edition. The 6th edition is coming out April 2012 and adds info about Server 2008 R2 and Windows 7. </p>
<h2>And now, for the most important (and best) resource for learning Win32 API:</h2>
<p>Mark Russinovich's <a href="http://www.microsoft.com/resources/sharedsource/windowsacademic/curriculumresourcekit.mspx">Windows Operating Systems Internals Curriculum</a> which is offered for free. </p>
<p>It is designed to be used by an instructor to teach students. I went through it and it is awesome. Full of examples, history, and detailed explanations. In my opinion, this is an ideal way to learn the Windows API.</p>
<p>Mark Russinovich is a Microsoft Technical Fellow (there are only 14 at MS including the creator of C#). He used to own Winternals until he sold it to MS, he has a PhD in Computer Engineering from Carnegie Mellon, he has been a frequent presenter at Microsoft conferences (even before he worked for them), and he is crazy smart. His presentations are one of the primary reasons I attend Microsoft TechEd every year.</p>
| 18 | 2008-12-08T16:53:44Z | [
"python",
"winapi"
] |
How should I learn to use the Windows API with Python? | 342,729 | <p>I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. So, how should I go about learning to use the Windows API with Python?</p>
| 17 | 2008-12-05T02:20:30Z | 350,170 | <p>Umm...a lot of people have put the cart before the horse on this one. The question I have for you is: why do you want to learn Win32? </p>
<p>If you want to learn it so you can build Windows user interfaces, perhaps consider wxPython instead. If you only plan on calling into non-visual Win32 APIs then the Petzold book may not be the best. There are tools like <a href="http://www.swig.org/" rel="nofollow">SWIG</a> that make calling libraries such as Win32 easier from languages like Python.</p>
| 0 | 2008-12-08T17:02:05Z | [
"python",
"winapi"
] |
How should I learn to use the Windows API with Python? | 342,729 | <p>I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. So, how should I go about learning to use the Windows API with Python?</p>
| 17 | 2008-12-05T02:20:30Z | 1,076,124 | <p>You have to start with these two books.</p>
<p><a href="http://www.charlespetzold.com/faq.html" rel="nofollow">Petzold</a> book: Great for learning messages and message pumps, GDI and User32 stuff.</p>
<p><a href="http://rads.stackoverflow.com/amzn/click/0735624240" rel="nofollow">Richter</a> book: The windows base services, viz. Processes, memory, threads and dlls</p>
| 0 | 2009-07-02T19:04:10Z | [
"python",
"winapi"
] |
Problem regarding 3.0's "hashlib" module | 343,204 | <p>I've been working on getting a 2.5 module ported to 3.0, mostly for my own education, when I've gotten stuck. The class "Builder" has as its init:</p>
<pre><code>def __init__(self, **options):
self._verifyOptions(options)
self._options = options
self._initDigest()
self._initBuildNames()
self._methods = []
</code></pre>
<p></p>
<p>But the error occurs at:</p>
<pre><code>def _initDigest(self):
import os, sys, hashlib
digester = hashlib.md5()
digester.update(self._options.get('code'))
self._digest = digester.hexdigest()
</code></pre>
<p>which has as its traceback:</p>
<pre><code>Traceback (most recent call last):
File "<pyshell#5>", line 5, in <module>
""", language="Cee")
File "C:\Python30\lib\site-packages\PyInline\__init__.py", line 31, in build
b = m.Builder(**args)
File "C:\Python30\lib\site-packages\PyInline\Cee.py", line 17, in __init__
self._initDigest()
File "C:\Python30\lib\site-packages\PyInline\Cee.py", line 27, in _initDigest
digester.update(self._options.get('code'))
TypeError: object supporting the buffer API required
</code></pre>
<p>I've run it through 2to3, but it isn't picking up on it. As far as I can tell, the update function is expecting the argument to be in the form of bytes/buffer, but I've tried several different methods to convert it and haven't succeeded.</p>
<p>As always, any assistance would be greatly appreciated. :)</p>
| 2 | 2008-12-05T08:35:13Z | 343,228 | <p>I havent tried 3.0 yet. But there is now a bigger distinction between a sequence of bytes and strings. The latter hold unicode codepoints while the former don't hold unicode but only <code>encoded</code> unicode strings. Hashes operate on sequences of bytes. So you will have to encode your (unicode) strings first bevore feeding them to a hash.</p>
| 0 | 2008-12-05T08:47:02Z | [
"python",
"python-3.x",
"py2to3"
] |
Problem regarding 3.0's "hashlib" module | 343,204 | <p>I've been working on getting a 2.5 module ported to 3.0, mostly for my own education, when I've gotten stuck. The class "Builder" has as its init:</p>
<pre><code>def __init__(self, **options):
self._verifyOptions(options)
self._options = options
self._initDigest()
self._initBuildNames()
self._methods = []
</code></pre>
<p></p>
<p>But the error occurs at:</p>
<pre><code>def _initDigest(self):
import os, sys, hashlib
digester = hashlib.md5()
digester.update(self._options.get('code'))
self._digest = digester.hexdigest()
</code></pre>
<p>which has as its traceback:</p>
<pre><code>Traceback (most recent call last):
File "<pyshell#5>", line 5, in <module>
""", language="Cee")
File "C:\Python30\lib\site-packages\PyInline\__init__.py", line 31, in build
b = m.Builder(**args)
File "C:\Python30\lib\site-packages\PyInline\Cee.py", line 17, in __init__
self._initDigest()
File "C:\Python30\lib\site-packages\PyInline\Cee.py", line 27, in _initDigest
digester.update(self._options.get('code'))
TypeError: object supporting the buffer API required
</code></pre>
<p>I've run it through 2to3, but it isn't picking up on it. As far as I can tell, the update function is expecting the argument to be in the form of bytes/buffer, but I've tried several different methods to convert it and haven't succeeded.</p>
<p>As always, any assistance would be greatly appreciated. :)</p>
| 2 | 2008-12-05T08:35:13Z | 343,284 | <p>I'm guessing that this line:</p>
<pre><code>digester.update(self._options.get('code'))
</code></pre>
<p>should become:</p>
<pre><code>digester.update(self._options.get('code').encode("utf-8"))
</code></pre>
<p>The actual desired encoding could be different in your case, but UTF-8 will work in all cases.</p>
| 4 | 2008-12-05T09:16:24Z | [
"python",
"python-3.x",
"py2to3"
] |
What happened to the python bindings for CGAL? | 343,210 | <p>I found the <a href="http://www.cgal.org/">Computational Geometry Algorithms Library</a> in my search for an algorithm to decompose a concave polygon into the minimum number of convex components. Links off the site and numerous google results indicate there are python bindings for it, which would be really handy, but all the links are dead! What happened to it? Where can I get it now?</p>
| 7 | 2008-12-05T08:36:49Z | 343,231 | <p>The fastest would probably be just to look at the code and re-implement it yourself in python. carrying around all of CGAL just for this tiny bit seems redundant.<br />
Also this calculation doesn't strike me as something that would extremely benefit by running compiled.</p>
| 0 | 2008-12-05T08:47:23Z | [
"python",
"geometry",
"polygon",
"computational-geometry",
"cgal"
] |
What happened to the python bindings for CGAL? | 343,210 | <p>I found the <a href="http://www.cgal.org/">Computational Geometry Algorithms Library</a> in my search for an algorithm to decompose a concave polygon into the minimum number of convex components. Links off the site and numerous google results indicate there are python bindings for it, which would be really handy, but all the links are dead! What happened to it? Where can I get it now?</p>
| 7 | 2008-12-05T08:36:49Z | 343,544 | <p><a href="http://cgal-python.gforge.inria.fr/" rel="nofollow">CGAL-Python</a> has been inert for over a year but the code (available through the "Download" link) seems to work fine, though not with Python 3.</p>
| 3 | 2008-12-05T11:19:22Z | [
"python",
"geometry",
"polygon",
"computational-geometry",
"cgal"
] |
What happened to the python bindings for CGAL? | 343,210 | <p>I found the <a href="http://www.cgal.org/">Computational Geometry Algorithms Library</a> in my search for an algorithm to decompose a concave polygon into the minimum number of convex components. Links off the site and numerous google results indicate there are python bindings for it, which would be really handy, but all the links are dead! What happened to it? Where can I get it now?</p>
| 7 | 2008-12-05T08:36:49Z | 441,903 | <p>You may also be interested in the GEOS library, which is available in Python through <a href="http://trac.gispython.org/lab/wiki/Shapely" rel="nofollow">Shapely</a> and <a href="http://geodjango.org/docs/geos.html" rel="nofollow">the GEOS API included in GeoDjango</a>.</p>
| 1 | 2009-01-14T04:28:24Z | [
"python",
"geometry",
"polygon",
"computational-geometry",
"cgal"
] |
What happened to the python bindings for CGAL? | 343,210 | <p>I found the <a href="http://www.cgal.org/">Computational Geometry Algorithms Library</a> in my search for an algorithm to decompose a concave polygon into the minimum number of convex components. Links off the site and numerous google results indicate there are python bindings for it, which would be really handy, but all the links are dead! What happened to it? Where can I get it now?</p>
| 7 | 2008-12-05T08:36:49Z | 13,081,921 | <p>A rewrite of the CGAL-Python bindings has been done as part of the cgal-bindings project. Check it out : <a href="http://code.google.com/p/cgal-bindings/">http://code.google.com/p/cgal-bindings/</a></p>
| 10 | 2012-10-26T06:32:58Z | [
"python",
"geometry",
"polygon",
"computational-geometry",
"cgal"
] |
What happened to the python bindings for CGAL? | 343,210 | <p>I found the <a href="http://www.cgal.org/">Computational Geometry Algorithms Library</a> in my search for an algorithm to decompose a concave polygon into the minimum number of convex components. Links off the site and numerous google results indicate there are python bindings for it, which would be really handy, but all the links are dead! What happened to it? Where can I get it now?</p>
| 7 | 2008-12-05T08:36:49Z | 19,105,479 | <p>Bindings for CGAL are inherently difficult. Because the library is heavily template based there's a combinatorial explosion of possible ways to use it. Any binding would need to pick and choose what to include.</p>
<p>However: Python package demakein (which I wrote), includes a module to compile C++ snippets on the fly then load them with cffi. The code snippets are cached to make subsequent runs faster. There's code in there that wraps up the parts of CGAL I needed, these are probably different to what you need but should give you an idea of how to use it. It can be used with CPython or PyPy, on Linux or OS X.</p>
| 1 | 2013-09-30T23:19:30Z | [
"python",
"geometry",
"polygon",
"computational-geometry",
"cgal"
] |
What can Pygame do in terms of graphics that wxPython can't? | 343,505 | <p>I want to develop a very simple 2D game in Python. Pygame is the most popular library for game development in Python, but I'm already quite familiar with wxPython and feel comfortable using it. I've even written a <a href="http://eli.thegreenplace.net/2008/05/31/a-tetris-clone-in-python-wxpython/">Tetris clone</a> in it, and it was pretty smooth.</p>
<p>I wonder, what does Pygame offer in terms of graphics (leaving sound aside, for a moment) that wxPython can't do ? Is it somehow simpler/faster to do graphics in Pygame than in wxPython ? Is it even more cross-platform ?</p>
<p>It looks like I'm missing something here, but I don't know what.</p>
| 16 | 2008-12-05T11:03:36Z | 344,002 | <p>Well, in theory there is nothing you can do with Pygame that you can't with wxPython. The point is not what but how. In my opinion, it's easier to write a game with PyGame becasue:</p>
<ul>
<li><p>It's faster. Pygame is based on SDL which is a C library specifically designed for games, it has been developed with speed in mind. When you develop games, you need speed.</p></li>
<li><p>Is a game library, not a general purpose canvas, It has classes and functions useful for sprites, transformations, input handling, drawing, collision detection. It also implements algorithms and techniques often used in games like dirty rectangles, page flipping, etc. </p></li>
<li><p>There are <a href="http://pygame.org/tags/">thousands of games</a> and examples made with it. It will be easier for you to discover how to do any trick.</p></li>
<li><p>There are a lot of <a href="http://pygame.org/tags/libraries">libraries</a> with effects and utilities you could reuse. You want an isometric game, there is a library, you want a physics engine, there is a library, you what some cool visual effect, there is a library.</p></li>
<li><p><a href="http://www.pyweek.org/">PyWeek</a>. :) This is to make the development of your game even funnier!</p></li>
</ul>
<p>For some very simple games like Tetris, the difference won't be too much, but if you want to develop a fairly complex game, believe me, you will want something like PyGame.</p>
| 19 | 2008-12-05T14:35:58Z | [
"python",
"graphics",
"wxpython",
"pygame"
] |
What can Pygame do in terms of graphics that wxPython can't? | 343,505 | <p>I want to develop a very simple 2D game in Python. Pygame is the most popular library for game development in Python, but I'm already quite familiar with wxPython and feel comfortable using it. I've even written a <a href="http://eli.thegreenplace.net/2008/05/31/a-tetris-clone-in-python-wxpython/">Tetris clone</a> in it, and it was pretty smooth.</p>
<p>I wonder, what does Pygame offer in terms of graphics (leaving sound aside, for a moment) that wxPython can't do ? Is it somehow simpler/faster to do graphics in Pygame than in wxPython ? Is it even more cross-platform ?</p>
<p>It looks like I'm missing something here, but I don't know what.</p>
| 16 | 2008-12-05T11:03:36Z | 344,045 | <p>wxPython is based on <a href="http://wxwidgets.org/">wxWidgets</a> which is a GUI-oriented toolkit. It has the advantage of using the styles and decorations provided by the system it runs on and thus it is very easy to write portable applications that integrate nicely into the look and feel of whatever you're running. You want a checkbox? Use wxCheckBox and wxPython will handle looks and interaction. </p>
<p>pyGame, on the other hand, is oriented towards game development and thus brings you closer to the hardware in ways wxPython doesn't (and doesn't need to, since it calls the OS for drawing most of its controls). pyGame has lots of game related stuff like collision detection, fine-grained control of surfaces and layers or flipping display buffers at a time of your choosing. </p>
<p>That said, graphics-wise you can probably always find a way to do what you want with both toolkits. However, when speed counts or you wish to implement graphically more taxing game ideas than Tetris, you're probably better off with pyGame. If you want to use lots of GUI elements and don't need the fancy graphics and sound functions, you're better off with wxPython.</p>
<p>Portability is not an issue. Both are available for the big three (Linux, OSX, Windows).</p>
<p>It's more a question of what kind of special capabilities you need, really.</p>
| 13 | 2008-12-05T14:53:07Z | [
"python",
"graphics",
"wxpython",
"pygame"
] |
How do I work with multiple git branches of a python module? | 343,517 | <p>I want to use git to allow me to work on several features in a module I'm writing concurrently. I'm currently using SVN, with only one workspace, so I just have the workspace on my PYTHONPATH. I'm realizing this is less than ideal, so I was wondering if anyone could suggest a more 'proper' way of doing this.</p>
<p>Let me elaborate with a hypothetical situation:
I say I have a module 'eggs', with sub-modules 'foo' and 'bar'. Components in 'bar' use code in foo, so eggs/bar/a.py may 'import eggs.foo'. </p>
<p>Say that 'eggs' is in a git repository. I want to try out some changes to 'foo', so I copy it. The problem is that 'import eggs.foo' in eggs/bar finds the original repository in the PYTHONPATH, so it ends up using the old 'foo' instead of my modified one. </p>
<p>How do I set myself up such that each copy of the module uses its own associated 'foo'? Thanks.</p>
<p>edit- Thanks for the pointer to relative imports. I've read up on it and I can see how to apply it. One problem I'd have with using it is that I've built up a fairly large codebase, and I haven't been too neat about it so most modules have a quick 'self-test' under <code>if __name__ == '__main__':</code>, which from what I've read does not play with relative imports: </p>
<ul>
<li><p><a href="http://mail.python.org/pipermail/python-list/2006-October/408945.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2006-October/408945.html</a></p></li>
<li><p><a href="http://www.velocityreviews.com/forums/t502905-relative-import-broken.html" rel="nofollow">http://www.velocityreviews.com/forums/t502905-relative-import-broken.html</a></p></li>
</ul>
<p>The other solution I've been able to google up is to deliberately manipulate sys.path, which seems like an even worse hack. Are there any other possibilities?</p>
<p>edit - Thanks for the suggestions. I'd originally misunderstood git branches, so as pointed out branches are exactly what I want. Nonetheless, I hadn't heard of relative imports before so thanks for that as well. I've learnt something new and may incorporate its use.</p>
| 2 | 2008-12-05T11:06:01Z | 343,534 | <p><a href="http://www.python.org/doc/2.5.2/tut/node8.html#SECTION008420000000000000000" rel="nofollow">Relative imports</a> (<a href="http://www.python.org/dev/peps/pep-0328/" rel="nofollow">PEP 328</a>) might help:</p>
<pre><code>eggs/
__init__.py
foo.py
bar.py
# foo.py
from __future__ import absolute_import
from . import bar
</code></pre>
<p>See <a href="http://stackoverflow.com/questions/171785/how-do-you-organize-python-modules">How do you organize Python modules?</a> for other options.</p>
<p>EDIT:</p>
<p>Yet another option is to use S.Lott's and Jim's suggestions i.e, restructure your package to factor out a <code>eggs.foo</code> part used by <code>eggs.bar.a</code> and use <code>git</code> to work on experimental branches (see <a href="http://book.git-scm.com/" rel="nofollow">Git Community Book</a>).</p>
<p>Here's an example:</p>
<pre><code>$ git status
# On branch master
nothing to commit (working directory clean)
</code></pre>
<p>[just to make sure that all is good]</p>
<pre><code>$ git checkout -b experimental
Switched to a new branch "experimental"
</code></pre>
<p>[work on experimental stuff]</p>
<pre><code>$ git commit -a
</code></pre>
<p>[commit to experimental branch]</p>
<pre><code>$ git checkout master
Switched to branch "master"
</code></pre>
<p>[work on master branch]</p>
<pre><code>$ git commit -a
</code></pre>
<p>To merge changes into master branch: </p>
<pre><code>$ git merge experimental
</code></pre>
<p>See chapter <a href="http://book.git-scm.com/3_basic_branching_and_merging.html" rel="nofollow">Basic Branching and Merging</a> from the above book.</p>
| 3 | 2008-12-05T11:14:00Z | [
"python",
"git",
"module"
] |
How do I work with multiple git branches of a python module? | 343,517 | <p>I want to use git to allow me to work on several features in a module I'm writing concurrently. I'm currently using SVN, with only one workspace, so I just have the workspace on my PYTHONPATH. I'm realizing this is less than ideal, so I was wondering if anyone could suggest a more 'proper' way of doing this.</p>
<p>Let me elaborate with a hypothetical situation:
I say I have a module 'eggs', with sub-modules 'foo' and 'bar'. Components in 'bar' use code in foo, so eggs/bar/a.py may 'import eggs.foo'. </p>
<p>Say that 'eggs' is in a git repository. I want to try out some changes to 'foo', so I copy it. The problem is that 'import eggs.foo' in eggs/bar finds the original repository in the PYTHONPATH, so it ends up using the old 'foo' instead of my modified one. </p>
<p>How do I set myself up such that each copy of the module uses its own associated 'foo'? Thanks.</p>
<p>edit- Thanks for the pointer to relative imports. I've read up on it and I can see how to apply it. One problem I'd have with using it is that I've built up a fairly large codebase, and I haven't been too neat about it so most modules have a quick 'self-test' under <code>if __name__ == '__main__':</code>, which from what I've read does not play with relative imports: </p>
<ul>
<li><p><a href="http://mail.python.org/pipermail/python-list/2006-October/408945.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2006-October/408945.html</a></p></li>
<li><p><a href="http://www.velocityreviews.com/forums/t502905-relative-import-broken.html" rel="nofollow">http://www.velocityreviews.com/forums/t502905-relative-import-broken.html</a></p></li>
</ul>
<p>The other solution I've been able to google up is to deliberately manipulate sys.path, which seems like an even worse hack. Are there any other possibilities?</p>
<p>edit - Thanks for the suggestions. I'd originally misunderstood git branches, so as pointed out branches are exactly what I want. Nonetheless, I hadn't heard of relative imports before so thanks for that as well. I've learnt something new and may incorporate its use.</p>
| 2 | 2008-12-05T11:06:01Z | 343,614 | <p>"say I have a module 'eggs', with sub-modules 'foo' and 'bar'. Components in 'bar' use code in foo, so eggs/bar/a.py may 'import eggs.foo'."</p>
<p>This may not be the best structure. I suggest you have some other modules struggling to get out.</p>
<p>You have <code>eggs.bar.a</code> depending on <code>eggs.foo</code>. I'm guessing other stuff on <code>eggs</code> depends on <code>eggs.foo</code>. Further, I suspect that <code>eggs.foo</code> could be partitioned into <code>eggs.foo</code> and <code>eggs.quux</code> and things might be simpler.</p>
<p>I'd recommend refactoring this to get a better structure. The <code>PYTHONPATH</code> issues are symptomatic of too many things in the wrong places in the module tree.</p>
| 1 | 2008-12-05T11:56:56Z | [
"python",
"git",
"module"
] |
How do I work with multiple git branches of a python module? | 343,517 | <p>I want to use git to allow me to work on several features in a module I'm writing concurrently. I'm currently using SVN, with only one workspace, so I just have the workspace on my PYTHONPATH. I'm realizing this is less than ideal, so I was wondering if anyone could suggest a more 'proper' way of doing this.</p>
<p>Let me elaborate with a hypothetical situation:
I say I have a module 'eggs', with sub-modules 'foo' and 'bar'. Components in 'bar' use code in foo, so eggs/bar/a.py may 'import eggs.foo'. </p>
<p>Say that 'eggs' is in a git repository. I want to try out some changes to 'foo', so I copy it. The problem is that 'import eggs.foo' in eggs/bar finds the original repository in the PYTHONPATH, so it ends up using the old 'foo' instead of my modified one. </p>
<p>How do I set myself up such that each copy of the module uses its own associated 'foo'? Thanks.</p>
<p>edit- Thanks for the pointer to relative imports. I've read up on it and I can see how to apply it. One problem I'd have with using it is that I've built up a fairly large codebase, and I haven't been too neat about it so most modules have a quick 'self-test' under <code>if __name__ == '__main__':</code>, which from what I've read does not play with relative imports: </p>
<ul>
<li><p><a href="http://mail.python.org/pipermail/python-list/2006-October/408945.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2006-October/408945.html</a></p></li>
<li><p><a href="http://www.velocityreviews.com/forums/t502905-relative-import-broken.html" rel="nofollow">http://www.velocityreviews.com/forums/t502905-relative-import-broken.html</a></p></li>
</ul>
<p>The other solution I've been able to google up is to deliberately manipulate sys.path, which seems like an even worse hack. Are there any other possibilities?</p>
<p>edit - Thanks for the suggestions. I'd originally misunderstood git branches, so as pointed out branches are exactly what I want. Nonetheless, I hadn't heard of relative imports before so thanks for that as well. I've learnt something new and may incorporate its use.</p>
| 2 | 2008-12-05T11:06:01Z | 344,013 | <p>Maybe I'm not understanding correctly, but it seems that git would <em>be</em> the solution here, since git's branches don't need separate paths.</p>
<p>Create a branch for each working version of your eggs module. Then when you checkout that branch, the entire module is changed to a state matching the version of your sub-module. You could then merge what you need back and forth between the branches.</p>
<p>And as S.Lott pointed out, may a little refactoring couldn't hurt either ;)</p>
| 1 | 2008-12-05T14:39:44Z | [
"python",
"git",
"module"
] |
How do I submit a form given only the HTML source? | 343,622 | <p>I would like to be able to submit a form in an <strong>HTML source (string)</strong>. In other words I need at least the ability to generate POST parameters <strong>from a string containing HTML source of the form</strong>. This is needed in unit tests for a Django project. I would like a solution that possibly;</p>
<ul>
<li>Uses only standard Python library and Django.</li>
<li>Allows parameter generation from a specific form if there is more than one form present.</li>
<li>Allows me to change the values before submission.</li>
</ul>
<p>A solution that returns a (Django) form instance from a given form class is best. Because it would allow me to use validation. Ideally it would consume the source (which is a string), a form class, and optionally a form name and return the instance as it was before rendering.</p>
<p>NOTE: I am aware this is not an easy task, and probably the gains would hardly justify the effort needed. But I am just curious about how this can be done, in a practical and reliable way. If possible.</p>
| 0 | 2008-12-05T12:02:54Z | 343,639 | <p>Since the Django test framework does this, I'm not sure what you're asking.</p>
<p>Do you want to test a Django app that has a form?</p>
<ul>
<li>In which case, you need to do an initial GET</li>
<li>followed by the resulting POST</li>
</ul>
<p>Do you want to write (and test) a Django app that submits a form to another site?</p>
<p>Here's how we test Django apps with forms.</p>
<pre><code>class Test_HTML_Change_User( django.test.TestCase ):
fixtures = [ 'auth.json', 'someApp.json' ]
def test_chg_user_1( self ):
self.client.login( username='this', password='this' )
response= self.client.get( "/support/html/user/2/change/" )
self.assertEquals( 200, response.status_code )
self.assertTemplateUsed( response, "someApp/user.html")
def test_chg_user( self ):
self.client.login( username='this', password='this' )
# The truly fussy would redo the test_chg_user_1 test here
response= self.client.post(
"/support/html/user/2/change/",
{'web_services': 'P',
'username':'olduser',
'first_name':'asdf',
'last_name':'asdf',
'email':'[email protected]',
'password1':'passw0rd',
'password2':'passw0rd',} )
self.assertRedirects(response, "/support/html/user/2/" )
response= self.client.get( "/support/html/user/2/" )
self.assertContains( response, "<h2>Users: Details for", status_code=200 )
self.assertContains( response, "olduser" )
self.assertTemplateUsed( response, "someApp/user_detail.html")
</code></pre>
<p>Note - we don't parse the HTML in detail. If it has the right template and has the right response string, it has to be right.</p>
| 2 | 2008-12-05T12:10:32Z | [
"python",
"django",
"testing",
"parsing",
"form-submit"
] |
How do I submit a form given only the HTML source? | 343,622 | <p>I would like to be able to submit a form in an <strong>HTML source (string)</strong>. In other words I need at least the ability to generate POST parameters <strong>from a string containing HTML source of the form</strong>. This is needed in unit tests for a Django project. I would like a solution that possibly;</p>
<ul>
<li>Uses only standard Python library and Django.</li>
<li>Allows parameter generation from a specific form if there is more than one form present.</li>
<li>Allows me to change the values before submission.</li>
</ul>
<p>A solution that returns a (Django) form instance from a given form class is best. Because it would allow me to use validation. Ideally it would consume the source (which is a string), a form class, and optionally a form name and return the instance as it was before rendering.</p>
<p>NOTE: I am aware this is not an easy task, and probably the gains would hardly justify the effort needed. But I am just curious about how this can be done, in a practical and reliable way. If possible.</p>
| 0 | 2008-12-05T12:02:54Z | 343,743 | <p>Check out <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a> or it's wrapper <a href="http://twill.idyll.org/" rel="nofollow">twill</a>. I think it's <a href="http://wwwsearch.sourceforge.net/ClientForm/" rel="nofollow">ClientForm</a> module will work for you.</p>
| 0 | 2008-12-05T12:59:34Z | [
"python",
"django",
"testing",
"parsing",
"form-submit"
] |
How do I submit a form given only the HTML source? | 343,622 | <p>I would like to be able to submit a form in an <strong>HTML source (string)</strong>. In other words I need at least the ability to generate POST parameters <strong>from a string containing HTML source of the form</strong>. This is needed in unit tests for a Django project. I would like a solution that possibly;</p>
<ul>
<li>Uses only standard Python library and Django.</li>
<li>Allows parameter generation from a specific form if there is more than one form present.</li>
<li>Allows me to change the values before submission.</li>
</ul>
<p>A solution that returns a (Django) form instance from a given form class is best. Because it would allow me to use validation. Ideally it would consume the source (which is a string), a form class, and optionally a form name and return the instance as it was before rendering.</p>
<p>NOTE: I am aware this is not an easy task, and probably the gains would hardly justify the effort needed. But I am just curious about how this can be done, in a practical and reliable way. If possible.</p>
| 0 | 2008-12-05T12:02:54Z | 343,794 | <p>It is simple... and hard at the same time.<br />
Disclaimer: I don't know much about Python and nothing at all about Django... So I give general, language agnostic advices...
If one of the above advices doesn't work for you, you might want to do it manually:</p>
<ul>
<li>Load the page with an HTML parser, list the forms.</li>
<li>If the <code>method</code> attribute is POST (case insensitive), get the <code>action</code> attribute to get the URL of the request (can be relative).</li>
<li>In the form, get all <code>input</code> and <code>select</code> tags. The <code>name</code> (or <code>id</code> if no name) attributes are the keys of the request parameters. The <code>value</code> attributes (empty if absent) are the corresponding values.</li>
<li>For <code>select</code>, the value is the one of the selected <code>option</code> or the displayed text is no <code>value</code> attribute.</li>
</ul>
<p>These names and values must be URL encoded in GET requests, but not in POST ones.</p>
<p>HTH.</p>
| 2 | 2008-12-05T13:16:50Z | [
"python",
"django",
"testing",
"parsing",
"form-submit"
] |
How do I submit a form given only the HTML source? | 343,622 | <p>I would like to be able to submit a form in an <strong>HTML source (string)</strong>. In other words I need at least the ability to generate POST parameters <strong>from a string containing HTML source of the form</strong>. This is needed in unit tests for a Django project. I would like a solution that possibly;</p>
<ul>
<li>Uses only standard Python library and Django.</li>
<li>Allows parameter generation from a specific form if there is more than one form present.</li>
<li>Allows me to change the values before submission.</li>
</ul>
<p>A solution that returns a (Django) form instance from a given form class is best. Because it would allow me to use validation. Ideally it would consume the source (which is a string), a form class, and optionally a form name and return the instance as it was before rendering.</p>
<p>NOTE: I am aware this is not an easy task, and probably the gains would hardly justify the effort needed. But I am just curious about how this can be done, in a practical and reliable way. If possible.</p>
| 0 | 2008-12-05T12:02:54Z | 345,334 | <p>You should re-read the <a href="http://docs.djangoproject.com/en/dev/topics/testing/" rel="nofollow">documentation about Django's testing framework</a>, specifically the part about testing views (and forms) with <a href="http://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client" rel="nofollow">the test client</a>.</p>
<p>The test client acts as a simple web browser, and lets you make <code>GET</code> and <code>POST</code> requests to your Django views. You can read the response HTML or get the same <code>Context</code> object the template received. Your <code>Context</code> object should contain the actual <code>forms.Form</code> instance you're looking for.</p>
<p>As an example, if your view at the URL <code>/form/</code> passes the context <code>{'myform': forms.Form()}</code> to the template, you could get to it this way:</p>
<pre><code>from django.test.client import Client
c = Client()
# request the web page:
response = c.get('/form/')
# get the Form object:
form = response.context['myform']
form_data = form.cleaned_data
my_form_data = {} # put your filled-out data in here...
form_data.update(my_form_data)
# submit the form back to the web page:
new_form = forms.Form(form_data)
if new_form.is_valid():
c.post('/form/', new_form.cleaned_data)
</code></pre>
<p>Hopefully that accomplishes what you want, without having to mess with parsing HTML.</p>
<p><strong>Edit</strong>: After I re-read the Django docs about Forms, it turns out that forms are immutable. That's okay, though, just create a new <code>Form</code> instance and submit that; I've changed my code example to match this.</p>
| 4 | 2008-12-05T22:08:09Z | [
"python",
"django",
"testing",
"parsing",
"form-submit"
] |
How to use InterWiki links in moinmoin? | 343,769 | <p>We use a number of diffrent web services in our company, wiki(moinmoin), bugtracker (internally), requestracker (customer connection), subversion. Is there a way to parse the wikipages so that if I write "... in Bug1234 you could ..." Bug1234 woud be renderd as a link to <code>http://mybugtracker/bug1234</code></p>
| 2 | 2008-12-05T13:08:12Z | 343,926 | <p>check out the interwiki page in moinmoin, (most wikis have them) we use trac for example and you can set up different link paths to point to your different web resources. So in our Trac you can go [[SSGWiki:Some Topic]] and it will point to another internal wiki.</p>
| 3 | 2008-12-05T14:06:51Z | [
"python",
"wiki",
"moinmoin"
] |
How to use InterWiki links in moinmoin? | 343,769 | <p>We use a number of diffrent web services in our company, wiki(moinmoin), bugtracker (internally), requestracker (customer connection), subversion. Is there a way to parse the wikipages so that if I write "... in Bug1234 you could ..." Bug1234 woud be renderd as a link to <code>http://mybugtracker/bug1234</code></p>
| 2 | 2008-12-05T13:08:12Z | 412,963 | <p>I finally found the solution.
"Add the site to data/intermap.txt" found at:</p>
<p><a href="http://moinmo.in/MoinMoinQuestions#MoinMoinQuestions.2BAC8-Administration.Howtoaddnewinterwikisites.3F" rel="nofollow">http://moinmo.in/MoinMoinQuestions#MoinMoinQuestions.2BAC8-Administration.Howtoaddnewinterwikisites.3F</a></p>
| -1 | 2009-01-05T12:26:21Z | [
"python",
"wiki",
"moinmoin"
] |
How to use InterWiki links in moinmoin? | 343,769 | <p>We use a number of diffrent web services in our company, wiki(moinmoin), bugtracker (internally), requestracker (customer connection), subversion. Is there a way to parse the wikipages so that if I write "... in Bug1234 you could ..." Bug1234 woud be renderd as a link to <code>http://mybugtracker/bug1234</code></p>
| 2 | 2008-12-05T13:08:12Z | 1,932,862 | <p>add to the file <code>data/intermap.txt</code> (create if not existing, but that should not happen) a line like</p>
<pre><code>wpen http://en.wikipedia.org/wiki/
</code></pre>
<p>so that you can write <code>[[wpen:MoinMoin]]</code> instead of <code>http://en.wikipedia.org/wiki/MoinMoin</code></p>
<p>I also have</p>
<pre><code>wpfr http://fr.wikipedia.org/wiki/
wpde http://de.wikipedia.org/wiki/
</code></pre>
<p>the <code>data/intermap.txt</code> gives also other examples that serve just like bookmarklets in firefox. in your case, using :</p>
<pre><code>tracker http://mybugtracker/
</code></pre>
<p>you would issue <code>[[tracker:bug1234]]</code></p>
| 0 | 2009-12-19T12:58:37Z | [
"python",
"wiki",
"moinmoin"
] |
How to convert from UTM to LatLng in python or Javascript | 343,865 | <p>I have a bunch of files with coordinates in UTM form. For each coordinate I have easting, northing and zone. I need to convert this to LatLng for use with Google Map API to show the information in a map.</p>
<p>I have found some online calculators that does this, but no actual code or libraries. <a href="http://trac.osgeo.org/proj4js/">http://trac.osgeo.org/proj4js/</a> is a projection library for Javascript, but looking at the demo it doesn't include UTM projection.</p>
<p>I am still pretty fresh to the entire GIS domain, so what I want is something ala:</p>
<pre><code>(lat,lng) = transform(easting, northing, zone)
</code></pre>
| 23 | 2008-12-05T13:42:34Z | 343,961 | <p>What I found is the following site: <a href="http://home.hiwaay.net/~taylorc/toolbox/geography/geoutm.html" rel="nofollow">http://home.hiwaay.net/~taylorc/toolbox/geography/geoutm.html</a>
It has a javascript converter, you should check the algorithm there. From the page:</p>
<blockquote>
<p>Programmers: The JavaScript source code in this document may be copied and reused without restriction.</p>
</blockquote>
| 10 | 2008-12-05T14:21:28Z | [
"javascript",
"python",
"gis",
"arcgis-js-api",
"proj4js"
] |
How to convert from UTM to LatLng in python or Javascript | 343,865 | <p>I have a bunch of files with coordinates in UTM form. For each coordinate I have easting, northing and zone. I need to convert this to LatLng for use with Google Map API to show the information in a map.</p>
<p>I have found some online calculators that does this, but no actual code or libraries. <a href="http://trac.osgeo.org/proj4js/">http://trac.osgeo.org/proj4js/</a> is a projection library for Javascript, but looking at the demo it doesn't include UTM projection.</p>
<p>I am still pretty fresh to the entire GIS domain, so what I want is something ala:</p>
<pre><code>(lat,lng) = transform(easting, northing, zone)
</code></pre>
| 23 | 2008-12-05T13:42:34Z | 344,060 | <p>According to this page, UTM is supported by proj4js.</p>
<p><a href="http://trac.osgeo.org/proj4js/wiki/UserGuide#Supportedprojectionclasses">http://trac.osgeo.org/proj4js/wiki/UserGuide#Supportedprojectionclasses</a></p>
<p>You may also want to take a look at <a href="http://gdal.org">GDAL</a>. The gdal library has excellent python support, though it may be a bit overkill if you're only doing projection conversion.</p>
| 8 | 2008-12-05T14:58:52Z | [
"javascript",
"python",
"gis",
"arcgis-js-api",
"proj4js"
] |
How to convert from UTM to LatLng in python or Javascript | 343,865 | <p>I have a bunch of files with coordinates in UTM form. For each coordinate I have easting, northing and zone. I need to convert this to LatLng for use with Google Map API to show the information in a map.</p>
<p>I have found some online calculators that does this, but no actual code or libraries. <a href="http://trac.osgeo.org/proj4js/">http://trac.osgeo.org/proj4js/</a> is a projection library for Javascript, but looking at the demo it doesn't include UTM projection.</p>
<p>I am still pretty fresh to the entire GIS domain, so what I want is something ala:</p>
<pre><code>(lat,lng) = transform(easting, northing, zone)
</code></pre>
| 23 | 2008-12-05T13:42:34Z | 344,083 | <p>I ended up finding java code from IBM that solved it: <a href="http://www.ibm.com/developerworks/java/library/j-coordconvert/index.html">http://www.ibm.com/developerworks/java/library/j-coordconvert/index.html</a></p>
<p>Just for reference, here is my python implementation of the method I needed:</p>
<pre><code>import math
def utmToLatLng(zone, easting, northing, northernHemisphere=True):
if not northernHemisphere:
northing = 10000000 - northing
a = 6378137
e = 0.081819191
e1sq = 0.006739497
k0 = 0.9996
arc = northing / k0
mu = arc / (a * (1 - math.pow(e, 2) / 4.0 - 3 * math.pow(e, 4) / 64.0 - 5 * math.pow(e, 6) / 256.0))
ei = (1 - math.pow((1 - e * e), (1 / 2.0))) / (1 + math.pow((1 - e * e), (1 / 2.0)))
ca = 3 * ei / 2 - 27 * math.pow(ei, 3) / 32.0
cb = 21 * math.pow(ei, 2) / 16 - 55 * math.pow(ei, 4) / 32
cc = 151 * math.pow(ei, 3) / 96
cd = 1097 * math.pow(ei, 4) / 512
phi1 = mu + ca * math.sin(2 * mu) + cb * math.sin(4 * mu) + cc * math.sin(6 * mu) + cd * math.sin(8 * mu)
n0 = a / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (1 / 2.0))
r0 = a * (1 - e * e) / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (3 / 2.0))
fact1 = n0 * math.tan(phi1) / r0
_a1 = 500000 - easting
dd0 = _a1 / (n0 * k0)
fact2 = dd0 * dd0 / 2
t0 = math.pow(math.tan(phi1), 2)
Q0 = e1sq * math.pow(math.cos(phi1), 2)
fact3 = (5 + 3 * t0 + 10 * Q0 - 4 * Q0 * Q0 - 9 * e1sq) * math.pow(dd0, 4) / 24
fact4 = (61 + 90 * t0 + 298 * Q0 + 45 * t0 * t0 - 252 * e1sq - 3 * Q0 * Q0) * math.pow(dd0, 6) / 720
lof1 = _a1 / (n0 * k0)
lof2 = (1 + 2 * t0 + Q0) * math.pow(dd0, 3) / 6.0
lof3 = (5 - 2 * Q0 + 28 * t0 - 3 * math.pow(Q0, 2) + 8 * e1sq + 24 * math.pow(t0, 2)) * math.pow(dd0, 5) / 120
_a2 = (lof1 - lof2 + lof3) / math.cos(phi1)
_a3 = _a2 * 180 / math.pi
latitude = 180 * (phi1 - fact1 * (fact2 + fact3 + fact4)) / math.pi
if not northernHemisphere:
latitude = -latitude
longitude = ((zone > 0) and (6 * zone - 183.0) or 3.0) - _a3
return (latitude, longitude)
</code></pre>
<p>And here I thought it was something simple like easting*x+zone*y or something.</p>
| 31 | 2008-12-05T15:04:59Z | [
"javascript",
"python",
"gis",
"arcgis-js-api",
"proj4js"
] |
How to convert from UTM to LatLng in python or Javascript | 343,865 | <p>I have a bunch of files with coordinates in UTM form. For each coordinate I have easting, northing and zone. I need to convert this to LatLng for use with Google Map API to show the information in a map.</p>
<p>I have found some online calculators that does this, but no actual code or libraries. <a href="http://trac.osgeo.org/proj4js/">http://trac.osgeo.org/proj4js/</a> is a projection library for Javascript, but looking at the demo it doesn't include UTM projection.</p>
<p>I am still pretty fresh to the entire GIS domain, so what I want is something ala:</p>
<pre><code>(lat,lng) = transform(easting, northing, zone)
</code></pre>
| 23 | 2008-12-05T13:42:34Z | 1,092,232 | <p>There is a perl module via CPAN called Geography::NationalGrid which can convert easting/northing to lat/longs. That may help.</p>
<p>Alternatively there are lots of scripts on the <a href="http://www.movable-type.co.uk/scripts/latlong-gridref.html" rel="nofollow">movable-type site</a> that let you convert lat/long and easting/northings.</p>
| 0 | 2009-07-07T13:04:24Z | [
"javascript",
"python",
"gis",
"arcgis-js-api",
"proj4js"
] |
How to convert from UTM to LatLng in python or Javascript | 343,865 | <p>I have a bunch of files with coordinates in UTM form. For each coordinate I have easting, northing and zone. I need to convert this to LatLng for use with Google Map API to show the information in a map.</p>
<p>I have found some online calculators that does this, but no actual code or libraries. <a href="http://trac.osgeo.org/proj4js/">http://trac.osgeo.org/proj4js/</a> is a projection library for Javascript, but looking at the demo it doesn't include UTM projection.</p>
<p>I am still pretty fresh to the entire GIS domain, so what I want is something ala:</p>
<pre><code>(lat,lng) = transform(easting, northing, zone)
</code></pre>
| 23 | 2008-12-05T13:42:34Z | 6,734,087 | <pre class="lang-js prettyprint-override"><code>////////////////////////////////////////////////////////////////////////////////////////////
//
// ToLL - function to compute Latitude and Longitude given UTM Northing and Easting in meters
//
// Description:
// This member function converts input north and east coordinates
// to the corresponding Northing and Easting values relative to the defined
// UTM zone. Refer to the reference in this file's header.
//
// Parameters:
// north - (i) Northing (meters)
// east - (i) Easting (meters)
// utmZone - (i) UTM Zone of the North and East parameters
// lat - (o) Latitude in degrees
// lon - (o) Longitude in degrees
//
function ToLL(north,east,utmZone)
{
// This is the lambda knot value in the reference
var LngOrigin = DegToRad(utmZone * 6 - 183)
// The following set of class constants define characteristics of the
// ellipsoid, as defined my the WGS84 datum. These values need to be
// changed if a different dataum is used.
var FalseNorth = 0. // South or North?
//if (lat < 0.) FalseNorth = 10000000. // South or North?
//else FalseNorth = 0.
var Ecc = 0.081819190842622 // Eccentricity
var EccSq = Ecc * Ecc
var Ecc2Sq = EccSq / (1. - EccSq)
var Ecc2 = Math.sqrt(Ecc2Sq) // Secondary eccentricity
var E1 = ( 1 - Math.sqrt(1-EccSq) ) / ( 1 + Math.sqrt(1-EccSq) )
var E12 = E1 * E1
var E13 = E12 * E1
var E14 = E13 * E1
var SemiMajor = 6378137.0 // Ellipsoidal semi-major axis (Meters)
var FalseEast = 500000.0 // UTM East bias (Meters)
var ScaleFactor = 0.9996 // Scale at natural origin
// Calculate the Cassini projection parameters
var M1 = (north - FalseNorth) / ScaleFactor
var Mu1 = M1 / ( SemiMajor * (1 - EccSq/4.0 - 3.0*EccSq*EccSq/64.0 -
5.0*EccSq*EccSq*EccSq/256.0) )
var Phi1 = Mu1 + (3.0*E1/2.0 - 27.0*E13/32.0) * Math.sin(2.0*Mu1)
+ (21.0*E12/16.0 - 55.0*E14/32.0) * Math.sin(4.0*Mu1)
+ (151.0*E13/96.0) * Math.sin(6.0*Mu1)
+ (1097.0*E14/512.0) * Math.sin(8.0*Mu1)
var sin2phi1 = Math.sin(Phi1) * Math.sin(Phi1)
var Rho1 = (SemiMajor * (1.0-EccSq) ) / Math.pow(1.0-EccSq*sin2phi1,1.5)
var Nu1 = SemiMajor / Math.sqrt(1.0-EccSq*sin2phi1)
// Compute parameters as defined in the POSC specification. T, C and D
var T1 = Math.tan(Phi1) * Math.tan(Phi1)
var T12 = T1 * T1
var C1 = Ecc2Sq * Math.cos(Phi1) * Math.cos(Phi1)
var C12 = C1 * C1
var D = (east - FalseEast) / (ScaleFactor * Nu1)
var D2 = D * D
var D3 = D2 * D
var D4 = D3 * D
var D5 = D4 * D
var D6 = D5 * D
// Compute the Latitude and Longitude and convert to degrees
var lat = Phi1 - Nu1*Math.tan(Phi1)/Rho1 *
( D2/2.0 - (5.0 + 3.0*T1 + 10.0*C1 - 4.0*C12 - 9.0*Ecc2Sq)*D4/24.0
+ (61.0 + 90.0*T1 + 298.0*C1 + 45.0*T12 - 252.0*Ecc2Sq - 3.0*C12)*D6/720.0 )
lat = RadToDeg(lat)
var lon = LngOrigin +
( D - (1.0 + 2.0*T1 + C1)*D3/6.0
+ (5.0 - 2.0*C1 + 28.0*T1 - 3.0*C12 + 8.0*Ecc2Sq + 24.0*T12)*D5/120.0) / Math.cos(Phi1)
lon = RadToDeg(lon)
// Create a object to store the calculated Latitude and Longitude values
var sendLatLon = new PC_LatLon(lat,lon)
// Returns a PC_LatLon object
return sendLatLon
}
////////////////////////////////////////////////////////////////////////////////////////////
//
// RadToDeg - function that inputs a value in radians and returns a value in degrees
//
function RadToDeg(value)
{
return ( value * 180.0 / Math.PI )
}
////////////////////////////////////////////////////////////////////////////////////////////
//
// PC_LatLon - this psuedo class is used to store lat/lon values computed by the ToLL
// function.
//
function PC_LatLon(inLat,inLon)
{
this.lat = inLat // Store Latitude in decimal degrees
this.lon = inLon // Store Longitude in decimal degrees
}
</code></pre>
| 1 | 2011-07-18T14:00:41Z | [
"javascript",
"python",
"gis",
"arcgis-js-api",
"proj4js"
] |
How to convert from UTM to LatLng in python or Javascript | 343,865 | <p>I have a bunch of files with coordinates in UTM form. For each coordinate I have easting, northing and zone. I need to convert this to LatLng for use with Google Map API to show the information in a map.</p>
<p>I have found some online calculators that does this, but no actual code or libraries. <a href="http://trac.osgeo.org/proj4js/">http://trac.osgeo.org/proj4js/</a> is a projection library for Javascript, but looking at the demo it doesn't include UTM projection.</p>
<p>I am still pretty fresh to the entire GIS domain, so what I want is something ala:</p>
<pre><code>(lat,lng) = transform(easting, northing, zone)
</code></pre>
| 23 | 2008-12-05T13:42:34Z | 10,239,676 | <p>I'm new to this as well and have been studying up on the subject recently.</p>
<p>Here's a method I found using the python <a href="http://pypi.python.org/pypi/GDAL" rel="nofollow">gdal</a> pacakge (the <em>osr</em> package is included in gdal). The gdal package is pretty powerful, but the documentation could be better. </p>
<p>This is derived from a discussion here:
<a href="http://www.mail-archive.com/[email protected]/msg12398.html" rel="nofollow">http://www.mail-archive.com/[email protected]/msg12398.html</a></p>
<pre><code>import osr
def transform_utm_to_wgs84(easting, northing, zone):
utm_coordinate_system = osr.SpatialReference()
utm_coordinate_system.SetWellKnownGeogCS("WGS84") # Set geographic coordinate system to handle lat/lon
is_northern = northing > 0
utm_coordinate_system.SetUTM(zone, is_northern)
wgs84_coordinate_system = utm_coordinate_system.CloneGeogCS() # Clone ONLY the geographic coordinate system
# create transform component
utm_to_wgs84_transform = osr.CoordinateTransformation(utm_coordinate_system, wgs84_coordinate_system) # (<from>, <to>)
return utm_to_wgs84_transform.TransformPoint(easting, northing, 0) # returns lon, lat, altitude
</code></pre>
<p>And here's the method for converting from a lat, lon in wgs84 (what most gps units report) to utm:</p>
<pre><code>def transform_wgs84_to_utm(lon, lat):
def get_utm_zone(longitude):
return (int(1+(longitude+180.0)/6.0))
def is_northern(latitude):
"""
Determines if given latitude is a northern for UTM
"""
if (latitude < 0.0):
return 0
else:
return 1
utm_coordinate_system = osr.SpatialReference()
utm_coordinate_system.SetWellKnownGeogCS("WGS84") # Set geographic coordinate system to handle lat/lon
utm_coordinate_system.SetUTM(get_utm_zone(lon), is_northern(lat))
wgs84_coordinate_system = utm_coordinate_system.CloneGeogCS() # Clone ONLY the geographic coordinate system
# create transform component
wgs84_to_utm_transform = osr.CoordinateTransformation(wgs84_coordinate_system, utm_coordinate_system) # (<from>, <to>)
return wgs84_to_utm_transform.TransformPoint(lon, lat, 0) # returns easting, northing, altitude
</code></pre>
<p>I also found that if you've already got django/gdal installed and you know the <a href="http://reference.mapinfo.com/common/docs/mapxtend-dev-web-none-eng/miaware/doc/guide/xmlapi/coordsys/systems.htm" rel="nofollow">EPSG</a> code for the UTM zone you're working on, you can just use the <code>Point()</code> <em>transform()</em> method.</p>
<pre><code>from django.contrib.gis.geos import Point
utm2epsg = {"54N": 3185, ...}
p = Point(lon, lat, srid=4326) # 4326 = WGS84 epsg code
p.transform(utm2epsg["54N"])
</code></pre>
| 5 | 2012-04-20T03:01:42Z | [
"javascript",
"python",
"gis",
"arcgis-js-api",
"proj4js"
] |
How to convert from UTM to LatLng in python or Javascript | 343,865 | <p>I have a bunch of files with coordinates in UTM form. For each coordinate I have easting, northing and zone. I need to convert this to LatLng for use with Google Map API to show the information in a map.</p>
<p>I have found some online calculators that does this, but no actual code or libraries. <a href="http://trac.osgeo.org/proj4js/">http://trac.osgeo.org/proj4js/</a> is a projection library for Javascript, but looking at the demo it doesn't include UTM projection.</p>
<p>I am still pretty fresh to the entire GIS domain, so what I want is something ala:</p>
<pre><code>(lat,lng) = transform(easting, northing, zone)
</code></pre>
| 23 | 2008-12-05T13:42:34Z | 18,621,253 | <p>You could use Proj4js, as follows.</p>
<p>Download Proj4JS from GitHub, using <a href="https://github.com/proj4js/proj4js" rel="nofollow">this</a> link.</p>
<p>The following code will convert from UTM to longitude latitude</p>
<pre><code><html>
<head>
<script src="proj4.js"></script>
<script>
var utm = "+proj=utm +zone=32";
var wgs84 = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs";
console.log(proj4(utm,wgs84,[539884, 4942158]));
</script>
</head>
<body>
</body>
</html>
</code></pre>
<p>In this code, the UTM zone is 32, as should be obvious. The Easting is 539884, and the Northing is 4942158. The result is:</p>
<pre><code>[9.502832656648073, 44.631671014204365]
</code></pre>
<p>Which is to say 44.631671014204365N, 9.502832656648073E. Which I have <a href="http://www.rcn.montana.edu/resources/tools/coordinates.aspx?nav=11&c=UTM&md=83&mdt=NAD83/WGS84&z=32&e=539884&n=4942158&h=N" rel="nofollow">verified</a> is correct.</p>
<p>If you need other projections, you can find their strings <a href="http://spatialreference.org/ref/epsg/4326/" rel="nofollow">here</a>.</p>
| 4 | 2013-09-04T18:30:40Z | [
"javascript",
"python",
"gis",
"arcgis-js-api",
"proj4js"
] |
How to convert from UTM to LatLng in python or Javascript | 343,865 | <p>I have a bunch of files with coordinates in UTM form. For each coordinate I have easting, northing and zone. I need to convert this to LatLng for use with Google Map API to show the information in a map.</p>
<p>I have found some online calculators that does this, but no actual code or libraries. <a href="http://trac.osgeo.org/proj4js/">http://trac.osgeo.org/proj4js/</a> is a projection library for Javascript, but looking at the demo it doesn't include UTM projection.</p>
<p>I am still pretty fresh to the entire GIS domain, so what I want is something ala:</p>
<pre><code>(lat,lng) = transform(easting, northing, zone)
</code></pre>
| 23 | 2008-12-05T13:42:34Z | 27,388,998 | <p>A Javascript version of Staale answer</p>
<pre><code>function utmToLatLng(zone, easting, northing, northernHemisphere){
if (!northernHemisphere){
northing = 10000000 - northing;
}
var a = 6378137;
var e = 0.081819191;
var e1sq = 0.006739497;
var k0 = 0.9996;
var arc = northing / k0;
var mu = arc / (a * (1 - Math.pow(e, 2) / 4.0 - 3 * Math.pow(e, 4) / 64.0 - 5 * Math.pow(e, 6) / 256.0));
var ei = (1 - Math.pow((1 - e * e), (1 / 2.0))) / (1 + Math.pow((1 - e * e), (1 / 2.0)));
var ca = 3 * ei / 2 - 27 * Math.pow(ei, 3) / 32.0;
var cb = 21 * Math.pow(ei, 2) / 16 - 55 * Math.pow(ei, 4) / 32;
var cc = 151 * Math.pow(ei, 3) / 96;
var cd = 1097 * Math.pow(ei, 4) / 512;
var phi1 = mu + ca * Math.sin(2 * mu) + cb * Math.sin(4 * mu) + cc * Math.sin(6 * mu) + cd * Math.sin(8 * mu);
var n0 = a / Math.pow((1 - Math.pow((e * Math.sin(phi1)), 2)), (1 / 2.0));
var r0 = a * (1 - e * e) / Math.pow((1 - Math.pow((e * Math.sin(phi1)), 2)), (3 / 2.0));
var fact1 = n0 * Math.tan(phi1) / r0;
var _a1 = 500000 - easting;
var dd0 = _a1 / (n0 * k0);
var fact2 = dd0 * dd0 / 2;
var t0 = Math.pow(Math.tan(phi1), 2);
var Q0 = e1sq * Math.pow(Math.cos(phi1), 2);
var fact3 = (5 + 3 * t0 + 10 * Q0 - 4 * Q0 * Q0 - 9 * e1sq) * Math.pow(dd0, 4) / 24;
var fact4 = (61 + 90 * t0 + 298 * Q0 + 45 * t0 * t0 - 252 * e1sq - 3 * Q0 * Q0) * Math.pow(dd0, 6) / 720;
var lof1 = _a1 / (n0 * k0);
var lof2 = (1 + 2 * t0 + Q0) * Math.pow(dd0, 3) / 6.0;
var lof3 = (5 - 2 * Q0 + 28 * t0 - 3 * Math.pow(Q0, 2) + 8 * e1sq + 24 * Math.pow(t0, 2)) * Math.pow(dd0, 5) / 120;
var _a2 = (lof1 - lof2 + lof3) / Math.cos(phi1);
var _a3 = _a2 * 180 / Math.PI;
var latitude = 180 * (phi1 - fact1 * (fact2 + fact3 + fact4)) / Math.PI;
if (!northernHemisphere){
latitude = -latitude;
}
var longitude = ((zone > 0) && (6 * zone - 183.0) || 3.0) - _a3;
var obj = {
latitude : latitude,
longitude: longitude
};
return obj;
}
</code></pre>
| 1 | 2014-12-09T21:17:17Z | [
"javascript",
"python",
"gis",
"arcgis-js-api",
"proj4js"
] |
How to convert from UTM to LatLng in python or Javascript | 343,865 | <p>I have a bunch of files with coordinates in UTM form. For each coordinate I have easting, northing and zone. I need to convert this to LatLng for use with Google Map API to show the information in a map.</p>
<p>I have found some online calculators that does this, but no actual code or libraries. <a href="http://trac.osgeo.org/proj4js/">http://trac.osgeo.org/proj4js/</a> is a projection library for Javascript, but looking at the demo it doesn't include UTM projection.</p>
<p>I am still pretty fresh to the entire GIS domain, so what I want is something ala:</p>
<pre><code>(lat,lng) = transform(easting, northing, zone)
</code></pre>
| 23 | 2008-12-05T13:42:34Z | 27,581,360 | <p>One problem I had with using proj4js was that it needed the exact zone as @Richard points out. I found a great resource <a href="http://home.hiwaay.net/~taylorc/toolbox/geography/geoutm.html" rel="nofollow">here</a> which can convert WGS to UTM and wrote a cleaner wrapper in JavaScript:</p>
<p><a href="https://github.com/urbanetic/utm-converter" rel="nofollow">https://github.com/urbanetic/utm-converter</a></p>
| 0 | 2014-12-20T14:55:26Z | [
"javascript",
"python",
"gis",
"arcgis-js-api",
"proj4js"
] |
Notification Library for Windows | 344,442 | <p>I'm developing a small tray-icon application for Windows and I need to display non-intrusive visual notifications similar to those that appear when you receive a new message in MSN Messenger or any other IM application.</p>
<p>I have looked at <a href="http://www.fullphat.net/index.php">Snarl</a>, but it seems to be a separate application that I need to install. I want something that could be bundled with my application in one installer, a library.</p>
<p>Which one do you recommend?</p>
<p>Python support is a huge plus.</p>
| 6 | 2008-12-05T16:41:40Z | 344,600 | <p>I wrote one for .NET for the Genghis project (<a href="http://www.codeplex.com/genghis" rel="nofollow">link here</a>) a while back. Looks like it is over at MS CodePlex now. Look for the "AniForm" class. <a href="http://www.sellsbrothers.com/tools/genghis/screenshots/AniForm.JPG" rel="nofollow">Here</a> is a screenshot.</p>
<p>It has more of an older MSN Messenger look and feel but should get you started.</p>
| 2 | 2008-12-05T17:28:54Z | [
"python",
"windows",
"notifications"
] |
Notification Library for Windows | 344,442 | <p>I'm developing a small tray-icon application for Windows and I need to display non-intrusive visual notifications similar to those that appear when you receive a new message in MSN Messenger or any other IM application.</p>
<p>I have looked at <a href="http://www.fullphat.net/index.php">Snarl</a>, but it seems to be a separate application that I need to install. I want something that could be bundled with my application in one installer, a library.</p>
<p>Which one do you recommend?</p>
<p>Python support is a huge plus.</p>
| 6 | 2008-12-05T16:41:40Z | 344,613 | <p>You don't need anyhting.
Just use toasters windows with Win32 api</p>
| 1 | 2008-12-05T17:35:51Z | [
"python",
"windows",
"notifications"
] |
Notification Library for Windows | 344,442 | <p>I'm developing a small tray-icon application for Windows and I need to display non-intrusive visual notifications similar to those that appear when you receive a new message in MSN Messenger or any other IM application.</p>
<p>I have looked at <a href="http://www.fullphat.net/index.php">Snarl</a>, but it seems to be a separate application that I need to install. I want something that could be bundled with my application in one installer, a library.</p>
<p>Which one do you recommend?</p>
<p>Python support is a huge plus.</p>
| 6 | 2008-12-05T16:41:40Z | 344,649 | <p>Are you developing the application in Python? It depends what GUI toolkit you're using.</p>
<p>If you're using wxPython, you could try <a href="http://xoomer.alice.it/infinity77/main/ToasterBox.html" rel="nofollow">ToasterBox</a>, or the wxPopupWindow.</p>
| 2 | 2008-12-05T17:53:10Z | [
"python",
"windows",
"notifications"
] |
Notification Library for Windows | 344,442 | <p>I'm developing a small tray-icon application for Windows and I need to display non-intrusive visual notifications similar to those that appear when you receive a new message in MSN Messenger or any other IM application.</p>
<p>I have looked at <a href="http://www.fullphat.net/index.php">Snarl</a>, but it seems to be a separate application that I need to install. I want something that could be bundled with my application in one installer, a library.</p>
<p>Which one do you recommend?</p>
<p>Python support is a huge plus.</p>
| 6 | 2008-12-05T16:41:40Z | 349,840 | <p>You can do it by depending on a GUI library.</p>
<p>For example, with PyQt,it is possible :</p>
<ul>
<li><p><a href="http://pyqt.sourceforge.net/Docs/PyQt4/qsystemtrayicon.html" rel="nofollow">PyQt QSystemTrayIcon Documentation</a></p></li>
<li><p><a href="http://qt-project.org/doc/qt-4.8/qsystemtrayicon.html" rel="nofollow">QSystemTrayIcon Class Reference</a></p></li>
<li><p><a href="http://qt-project.org/doc/qt-4.8/desktop-systray.html" rel="nofollow">Example of QSystemTrayIcon</a> (in C++, easy to adapt to python)</p></li>
</ul>
| 3 | 2008-12-08T15:20:50Z | [
"python",
"windows",
"notifications"
] |
What is the most efficient way of extracting information from a large number of xml files in python? | 344,559 | <p>I have a directory full (~10<sup>3</sup>, 10<sup>4</sup>) of XML files from which I need to extract the contents of several fields.
I've tested different xml parsers, and since I don't need to validate the contents (expensive) I was thinking of simply using xml.parsers.expat (the fastest one) to go through the files, one by one to extract the data. </p>
<ol>
<li>Is there a more efficient way? (simple text matching doesn't work)</li>
<li>Do I need to issue a new ParserCreate() for each new file (or string) or can I reuse the same one for every file?</li>
<li>Any caveats?</li>
</ol>
<p>Thanks!</p>
| 3 | 2008-12-05T17:15:37Z | 344,641 | <p>If you know that the XML files are generated using the ever-same algorithm, it might be more efficient to not do any XML parsing at all. E.g. if you know that the data is in lines 3, 4, and 5, you might read through the file line-by-line, and then use regular expressions.</p>
<p>Of course, that approach would fail if the files are not machine-generated, or originate from different generators, or if the generator changes over time. However, I'm optimistic that it <em>would</em> be more efficient.</p>
<p>Whether or not you recycle the parser objects is largely irrelevant. Many more objects will get created, so a single parser object doesn't really count much.</p>
| 1 | 2008-12-05T17:49:00Z | [
"python",
"xml",
"performance",
"large-files",
"expat-parser"
] |
What is the most efficient way of extracting information from a large number of xml files in python? | 344,559 | <p>I have a directory full (~10<sup>3</sup>, 10<sup>4</sup>) of XML files from which I need to extract the contents of several fields.
I've tested different xml parsers, and since I don't need to validate the contents (expensive) I was thinking of simply using xml.parsers.expat (the fastest one) to go through the files, one by one to extract the data. </p>
<ol>
<li>Is there a more efficient way? (simple text matching doesn't work)</li>
<li>Do I need to issue a new ParserCreate() for each new file (or string) or can I reuse the same one for every file?</li>
<li>Any caveats?</li>
</ol>
<p>Thanks!</p>
| 3 | 2008-12-05T17:15:37Z | 344,694 | <p>The quickest way would be to match strings (with, e.g., regular expressions) instead of parsing XML - depending on your XMLs this could actually work.</p>
<p>But the most important thing is this: instead of thinking through several options, just implement them and time them on a small set. This will take roughly the same amount of time, and will give you real numbers do drive you forward.</p>
<p>EDIT:</p>
<ul>
<li>Are the files on a local drive or network drive? Network I/O will kill you here.</li>
<li>The problem parallelizes trivially - you can split the work among several computers (or several processes on a multicore computer).</li>
</ul>
| 3 | 2008-12-05T18:08:02Z | [
"python",
"xml",
"performance",
"large-files",
"expat-parser"
] |
What is the most efficient way of extracting information from a large number of xml files in python? | 344,559 | <p>I have a directory full (~10<sup>3</sup>, 10<sup>4</sup>) of XML files from which I need to extract the contents of several fields.
I've tested different xml parsers, and since I don't need to validate the contents (expensive) I was thinking of simply using xml.parsers.expat (the fastest one) to go through the files, one by one to extract the data. </p>
<ol>
<li>Is there a more efficient way? (simple text matching doesn't work)</li>
<li>Do I need to issue a new ParserCreate() for each new file (or string) or can I reuse the same one for every file?</li>
<li>Any caveats?</li>
</ol>
<p>Thanks!</p>
| 3 | 2008-12-05T17:15:37Z | 345,650 | <p>One thing you didn't indicate is whether or not you're reading the XML into a DOM of some kind. I'm guessing that you're probably not, but on the off chance you are, don't. Use xml.sax instead. Using SAX instead of DOM will get you a significant performance boost.</p>
| 1 | 2008-12-06T00:52:34Z | [
"python",
"xml",
"performance",
"large-files",
"expat-parser"
] |
What is the most efficient way of extracting information from a large number of xml files in python? | 344,559 | <p>I have a directory full (~10<sup>3</sup>, 10<sup>4</sup>) of XML files from which I need to extract the contents of several fields.
I've tested different xml parsers, and since I don't need to validate the contents (expensive) I was thinking of simply using xml.parsers.expat (the fastest one) to go through the files, one by one to extract the data. </p>
<ol>
<li>Is there a more efficient way? (simple text matching doesn't work)</li>
<li>Do I need to issue a new ParserCreate() for each new file (or string) or can I reuse the same one for every file?</li>
<li>Any caveats?</li>
</ol>
<p>Thanks!</p>
| 3 | 2008-12-05T17:15:37Z | 349,472 | <p>Usually, I would suggest using ElementTree's <a href="http://effbot.org/zone/element-iterparse.htm" rel="nofollow"><code>iterparse</code></a>, or for extra-speed, its counterpart from <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a>. Also try to use <a href="http://pypi.python.org/pypi/processing" rel="nofollow">Processing</a> (comes built-in with 2.6) to parallelize.</p>
<p>The important thing about <code>iterparse</code> is that you get the element (sub-)structures as they are parsed.</p>
<pre><code>import xml.etree.cElementTree as ET
xml_it = ET.iterparse("some.xml")
event, elem = xml_it.next()
</code></pre>
<p><code>event</code> will always be the string <code>"end"</code> in this case, but you can also initialize the parser to also tell you about new elements as they are parsed. You don't have any guarantee that all children elements will have been parsed at that point, but the attributes are there, if you are only interested in that.</p>
<p>Another point is that you can stop reading elements from iterator early, i.e. before the whole document has been processed.</p>
<p>If the files are large (are they?), there is a common idiom to keep memory usage constant just as in a streaming parser.</p>
| 4 | 2008-12-08T13:01:56Z | [
"python",
"xml",
"performance",
"large-files",
"expat-parser"
] |
Having problem importing the PIL image library | 344,753 | <p>i am trying to do something with the PIL Image library in django, but i experience some problems.</p>
<p>I do like this:</p>
<p><code>
import Image
</code></p>
<p>And then I do like this</p>
<p><code>
images = map(Image.open, glob.glob(os.path.join(dirpath, '*.thumb.jpg')))
</code></p>
<p>But when i try to run this i get an error and it leeds me to think that its not imported correctly, anybody know?</p>
<p><code>
type object 'Image' has no attribute 'open'
</code></p>
| 0 | 2008-12-05T18:34:25Z | 344,791 | <p>Your example works fine in my machine. I don't know why you're getting that error. PIL documentation say you have to import the library in this way:</p>
<pre><code>from PIL import Image
</code></pre>
<p>You should try that way. As I said, for me works in both ways.</p>
| 0 | 2008-12-05T18:51:53Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Having problem importing the PIL image library | 344,753 | <p>i am trying to do something with the PIL Image library in django, but i experience some problems.</p>
<p>I do like this:</p>
<p><code>
import Image
</code></p>
<p>And then I do like this</p>
<p><code>
images = map(Image.open, glob.glob(os.path.join(dirpath, '*.thumb.jpg')))
</code></p>
<p>But when i try to run this i get an error and it leeds me to think that its not imported correctly, anybody know?</p>
<p><code>
type object 'Image' has no attribute 'open'
</code></p>
| 0 | 2008-12-05T18:34:25Z | 344,805 | <p>The error above happens because your file is called Image.py and you're trying to import yourself. As Manual pointed out, you should import Image from the PIL module, but you'd also need to rename your file so it's <em>not</em> called Image.py.</p>
| 1 | 2008-12-05T19:00:03Z | [
"python",
"django",
"image",
"python-imaging-library"
] |
Looking for input in model design for Django Schools | 344,826 | <p>Today I'm starting a little project to create a Django based school administration program. I'm currently designing the models and their corresponding relationships. Being rather new to Django and relational databases in general, I would like some input.</p>
<p>Before I show you the current model layout, you need to have an idea of what the program is meant to do. Keep in mind that it is my goal for the software to be usable by both individual schools and entire school systems.</p>
<p>Features:
- Create multiple schools<br />
- Track student population per school<br />
- Track student demographics, parent contact info, etc.<br />
- Grade books<br />
- Transcripts<br />
- Track disciplinary record.<br />
- Fees schedules and payment tracking<br />
- Generate reports (student activity, student transcripts, class progress, progress by demographic, payment reports, disciplinary report by student class and demographic)<br />
-- Automated PDF report email to parents for student reports.</p>
<p>Given those feature requirements, here is the model layout that I currently have:
Models</p>
<pre><code>* Person
o ID: char or int
o FirstName: char
o MiddleName: char
o FamilyName: char
o Sex: multiple choice
o Ethnicity: multiple choice
o BirthDate: date
o Email: char
o HomePhone: char
o WordPhone: char
o CellPhone: char
o Address: one-to-one with Location
* Student (inherent Person)
o Classes: one-to-many with Class
o Parents: one-to-many with Parent
o Account: one-to-one with PaymentSchedule
o Tasks: one-to-many with Tasks
o Diciplin: one-to-many with Discipline
* Parent (inherent Person)
o Children: one-to-many with Student
* Teacher (inherent Person)
o Classes: one-to-many with Class
* Location
o Address: char
o Address2: char
o Address3: char
o City: char
o StateProvince: char
o PostalCode: char
o Country: multiple choice
* Course
o Name: char
o Description: text field
o Grade: int
* Class
o School: one-to-one with School
o Course: one-to-one with Course
o Teacher: one-to-one with Teacher
o Students: one-to-many with Student
* School
o ID: char or int
o Name: char
o Location: one-to-one with location
* Tasks
o ID: auto increment
o Type: multiple choice (assignment, test, etc.)
o DateAssigned: date
o DateCompleted: date
o Score: real
o Weight: real
o Class: one-to-one with class
o Student: one-to-one with Student
* Discipline
o ID: auto-increment
o Discription: text-field
o Reaction: text-field
o Students: one-to-many with Student
* PaymentSchedule
o ID: auto-increment
o YearlyCost: real
o PaymentSchedule: multiple choice
o ScholarshipType: multiple choice, None if N/A
o ScholarshipAmount: real, 0 if N/A
o Transactions: one-to-many with Payments
* Payments
o auto-increment
o Amount: real
o Date: date
</code></pre>
<p>If you have ideas on how this could be improved upon, I'd love to year them!</p>
<h1>Update</h1>
<p>I've written the initial models.py code, which is probably in need of much love. If you would like to take a look, or even join the project, check out the link.<br>
<a href="http://bazaar.launchpad.net/~djangoschools/djangoschools/trunk/files" rel="nofollow">http://bazaar.launchpad.net/~djangoschools/djangoschools/trunk/files</a></p>
| 2 | 2008-12-05T19:13:41Z | 344,919 | <p>From a quick look I think that its fairly comprehensive. Perhaps you should allow multiple teachers on a course, and allow reuse of addresses/locations between parents and students.</p>
<p>As a general rule I would say that you should start implementing and then you will find where you need improvement.</p>
| 1 | 2008-12-05T19:51:46Z | [
"python",
"django",
"django-models"
] |
Looking for input in model design for Django Schools | 344,826 | <p>Today I'm starting a little project to create a Django based school administration program. I'm currently designing the models and their corresponding relationships. Being rather new to Django and relational databases in general, I would like some input.</p>
<p>Before I show you the current model layout, you need to have an idea of what the program is meant to do. Keep in mind that it is my goal for the software to be usable by both individual schools and entire school systems.</p>
<p>Features:
- Create multiple schools<br />
- Track student population per school<br />
- Track student demographics, parent contact info, etc.<br />
- Grade books<br />
- Transcripts<br />
- Track disciplinary record.<br />
- Fees schedules and payment tracking<br />
- Generate reports (student activity, student transcripts, class progress, progress by demographic, payment reports, disciplinary report by student class and demographic)<br />
-- Automated PDF report email to parents for student reports.</p>
<p>Given those feature requirements, here is the model layout that I currently have:
Models</p>
<pre><code>* Person
o ID: char or int
o FirstName: char
o MiddleName: char
o FamilyName: char
o Sex: multiple choice
o Ethnicity: multiple choice
o BirthDate: date
o Email: char
o HomePhone: char
o WordPhone: char
o CellPhone: char
o Address: one-to-one with Location
* Student (inherent Person)
o Classes: one-to-many with Class
o Parents: one-to-many with Parent
o Account: one-to-one with PaymentSchedule
o Tasks: one-to-many with Tasks
o Diciplin: one-to-many with Discipline
* Parent (inherent Person)
o Children: one-to-many with Student
* Teacher (inherent Person)
o Classes: one-to-many with Class
* Location
o Address: char
o Address2: char
o Address3: char
o City: char
o StateProvince: char
o PostalCode: char
o Country: multiple choice
* Course
o Name: char
o Description: text field
o Grade: int
* Class
o School: one-to-one with School
o Course: one-to-one with Course
o Teacher: one-to-one with Teacher
o Students: one-to-many with Student
* School
o ID: char or int
o Name: char
o Location: one-to-one with location
* Tasks
o ID: auto increment
o Type: multiple choice (assignment, test, etc.)
o DateAssigned: date
o DateCompleted: date
o Score: real
o Weight: real
o Class: one-to-one with class
o Student: one-to-one with Student
* Discipline
o ID: auto-increment
o Discription: text-field
o Reaction: text-field
o Students: one-to-many with Student
* PaymentSchedule
o ID: auto-increment
o YearlyCost: real
o PaymentSchedule: multiple choice
o ScholarshipType: multiple choice, None if N/A
o ScholarshipAmount: real, 0 if N/A
o Transactions: one-to-many with Payments
* Payments
o auto-increment
o Amount: real
o Date: date
</code></pre>
<p>If you have ideas on how this could be improved upon, I'd love to year them!</p>
<h1>Update</h1>
<p>I've written the initial models.py code, which is probably in need of much love. If you would like to take a look, or even join the project, check out the link.<br>
<a href="http://bazaar.launchpad.net/~djangoschools/djangoschools/trunk/files" rel="nofollow">http://bazaar.launchpad.net/~djangoschools/djangoschools/trunk/files</a></p>
| 2 | 2008-12-05T19:13:41Z | 344,992 | <p>Looks like an interesting project. Do note that Django has higher-level types than SQL, so you can make use of things like the email address type.</p>
<p>If you're planning on targeting <a href="http://code.google.com/appengine/" rel="nofollow">GAE</a>, you should find a similarly rich <a href="http://code.google.com/appengine/docs/datastore/typesandpropertyclasses.html" rel="nofollow">set of model types</a>.</p>
| 0 | 2008-12-05T20:16:53Z | [
"python",
"django",
"django-models"
] |
Looking for input in model design for Django Schools | 344,826 | <p>Today I'm starting a little project to create a Django based school administration program. I'm currently designing the models and their corresponding relationships. Being rather new to Django and relational databases in general, I would like some input.</p>
<p>Before I show you the current model layout, you need to have an idea of what the program is meant to do. Keep in mind that it is my goal for the software to be usable by both individual schools and entire school systems.</p>
<p>Features:
- Create multiple schools<br />
- Track student population per school<br />
- Track student demographics, parent contact info, etc.<br />
- Grade books<br />
- Transcripts<br />
- Track disciplinary record.<br />
- Fees schedules and payment tracking<br />
- Generate reports (student activity, student transcripts, class progress, progress by demographic, payment reports, disciplinary report by student class and demographic)<br />
-- Automated PDF report email to parents for student reports.</p>
<p>Given those feature requirements, here is the model layout that I currently have:
Models</p>
<pre><code>* Person
o ID: char or int
o FirstName: char
o MiddleName: char
o FamilyName: char
o Sex: multiple choice
o Ethnicity: multiple choice
o BirthDate: date
o Email: char
o HomePhone: char
o WordPhone: char
o CellPhone: char
o Address: one-to-one with Location
* Student (inherent Person)
o Classes: one-to-many with Class
o Parents: one-to-many with Parent
o Account: one-to-one with PaymentSchedule
o Tasks: one-to-many with Tasks
o Diciplin: one-to-many with Discipline
* Parent (inherent Person)
o Children: one-to-many with Student
* Teacher (inherent Person)
o Classes: one-to-many with Class
* Location
o Address: char
o Address2: char
o Address3: char
o City: char
o StateProvince: char
o PostalCode: char
o Country: multiple choice
* Course
o Name: char
o Description: text field
o Grade: int
* Class
o School: one-to-one with School
o Course: one-to-one with Course
o Teacher: one-to-one with Teacher
o Students: one-to-many with Student
* School
o ID: char or int
o Name: char
o Location: one-to-one with location
* Tasks
o ID: auto increment
o Type: multiple choice (assignment, test, etc.)
o DateAssigned: date
o DateCompleted: date
o Score: real
o Weight: real
o Class: one-to-one with class
o Student: one-to-one with Student
* Discipline
o ID: auto-increment
o Discription: text-field
o Reaction: text-field
o Students: one-to-many with Student
* PaymentSchedule
o ID: auto-increment
o YearlyCost: real
o PaymentSchedule: multiple choice
o ScholarshipType: multiple choice, None if N/A
o ScholarshipAmount: real, 0 if N/A
o Transactions: one-to-many with Payments
* Payments
o auto-increment
o Amount: real
o Date: date
</code></pre>
<p>If you have ideas on how this could be improved upon, I'd love to year them!</p>
<h1>Update</h1>
<p>I've written the initial models.py code, which is probably in need of much love. If you would like to take a look, or even join the project, check out the link.<br>
<a href="http://bazaar.launchpad.net/~djangoschools/djangoschools/trunk/files" rel="nofollow">http://bazaar.launchpad.net/~djangoschools/djangoschools/trunk/files</a></p>
| 2 | 2008-12-05T19:13:41Z | 344,996 | <p>hey...i agree...it looks pretty good. someone advised me to use auto-increment on all tables just to be sure there really is a unique id on every record. it's your choice if you'd like to go that route.</p>
| 0 | 2008-12-05T20:19:08Z | [
"python",
"django",
"django-models"
] |
Looking for input in model design for Django Schools | 344,826 | <p>Today I'm starting a little project to create a Django based school administration program. I'm currently designing the models and their corresponding relationships. Being rather new to Django and relational databases in general, I would like some input.</p>
<p>Before I show you the current model layout, you need to have an idea of what the program is meant to do. Keep in mind that it is my goal for the software to be usable by both individual schools and entire school systems.</p>
<p>Features:
- Create multiple schools<br />
- Track student population per school<br />
- Track student demographics, parent contact info, etc.<br />
- Grade books<br />
- Transcripts<br />
- Track disciplinary record.<br />
- Fees schedules and payment tracking<br />
- Generate reports (student activity, student transcripts, class progress, progress by demographic, payment reports, disciplinary report by student class and demographic)<br />
-- Automated PDF report email to parents for student reports.</p>
<p>Given those feature requirements, here is the model layout that I currently have:
Models</p>
<pre><code>* Person
o ID: char or int
o FirstName: char
o MiddleName: char
o FamilyName: char
o Sex: multiple choice
o Ethnicity: multiple choice
o BirthDate: date
o Email: char
o HomePhone: char
o WordPhone: char
o CellPhone: char
o Address: one-to-one with Location
* Student (inherent Person)
o Classes: one-to-many with Class
o Parents: one-to-many with Parent
o Account: one-to-one with PaymentSchedule
o Tasks: one-to-many with Tasks
o Diciplin: one-to-many with Discipline
* Parent (inherent Person)
o Children: one-to-many with Student
* Teacher (inherent Person)
o Classes: one-to-many with Class
* Location
o Address: char
o Address2: char
o Address3: char
o City: char
o StateProvince: char
o PostalCode: char
o Country: multiple choice
* Course
o Name: char
o Description: text field
o Grade: int
* Class
o School: one-to-one with School
o Course: one-to-one with Course
o Teacher: one-to-one with Teacher
o Students: one-to-many with Student
* School
o ID: char or int
o Name: char
o Location: one-to-one with location
* Tasks
o ID: auto increment
o Type: multiple choice (assignment, test, etc.)
o DateAssigned: date
o DateCompleted: date
o Score: real
o Weight: real
o Class: one-to-one with class
o Student: one-to-one with Student
* Discipline
o ID: auto-increment
o Discription: text-field
o Reaction: text-field
o Students: one-to-many with Student
* PaymentSchedule
o ID: auto-increment
o YearlyCost: real
o PaymentSchedule: multiple choice
o ScholarshipType: multiple choice, None if N/A
o ScholarshipAmount: real, 0 if N/A
o Transactions: one-to-many with Payments
* Payments
o auto-increment
o Amount: real
o Date: date
</code></pre>
<p>If you have ideas on how this could be improved upon, I'd love to year them!</p>
<h1>Update</h1>
<p>I've written the initial models.py code, which is probably in need of much love. If you would like to take a look, or even join the project, check out the link.<br>
<a href="http://bazaar.launchpad.net/~djangoschools/djangoschools/trunk/files" rel="nofollow">http://bazaar.launchpad.net/~djangoschools/djangoschools/trunk/files</a></p>
| 2 | 2008-12-05T19:13:41Z | 345,053 | <p>You should link paiement (transaction) to the person concerned.</p>
| 0 | 2008-12-05T20:40:28Z | [
"python",
"django",
"django-models"
] |
Looking for input in model design for Django Schools | 344,826 | <p>Today I'm starting a little project to create a Django based school administration program. I'm currently designing the models and their corresponding relationships. Being rather new to Django and relational databases in general, I would like some input.</p>
<p>Before I show you the current model layout, you need to have an idea of what the program is meant to do. Keep in mind that it is my goal for the software to be usable by both individual schools and entire school systems.</p>
<p>Features:
- Create multiple schools<br />
- Track student population per school<br />
- Track student demographics, parent contact info, etc.<br />
- Grade books<br />
- Transcripts<br />
- Track disciplinary record.<br />
- Fees schedules and payment tracking<br />
- Generate reports (student activity, student transcripts, class progress, progress by demographic, payment reports, disciplinary report by student class and demographic)<br />
-- Automated PDF report email to parents for student reports.</p>
<p>Given those feature requirements, here is the model layout that I currently have:
Models</p>
<pre><code>* Person
o ID: char or int
o FirstName: char
o MiddleName: char
o FamilyName: char
o Sex: multiple choice
o Ethnicity: multiple choice
o BirthDate: date
o Email: char
o HomePhone: char
o WordPhone: char
o CellPhone: char
o Address: one-to-one with Location
* Student (inherent Person)
o Classes: one-to-many with Class
o Parents: one-to-many with Parent
o Account: one-to-one with PaymentSchedule
o Tasks: one-to-many with Tasks
o Diciplin: one-to-many with Discipline
* Parent (inherent Person)
o Children: one-to-many with Student
* Teacher (inherent Person)
o Classes: one-to-many with Class
* Location
o Address: char
o Address2: char
o Address3: char
o City: char
o StateProvince: char
o PostalCode: char
o Country: multiple choice
* Course
o Name: char
o Description: text field
o Grade: int
* Class
o School: one-to-one with School
o Course: one-to-one with Course
o Teacher: one-to-one with Teacher
o Students: one-to-many with Student
* School
o ID: char or int
o Name: char
o Location: one-to-one with location
* Tasks
o ID: auto increment
o Type: multiple choice (assignment, test, etc.)
o DateAssigned: date
o DateCompleted: date
o Score: real
o Weight: real
o Class: one-to-one with class
o Student: one-to-one with Student
* Discipline
o ID: auto-increment
o Discription: text-field
o Reaction: text-field
o Students: one-to-many with Student
* PaymentSchedule
o ID: auto-increment
o YearlyCost: real
o PaymentSchedule: multiple choice
o ScholarshipType: multiple choice, None if N/A
o ScholarshipAmount: real, 0 if N/A
o Transactions: one-to-many with Payments
* Payments
o auto-increment
o Amount: real
o Date: date
</code></pre>
<p>If you have ideas on how this could be improved upon, I'd love to year them!</p>
<h1>Update</h1>
<p>I've written the initial models.py code, which is probably in need of much love. If you would like to take a look, or even join the project, check out the link.<br>
<a href="http://bazaar.launchpad.net/~djangoschools/djangoschools/trunk/files" rel="nofollow">http://bazaar.launchpad.net/~djangoschools/djangoschools/trunk/files</a></p>
| 2 | 2008-12-05T19:13:41Z | 345,257 | <p>Some possible issues:</p>
<p>For the location object, what if in the future you need to hold a home address, work address, etc. for a person? Same for email addresses and phone numbers - I would have phone numbers be their own object.</p>
<p>Include an Address_3 on your address object.</p>
| 1 | 2008-12-05T21:41:53Z | [
"python",
"django",
"django-models"
] |
Looking for input in model design for Django Schools | 344,826 | <p>Today I'm starting a little project to create a Django based school administration program. I'm currently designing the models and their corresponding relationships. Being rather new to Django and relational databases in general, I would like some input.</p>
<p>Before I show you the current model layout, you need to have an idea of what the program is meant to do. Keep in mind that it is my goal for the software to be usable by both individual schools and entire school systems.</p>
<p>Features:
- Create multiple schools<br />
- Track student population per school<br />
- Track student demographics, parent contact info, etc.<br />
- Grade books<br />
- Transcripts<br />
- Track disciplinary record.<br />
- Fees schedules and payment tracking<br />
- Generate reports (student activity, student transcripts, class progress, progress by demographic, payment reports, disciplinary report by student class and demographic)<br />
-- Automated PDF report email to parents for student reports.</p>
<p>Given those feature requirements, here is the model layout that I currently have:
Models</p>
<pre><code>* Person
o ID: char or int
o FirstName: char
o MiddleName: char
o FamilyName: char
o Sex: multiple choice
o Ethnicity: multiple choice
o BirthDate: date
o Email: char
o HomePhone: char
o WordPhone: char
o CellPhone: char
o Address: one-to-one with Location
* Student (inherent Person)
o Classes: one-to-many with Class
o Parents: one-to-many with Parent
o Account: one-to-one with PaymentSchedule
o Tasks: one-to-many with Tasks
o Diciplin: one-to-many with Discipline
* Parent (inherent Person)
o Children: one-to-many with Student
* Teacher (inherent Person)
o Classes: one-to-many with Class
* Location
o Address: char
o Address2: char
o Address3: char
o City: char
o StateProvince: char
o PostalCode: char
o Country: multiple choice
* Course
o Name: char
o Description: text field
o Grade: int
* Class
o School: one-to-one with School
o Course: one-to-one with Course
o Teacher: one-to-one with Teacher
o Students: one-to-many with Student
* School
o ID: char or int
o Name: char
o Location: one-to-one with location
* Tasks
o ID: auto increment
o Type: multiple choice (assignment, test, etc.)
o DateAssigned: date
o DateCompleted: date
o Score: real
o Weight: real
o Class: one-to-one with class
o Student: one-to-one with Student
* Discipline
o ID: auto-increment
o Discription: text-field
o Reaction: text-field
o Students: one-to-many with Student
* PaymentSchedule
o ID: auto-increment
o YearlyCost: real
o PaymentSchedule: multiple choice
o ScholarshipType: multiple choice, None if N/A
o ScholarshipAmount: real, 0 if N/A
o Transactions: one-to-many with Payments
* Payments
o auto-increment
o Amount: real
o Date: date
</code></pre>
<p>If you have ideas on how this could be improved upon, I'd love to year them!</p>
<h1>Update</h1>
<p>I've written the initial models.py code, which is probably in need of much love. If you would like to take a look, or even join the project, check out the link.<br>
<a href="http://bazaar.launchpad.net/~djangoschools/djangoschools/trunk/files" rel="nofollow">http://bazaar.launchpad.net/~djangoschools/djangoschools/trunk/files</a></p>
| 2 | 2008-12-05T19:13:41Z | 345,403 | <p>I would advise you to not worry about the underling relational database. Yes, you'll need to understand what a foreign key is and the difference between many-to-many and one-to-many, etc., but you should think about your models in terms of Django classes. That's how you'll have to write them anyway, so that's where I would start. The <a href="http://docs.djangoproject.com/en/dev/topics/db/models/" rel="nofollow">Django documenation on models</a> is great, and will help you a lot.</p>
<p>I think everyone here would be glad to help you with the Python classes; you should rewrite your example using Django. For example, your Person table would look like this:</p>
<pre><code>from django.db import models
SEX_CHOICES = (
('M', 'Male'),
('F', 'Female')
)
ETHNICITY_CHOICES = (
# follow the same format as SEX_CHOICES:
# (database_value, human_friendly_name)
)
class Person(models.Model):
first_name = models.CharField(max_length=200)
middle_name = models.CharField(max_length=200)
familiy_name = models.CharField(max_length=200)
sex = models.CharField(max_length=1, choices=SEX_CHOICES)
ethnicity = models.CharField(max_length=1, choices=ETHNICITY_CHOICES)
birth_date = models.DateField()
email = models.EmailField()
home_phone = models.CharField(max_length=10) # USA phone numbers
work_phone = models.CharField(max_length=10)
cell_phone = models.CharField(max_length=10)
address = models.ForeignKey(Location)
class Location(models.Model):
# left as an exercise for the reader
# more classes...
</code></pre>
| 0 | 2008-12-05T22:33:48Z | [
"python",
"django",
"django-models"
] |
Looking for input in model design for Django Schools | 344,826 | <p>Today I'm starting a little project to create a Django based school administration program. I'm currently designing the models and their corresponding relationships. Being rather new to Django and relational databases in general, I would like some input.</p>
<p>Before I show you the current model layout, you need to have an idea of what the program is meant to do. Keep in mind that it is my goal for the software to be usable by both individual schools and entire school systems.</p>
<p>Features:
- Create multiple schools<br />
- Track student population per school<br />
- Track student demographics, parent contact info, etc.<br />
- Grade books<br />
- Transcripts<br />
- Track disciplinary record.<br />
- Fees schedules and payment tracking<br />
- Generate reports (student activity, student transcripts, class progress, progress by demographic, payment reports, disciplinary report by student class and demographic)<br />
-- Automated PDF report email to parents for student reports.</p>
<p>Given those feature requirements, here is the model layout that I currently have:
Models</p>
<pre><code>* Person
o ID: char or int
o FirstName: char
o MiddleName: char
o FamilyName: char
o Sex: multiple choice
o Ethnicity: multiple choice
o BirthDate: date
o Email: char
o HomePhone: char
o WordPhone: char
o CellPhone: char
o Address: one-to-one with Location
* Student (inherent Person)
o Classes: one-to-many with Class
o Parents: one-to-many with Parent
o Account: one-to-one with PaymentSchedule
o Tasks: one-to-many with Tasks
o Diciplin: one-to-many with Discipline
* Parent (inherent Person)
o Children: one-to-many with Student
* Teacher (inherent Person)
o Classes: one-to-many with Class
* Location
o Address: char
o Address2: char
o Address3: char
o City: char
o StateProvince: char
o PostalCode: char
o Country: multiple choice
* Course
o Name: char
o Description: text field
o Grade: int
* Class
o School: one-to-one with School
o Course: one-to-one with Course
o Teacher: one-to-one with Teacher
o Students: one-to-many with Student
* School
o ID: char or int
o Name: char
o Location: one-to-one with location
* Tasks
o ID: auto increment
o Type: multiple choice (assignment, test, etc.)
o DateAssigned: date
o DateCompleted: date
o Score: real
o Weight: real
o Class: one-to-one with class
o Student: one-to-one with Student
* Discipline
o ID: auto-increment
o Discription: text-field
o Reaction: text-field
o Students: one-to-many with Student
* PaymentSchedule
o ID: auto-increment
o YearlyCost: real
o PaymentSchedule: multiple choice
o ScholarshipType: multiple choice, None if N/A
o ScholarshipAmount: real, 0 if N/A
o Transactions: one-to-many with Payments
* Payments
o auto-increment
o Amount: real
o Date: date
</code></pre>
<p>If you have ideas on how this could be improved upon, I'd love to year them!</p>
<h1>Update</h1>
<p>I've written the initial models.py code, which is probably in need of much love. If you would like to take a look, or even join the project, check out the link.<br>
<a href="http://bazaar.launchpad.net/~djangoschools/djangoschools/trunk/files" rel="nofollow">http://bazaar.launchpad.net/~djangoschools/djangoschools/trunk/files</a></p>
| 2 | 2008-12-05T19:13:41Z | 2,135,038 | <p>A student doesn't have a class. He/She attends a class that has them (in the roster). Here's another way to look at the class situation. (notice the model's name. that's just because I tend not to name anything 'Class' because it's easy to get into name clashes that way.)</p>
<pre><code>class SchoolClass(models.Model):
teacher = models.ManyToManyField(Teacher, related_name='teachers')
student = models.ManyToManyField(Student, related_name='students')
prerequisites = models.ForeignKey('self')
startdate = models.DateField()
enddate = models.DateField()
... and so on ...
</code></pre>
<p>This is more natural because you can have a class with students and take attendance according to the students list, or aggregate grades, student ages, etc. in a natural way.</p>
| 0 | 2010-01-25T19:36:01Z | [
"python",
"django",
"django-models"
] |
Django Admin's "view on site" points to example.com instead of my domain | 344,851 | <p>I added a <code>get_absolute_url</code> function to one of my models.</p>
<pre><code>def get_absolute_url(self):
return '/foo/bar'
</code></pre>
<p>The admin site picks it up and adds a "view on site" link to the detail page for that object (when I put a real URL there instead of "/foo/bar").</p>
<p>The problem is instead of going to <code>http://localhost:8000/foo/bar</code>, it goes to <code>http://example.com/foo/bar</code>.</p>
<p>What am I doing wrong?</p>
| 22 | 2008-12-05T19:23:11Z | 344,909 | <p>You have to change <a href="http://docs.djangoproject.com/en/dev/ref/contrib/sites/#ref-contrib-sites">default site</a> domain value.</p>
| 21 | 2008-12-05T19:46:26Z | [
"python",
"django",
"django-admin"
] |
Django Admin's "view on site" points to example.com instead of my domain | 344,851 | <p>I added a <code>get_absolute_url</code> function to one of my models.</p>
<pre><code>def get_absolute_url(self):
return '/foo/bar'
</code></pre>
<p>The admin site picks it up and adds a "view on site" link to the detail page for that object (when I put a real URL there instead of "/foo/bar").</p>
<p>The problem is instead of going to <code>http://localhost:8000/foo/bar</code>, it goes to <code>http://example.com/foo/bar</code>.</p>
<p>What am I doing wrong?</p>
| 22 | 2008-12-05T19:23:11Z | 374,111 | <p>You can change this in /admin/sites if you have admin enabled.</p>
| 2 | 2008-12-17T09:51:40Z | [
"python",
"django",
"django-admin"
] |
Django Admin's "view on site" points to example.com instead of my domain | 344,851 | <p>I added a <code>get_absolute_url</code> function to one of my models.</p>
<pre><code>def get_absolute_url(self):
return '/foo/bar'
</code></pre>
<p>The admin site picks it up and adds a "view on site" link to the detail page for that object (when I put a real URL there instead of "/foo/bar").</p>
<p>The problem is instead of going to <code>http://localhost:8000/foo/bar</code>, it goes to <code>http://example.com/foo/bar</code>.</p>
<p>What am I doing wrong?</p>
| 22 | 2008-12-05T19:23:11Z | 2,349,374 | <p>The funniest thing is that "example.com" appears in an obvious place. Yet, I was looking for in in an hour or so. </p>
<p>Just use your admin interface -> Sites -> ... there it is :)</p>
| 4 | 2010-02-27T23:30:00Z | [
"python",
"django",
"django-admin"
] |
Django Admin's "view on site" points to example.com instead of my domain | 344,851 | <p>I added a <code>get_absolute_url</code> function to one of my models.</p>
<pre><code>def get_absolute_url(self):
return '/foo/bar'
</code></pre>
<p>The admin site picks it up and adds a "view on site" link to the detail page for that object (when I put a real URL there instead of "/foo/bar").</p>
<p>The problem is instead of going to <code>http://localhost:8000/foo/bar</code>, it goes to <code>http://example.com/foo/bar</code>.</p>
<p>What am I doing wrong?</p>
| 22 | 2008-12-05T19:23:11Z | 11,420,803 | <p>When you have edited a Site instance thought the admin, you need to restart your web server for the change to take effect. I guess this must mean that the database is only read when the web server first starts.</p>
| 1 | 2012-07-10T19:48:26Z | [
"python",
"django",
"django-admin"
] |
Django Admin's "view on site" points to example.com instead of my domain | 344,851 | <p>I added a <code>get_absolute_url</code> function to one of my models.</p>
<pre><code>def get_absolute_url(self):
return '/foo/bar'
</code></pre>
<p>The admin site picks it up and adds a "view on site" link to the detail page for that object (when I put a real URL there instead of "/foo/bar").</p>
<p>The problem is instead of going to <code>http://localhost:8000/foo/bar</code>, it goes to <code>http://example.com/foo/bar</code>.</p>
<p>What am I doing wrong?</p>
| 22 | 2008-12-05T19:23:11Z | 11,420,955 | <p>As others have mentioned, this is to do with the <a href="https://docs.djangoproject.com/en/1.4/ref/contrib/sites/#how-django-uses-the-sites-framework" rel="nofollow">default <code>sites</code> framework</a>.</p>
<p>If you're using <a href="http://south.aeracode.org" rel="nofollow">South</a> for database migrations (probably a good
idea in general), you can <a href="http://codeinthehole.com/writing/a-data-migration-for-every-django-project/" rel="nofollow">use a data migration to avoid having to make this same database change everywhere you deploy your application</a>, along the lines of</p>
<pre><code>from south.v2 import DataMigration
from django.conf import settings
class Migration(DataMigration):
def forwards(self, orm):
Site = orm['sites.Site']
site = Site.objects.get(id=settings.SITE_ID)
site.domain = 'yoursite.com'
site.name = 'yoursite'
site.save()
</code></pre>
| 2 | 2012-07-10T19:58:13Z | [
"python",
"django",
"django-admin"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.