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 |
---|---|---|---|---|---|---|---|---|---|
Django/Python - Grouping objects by common set from a many-to-many relationships | 160,298 | <p>This is a part algorithm-logic question (how to do it), part implementation question (how to do it best!). I'm working with Django, so I thought I'd share with that.</p>
<p>In Python, it's worth mentioning that the problem is somewhat related to <a href="http://stackoverflow.com/questions/773/how-do-i-use-pythons-itertoolsgroupby">how-do-i-use-pythons-itertoolsgroupby</a>.</p>
<p>Suppose you're given two Django Model-derived classes:</p>
<pre><code>from django.db import models
class Car(models.Model):
mods = models.ManyToManyField(Representative)
</code></pre>
<p>and</p>
<pre><code>from django.db import models
class Mods(models.Model):
...
</code></pre>
<p>How does one get a list of Cars, grouped by Cars with a common set of Mods?</p>
<p>I.e. I want to get a class likeso:</p>
<pre><code>Cars_by_common_mods = [
{ mods: { 'a' }, cars: { 'W1', 'W2' } },
{ mods: { 'a', 'b' }, cars: { 'X1', 'X2', 'X3' }, },
{ mods: { 'b' }, cars: { 'Y1', 'Y2' } },
{ mods: { 'a', 'b', 'c' }, cars: { 'Z1' } },
]
</code></pre>
<p>I've been thinking of something like:</p>
<pre><code>def cars_by_common_mods():
cars = Cars.objects.all()
mod_list = []
for car in cars:
mod_list.append( { 'car': car, 'mods': list(car.mods.all()) }
ret = []
for key, mods_group in groupby(list(mods), lambda x: set(x.mods)):
ret.append(mods_group)
return ret
</code></pre>
<p>However, that doesn't work because (perhaps among other reasons) the groupby doesn't seem to group by the mods sets. I guess the mod_list has to be sorted to work with groupby. All to say, I'm confident there's something simple and elegant out there that will be both enlightening and illuminating.</p>
<p><em>Cheers & thanks!</em></p>
| 5 | 2008-10-01T23:59:52Z | 161,227 | <p>You have a few problems here.</p>
<p>You didn't sort your list before calling groupby, and this is required. From <a href="http://www.python.org/doc/2.5/lib/itertools-functions.html" rel="nofollow">itertools documentation</a>:</p>
<blockquote>
<p>Generally, the iterable needs to already be sorted on the same key function.</p>
</blockquote>
<p>Then, you don't duplicate the list returned by groupby. Again, documentation states:</p>
<blockquote>
<p>The returned group is itself an iterator that shares the underlying iterable with
groupby(). Because the source is shared, when the groupby object is advanced, the
previous group is no longer visible. So, if that data is needed later, it should
be stored as a list:</p>
<pre><code>groups = []
uniquekeys = []
for k, g in groupby(data, keyfunc):
groups.append(list(g)) # Store group iterator as a list
uniquekeys.append(k)
</code></pre>
</blockquote>
<p>And final mistake is using sets as keys. They don't work here. A quick fix is to cast them to sorted tuples (there could be a better solution, but I cannot think of it now).</p>
<p>So, in your example, the last part should look like this:</p>
<pre><code>sortMethod = lambda x: tuple(sorted(set(x.mods)))
sortedMods = sorted(list(mods), key=sortMethod)
for key, mods_group in groupby(sortedMods, sortMethod):
ret.append(list(mods_group))
</code></pre>
| 1 | 2008-10-02T07:38:59Z | [
"python",
"django",
"algorithm",
"puzzle"
] |
Django/Python - Grouping objects by common set from a many-to-many relationships | 160,298 | <p>This is a part algorithm-logic question (how to do it), part implementation question (how to do it best!). I'm working with Django, so I thought I'd share with that.</p>
<p>In Python, it's worth mentioning that the problem is somewhat related to <a href="http://stackoverflow.com/questions/773/how-do-i-use-pythons-itertoolsgroupby">how-do-i-use-pythons-itertoolsgroupby</a>.</p>
<p>Suppose you're given two Django Model-derived classes:</p>
<pre><code>from django.db import models
class Car(models.Model):
mods = models.ManyToManyField(Representative)
</code></pre>
<p>and</p>
<pre><code>from django.db import models
class Mods(models.Model):
...
</code></pre>
<p>How does one get a list of Cars, grouped by Cars with a common set of Mods?</p>
<p>I.e. I want to get a class likeso:</p>
<pre><code>Cars_by_common_mods = [
{ mods: { 'a' }, cars: { 'W1', 'W2' } },
{ mods: { 'a', 'b' }, cars: { 'X1', 'X2', 'X3' }, },
{ mods: { 'b' }, cars: { 'Y1', 'Y2' } },
{ mods: { 'a', 'b', 'c' }, cars: { 'Z1' } },
]
</code></pre>
<p>I've been thinking of something like:</p>
<pre><code>def cars_by_common_mods():
cars = Cars.objects.all()
mod_list = []
for car in cars:
mod_list.append( { 'car': car, 'mods': list(car.mods.all()) }
ret = []
for key, mods_group in groupby(list(mods), lambda x: set(x.mods)):
ret.append(mods_group)
return ret
</code></pre>
<p>However, that doesn't work because (perhaps among other reasons) the groupby doesn't seem to group by the mods sets. I guess the mod_list has to be sorted to work with groupby. All to say, I'm confident there's something simple and elegant out there that will be both enlightening and illuminating.</p>
<p><em>Cheers & thanks!</em></p>
| 5 | 2008-10-01T23:59:52Z | 173,592 | <p>If performance is a concern (i.e. lots of cars on a page, or a high-traffic site), <a href="http://groups.google.com/group/django-developers/browse_thread/thread/9a672d5bbbe67562" rel="nofollow">denormalization</a> makes sense, and simplifies your problem as a side effect.</p>
<p>Be aware that denormalizing many-to-many relations might be a bit tricky though. I haven't run into any such code examples yet.</p>
| 1 | 2008-10-06T08:41:56Z | [
"python",
"django",
"algorithm",
"puzzle"
] |
Django/Python - Grouping objects by common set from a many-to-many relationships | 160,298 | <p>This is a part algorithm-logic question (how to do it), part implementation question (how to do it best!). I'm working with Django, so I thought I'd share with that.</p>
<p>In Python, it's worth mentioning that the problem is somewhat related to <a href="http://stackoverflow.com/questions/773/how-do-i-use-pythons-itertoolsgroupby">how-do-i-use-pythons-itertoolsgroupby</a>.</p>
<p>Suppose you're given two Django Model-derived classes:</p>
<pre><code>from django.db import models
class Car(models.Model):
mods = models.ManyToManyField(Representative)
</code></pre>
<p>and</p>
<pre><code>from django.db import models
class Mods(models.Model):
...
</code></pre>
<p>How does one get a list of Cars, grouped by Cars with a common set of Mods?</p>
<p>I.e. I want to get a class likeso:</p>
<pre><code>Cars_by_common_mods = [
{ mods: { 'a' }, cars: { 'W1', 'W2' } },
{ mods: { 'a', 'b' }, cars: { 'X1', 'X2', 'X3' }, },
{ mods: { 'b' }, cars: { 'Y1', 'Y2' } },
{ mods: { 'a', 'b', 'c' }, cars: { 'Z1' } },
]
</code></pre>
<p>I've been thinking of something like:</p>
<pre><code>def cars_by_common_mods():
cars = Cars.objects.all()
mod_list = []
for car in cars:
mod_list.append( { 'car': car, 'mods': list(car.mods.all()) }
ret = []
for key, mods_group in groupby(list(mods), lambda x: set(x.mods)):
ret.append(mods_group)
return ret
</code></pre>
<p>However, that doesn't work because (perhaps among other reasons) the groupby doesn't seem to group by the mods sets. I guess the mod_list has to be sorted to work with groupby. All to say, I'm confident there's something simple and elegant out there that will be both enlightening and illuminating.</p>
<p><em>Cheers & thanks!</em></p>
| 5 | 2008-10-01T23:59:52Z | 178,657 | <p>Thank you all for the helpful replies. I've been plugging away at this problem. A 'best' solution still eludes me, but I've some thoughts.</p>
<p>I should mention that the statistics of the data-set I'm working with. In 75% of the cases there will be one Mod. In 24% of the cases, two. In 1% of the cases there will be zero, or three or more. For every Mod, there is at least one unique Car, though a Mod may be applied to numerous Cars.</p>
<p>Having said that, I've considered (but not implemented) something like-so:</p>
<pre><code>class ModSet(models.Model):
mods = models.ManyToManyField(Mod)
</code></pre>
<p>and change cars to </p>
<pre><code>class Car(models.Model):
modset = models.ForeignKey(ModSet)
</code></pre>
<p>It's trivial to group by Car.modset: I can use regroup, as suggested by Javier, for example. It seems a simpler and reasonably elegant solution; thoughts would be much appreciated.</p>
| 0 | 2008-10-07T14:17:42Z | [
"python",
"django",
"algorithm",
"puzzle"
] |
Are there any other good alternatives to zc.buildout and/or virtualenv for installing non-python dependencies? | 160,834 | <p>I am a member of a team that is about to launch a beta of a python (Django specifically) based web site and accompanying suite of backend tools. The team itself has doubled in size from 2 to 4 over the past few weeks and we expect continued growth for the next couple of months at least. One issue that has started to plague us is getting everyone up to speed in terms of getting their development environment configured and having all the right eggs installed, etc.</p>
<p>I'm looking for ways to simplify this process and make it less error prone. Both zc.buildout and virtualenv look like they would be good tools for addressing this problem but both seem to concentrate primarily on the python-specific issues. We have a couple of small subprojects in other languages (Java and Ruby specifically) as well as numerous python extensions that have to be compiled natively (lxml, MySQL drivers, etc). In fact, one of the biggest thorns in our side has been getting some of these extensions compiled against appropriate versions of the shared libraries so as to avoid segfaults, malloc errors and all sorts of similar issues. It doesn't help that out of 4 people we have 4 different development environments -- 1 leopard on ppc, 1 leopard on intel, 1 ubuntu and 1 windows.</p>
<p>Ultimately what would be ideal would be something that works roughly like this, from the dos/unix prompt:</p>
<p>$ git clone [repository url]
...
$ python setup-env.py
...</p>
<p>that then does what zc.buildout/virtualenv does (copy/symlink the python interpreter, provide a clean space to install eggs) then installs all required eggs, including installing any native shared library dependencies, installs the ruby project, the java project, etc.</p>
<p>Obviously this would be useful for both getting development environments up as well as deploying on staging/production servers.</p>
<p>Ideally I would like for the tool that accomplishes this to be written in/extensible via python, since that is (and always will be) the lingua franca of our team, but I am open to solutions in other languages.</p>
<p>So, my question then is: does anyone have any suggestions for better alternatives or any experiences they can share using one of these solutions to handle larger/broader install bases?</p>
| 6 | 2008-10-02T03:55:22Z | 160,872 | <p>Basically, you're looking for a <strong>cross-platform software/package installer</strong> (on the lines of apt-get/yum/etc.) I'm not sure something like that exists?</p>
<p>An alternative might be specifying the list of packages that need to be installed via the OS-specific package management system such as Fink or DarwinPorts for Mac OS X and having a script that sets up the build environment for the in-house code?</p>
| 0 | 2008-10-02T04:21:44Z | [
"python",
"deployment",
"build-process"
] |
Are there any other good alternatives to zc.buildout and/or virtualenv for installing non-python dependencies? | 160,834 | <p>I am a member of a team that is about to launch a beta of a python (Django specifically) based web site and accompanying suite of backend tools. The team itself has doubled in size from 2 to 4 over the past few weeks and we expect continued growth for the next couple of months at least. One issue that has started to plague us is getting everyone up to speed in terms of getting their development environment configured and having all the right eggs installed, etc.</p>
<p>I'm looking for ways to simplify this process and make it less error prone. Both zc.buildout and virtualenv look like they would be good tools for addressing this problem but both seem to concentrate primarily on the python-specific issues. We have a couple of small subprojects in other languages (Java and Ruby specifically) as well as numerous python extensions that have to be compiled natively (lxml, MySQL drivers, etc). In fact, one of the biggest thorns in our side has been getting some of these extensions compiled against appropriate versions of the shared libraries so as to avoid segfaults, malloc errors and all sorts of similar issues. It doesn't help that out of 4 people we have 4 different development environments -- 1 leopard on ppc, 1 leopard on intel, 1 ubuntu and 1 windows.</p>
<p>Ultimately what would be ideal would be something that works roughly like this, from the dos/unix prompt:</p>
<p>$ git clone [repository url]
...
$ python setup-env.py
...</p>
<p>that then does what zc.buildout/virtualenv does (copy/symlink the python interpreter, provide a clean space to install eggs) then installs all required eggs, including installing any native shared library dependencies, installs the ruby project, the java project, etc.</p>
<p>Obviously this would be useful for both getting development environments up as well as deploying on staging/production servers.</p>
<p>Ideally I would like for the tool that accomplishes this to be written in/extensible via python, since that is (and always will be) the lingua franca of our team, but I am open to solutions in other languages.</p>
<p>So, my question then is: does anyone have any suggestions for better alternatives or any experiences they can share using one of these solutions to handle larger/broader install bases?</p>
| 6 | 2008-10-02T03:55:22Z | 160,965 | <p>I have continued to research this issue since I posted the question. It looks like there are some attempts to address some of the needs I outlined, e.g. <a href="http://www.minitage.org/doc/rst/about.html" rel="nofollow">Minitage</a> and <a href="http://reductivelabs.com/projects/puppet/" rel="nofollow">Puppet</a> which take different approaches but both may accomplish what I want -- although Minitage does not explicitly state that it supports Windows. Lacking any better options I will try to make either one of these or just extensive customized use of zc.buildout work for our needs, but I still feel like there must be better options out there.</p>
| 0 | 2008-10-02T05:12:05Z | [
"python",
"deployment",
"build-process"
] |
Are there any other good alternatives to zc.buildout and/or virtualenv for installing non-python dependencies? | 160,834 | <p>I am a member of a team that is about to launch a beta of a python (Django specifically) based web site and accompanying suite of backend tools. The team itself has doubled in size from 2 to 4 over the past few weeks and we expect continued growth for the next couple of months at least. One issue that has started to plague us is getting everyone up to speed in terms of getting their development environment configured and having all the right eggs installed, etc.</p>
<p>I'm looking for ways to simplify this process and make it less error prone. Both zc.buildout and virtualenv look like they would be good tools for addressing this problem but both seem to concentrate primarily on the python-specific issues. We have a couple of small subprojects in other languages (Java and Ruby specifically) as well as numerous python extensions that have to be compiled natively (lxml, MySQL drivers, etc). In fact, one of the biggest thorns in our side has been getting some of these extensions compiled against appropriate versions of the shared libraries so as to avoid segfaults, malloc errors and all sorts of similar issues. It doesn't help that out of 4 people we have 4 different development environments -- 1 leopard on ppc, 1 leopard on intel, 1 ubuntu and 1 windows.</p>
<p>Ultimately what would be ideal would be something that works roughly like this, from the dos/unix prompt:</p>
<p>$ git clone [repository url]
...
$ python setup-env.py
...</p>
<p>that then does what zc.buildout/virtualenv does (copy/symlink the python interpreter, provide a clean space to install eggs) then installs all required eggs, including installing any native shared library dependencies, installs the ruby project, the java project, etc.</p>
<p>Obviously this would be useful for both getting development environments up as well as deploying on staging/production servers.</p>
<p>Ideally I would like for the tool that accomplishes this to be written in/extensible via python, since that is (and always will be) the lingua franca of our team, but I am open to solutions in other languages.</p>
<p>So, my question then is: does anyone have any suggestions for better alternatives or any experiences they can share using one of these solutions to handle larger/broader install bases?</p>
| 6 | 2008-10-02T03:55:22Z | 177,109 | <p>You might consider creating virtual machine appliances with whatever production OS you are running, and all of the software dependencies pre-built. Code can be edited either remotely, or with a shared folder. It worked pretty well for me in a past life that had a fairly complicated development environment.</p>
| 0 | 2008-10-07T03:13:09Z | [
"python",
"deployment",
"build-process"
] |
Are there any other good alternatives to zc.buildout and/or virtualenv for installing non-python dependencies? | 160,834 | <p>I am a member of a team that is about to launch a beta of a python (Django specifically) based web site and accompanying suite of backend tools. The team itself has doubled in size from 2 to 4 over the past few weeks and we expect continued growth for the next couple of months at least. One issue that has started to plague us is getting everyone up to speed in terms of getting their development environment configured and having all the right eggs installed, etc.</p>
<p>I'm looking for ways to simplify this process and make it less error prone. Both zc.buildout and virtualenv look like they would be good tools for addressing this problem but both seem to concentrate primarily on the python-specific issues. We have a couple of small subprojects in other languages (Java and Ruby specifically) as well as numerous python extensions that have to be compiled natively (lxml, MySQL drivers, etc). In fact, one of the biggest thorns in our side has been getting some of these extensions compiled against appropriate versions of the shared libraries so as to avoid segfaults, malloc errors and all sorts of similar issues. It doesn't help that out of 4 people we have 4 different development environments -- 1 leopard on ppc, 1 leopard on intel, 1 ubuntu and 1 windows.</p>
<p>Ultimately what would be ideal would be something that works roughly like this, from the dos/unix prompt:</p>
<p>$ git clone [repository url]
...
$ python setup-env.py
...</p>
<p>that then does what zc.buildout/virtualenv does (copy/symlink the python interpreter, provide a clean space to install eggs) then installs all required eggs, including installing any native shared library dependencies, installs the ruby project, the java project, etc.</p>
<p>Obviously this would be useful for both getting development environments up as well as deploying on staging/production servers.</p>
<p>Ideally I would like for the tool that accomplishes this to be written in/extensible via python, since that is (and always will be) the lingua franca of our team, but I am open to solutions in other languages.</p>
<p>So, my question then is: does anyone have any suggestions for better alternatives or any experiences they can share using one of these solutions to handle larger/broader install bases?</p>
| 6 | 2008-10-02T03:55:22Z | 180,149 | <p>Puppet doesn't (easily) support the Win32 world either. If you're looking for a deployment mechanism and not just a "dev setup" tool, you might consider looking into ControlTier (<a href="http://open.controltier.com/" rel="nofollow">http://open.controltier.com/</a>) which has a open-source cross-platform solution. </p>
<p>Beyond that you're looking at "enterprise" software such as BladeLogic or OpsWare and typically an outrageous pricetag for the functionality offered (my opinion, obviously).</p>
<p>A lot of folks have been aggressively using a combination of Puppet and Capistrano (even non-rails developers) for deployment automation tools to pretty good effect. Downside, again, is that it's expecting a somewhat homogeneous environment.</p>
| 0 | 2008-10-07T20:06:39Z | [
"python",
"deployment",
"build-process"
] |
Are there any other good alternatives to zc.buildout and/or virtualenv for installing non-python dependencies? | 160,834 | <p>I am a member of a team that is about to launch a beta of a python (Django specifically) based web site and accompanying suite of backend tools. The team itself has doubled in size from 2 to 4 over the past few weeks and we expect continued growth for the next couple of months at least. One issue that has started to plague us is getting everyone up to speed in terms of getting their development environment configured and having all the right eggs installed, etc.</p>
<p>I'm looking for ways to simplify this process and make it less error prone. Both zc.buildout and virtualenv look like they would be good tools for addressing this problem but both seem to concentrate primarily on the python-specific issues. We have a couple of small subprojects in other languages (Java and Ruby specifically) as well as numerous python extensions that have to be compiled natively (lxml, MySQL drivers, etc). In fact, one of the biggest thorns in our side has been getting some of these extensions compiled against appropriate versions of the shared libraries so as to avoid segfaults, malloc errors and all sorts of similar issues. It doesn't help that out of 4 people we have 4 different development environments -- 1 leopard on ppc, 1 leopard on intel, 1 ubuntu and 1 windows.</p>
<p>Ultimately what would be ideal would be something that works roughly like this, from the dos/unix prompt:</p>
<p>$ git clone [repository url]
...
$ python setup-env.py
...</p>
<p>that then does what zc.buildout/virtualenv does (copy/symlink the python interpreter, provide a clean space to install eggs) then installs all required eggs, including installing any native shared library dependencies, installs the ruby project, the java project, etc.</p>
<p>Obviously this would be useful for both getting development environments up as well as deploying on staging/production servers.</p>
<p>Ideally I would like for the tool that accomplishes this to be written in/extensible via python, since that is (and always will be) the lingua franca of our team, but I am open to solutions in other languages.</p>
<p>So, my question then is: does anyone have any suggestions for better alternatives or any experiences they can share using one of these solutions to handle larger/broader install bases?</p>
| 6 | 2008-10-02T03:55:22Z | 185,505 | <p>Setuptools may be capable of more of what you're looking for than you realize -- if you need a custom version of lxml to work correctly on MacOS X, for instance, you can put a URL to an appropriate egg inside your setup.py and have setuptools download and install that inside your developers' environments as necessary; it also can be told to download and install a specific version of a dependency from revision control.</p>
<p>That said, I'd lean towards using a scriptably generated virtual environment. It's pretty straightforward to build a kickstart file which installs whichever packages you depend on and then boot virtual machines (or production hardware!) against it, with puppet or similar software doing other administration (adding users, setting up services [where's your database come from?], etc). This comes in particularly handy when your production environment includes multiple machines -- just script the generation of multiple VMs within their handy little sandboxed subnet (I use libvirt+kvm for this; while kvm isn't available on all the platforms you have developers working on, qemu certainly is, or you can do as I do and have a small number of beefy VM hosts shared by multiple developers).</p>
<p>This gets you out of the headaches of supporting N platforms -- you only have a single virtual platform to support -- and means that your deployment process, as defined by the kickstart file and puppet code used for setup, is source-controlled and run through your QA and review processes just like everything else.</p>
| 3 | 2008-10-09T00:41:06Z | [
"python",
"deployment",
"build-process"
] |
Are there any other good alternatives to zc.buildout and/or virtualenv for installing non-python dependencies? | 160,834 | <p>I am a member of a team that is about to launch a beta of a python (Django specifically) based web site and accompanying suite of backend tools. The team itself has doubled in size from 2 to 4 over the past few weeks and we expect continued growth for the next couple of months at least. One issue that has started to plague us is getting everyone up to speed in terms of getting their development environment configured and having all the right eggs installed, etc.</p>
<p>I'm looking for ways to simplify this process and make it less error prone. Both zc.buildout and virtualenv look like they would be good tools for addressing this problem but both seem to concentrate primarily on the python-specific issues. We have a couple of small subprojects in other languages (Java and Ruby specifically) as well as numerous python extensions that have to be compiled natively (lxml, MySQL drivers, etc). In fact, one of the biggest thorns in our side has been getting some of these extensions compiled against appropriate versions of the shared libraries so as to avoid segfaults, malloc errors and all sorts of similar issues. It doesn't help that out of 4 people we have 4 different development environments -- 1 leopard on ppc, 1 leopard on intel, 1 ubuntu and 1 windows.</p>
<p>Ultimately what would be ideal would be something that works roughly like this, from the dos/unix prompt:</p>
<p>$ git clone [repository url]
...
$ python setup-env.py
...</p>
<p>that then does what zc.buildout/virtualenv does (copy/symlink the python interpreter, provide a clean space to install eggs) then installs all required eggs, including installing any native shared library dependencies, installs the ruby project, the java project, etc.</p>
<p>Obviously this would be useful for both getting development environments up as well as deploying on staging/production servers.</p>
<p>Ideally I would like for the tool that accomplishes this to be written in/extensible via python, since that is (and always will be) the lingua franca of our team, but I am open to solutions in other languages.</p>
<p>So, my question then is: does anyone have any suggestions for better alternatives or any experiences they can share using one of these solutions to handle larger/broader install bases?</p>
| 6 | 2008-10-02T03:55:22Z | 4,060,962 | <p>I always create a <code>develop.py</code> file at the top level of the project, and have also a <code>packages</code> directory with all of the <code>.tar.gz</code> files from PyPI that I want to install, and also included an unpacked copy of <code>virtualenv</code> that is ready to run right from that file. All of this goes into version control. Every developer can simply check out the trunk, run <code>develop.py</code>, and a few moments later will have a virtual environment ready to use that includes all of our dependencies at exactly the versions the other developers are using. And it works even if PyPI is down, which is very helpful at this point in that service's history.</p>
| 3 | 2010-10-30T22:31:38Z | [
"python",
"deployment",
"build-process"
] |
What is "lambda binding" in Python? | 160,859 | <p>I understand what are lambda functions in Python, but I can't find what is the meaning of "lambda binding" by searching the Python docs.
A link to read about it would be great.
A trivial explained example would be even better.
Thank you.</p>
| 9 | 2008-10-02T04:14:01Z | 160,884 | <p>Where have you seen the phrase used?</p>
<p>"Binding" in Python generally refers to the process by which a variable name ends up pointing to a specific object, whether by assignment or parameter passing or some other means, e.g.:</p>
<pre><code>a = dict(foo="bar", zip="zap", zig="zag") # binds a to a newly-created dict object
b = a # binds b to that same dictionary
def crunch(param):
print param
crunch(a) # binds the parameter "param" in the function crunch to that same dict again
</code></pre>
<p>So I would guess that "lambda binding" refers to the process of binding a lambda function to a variable name, or maybe binding its named parameters to specific objects? There's a pretty good explanation of binding in the Language Reference, at <a href="http://docs.python.org/ref/naming.html" rel="nofollow">http://docs.python.org/ref/naming.html</a></p>
| 1 | 2008-10-02T04:30:36Z | [
"python",
"binding",
"lambda"
] |
What is "lambda binding" in Python? | 160,859 | <p>I understand what are lambda functions in Python, but I can't find what is the meaning of "lambda binding" by searching the Python docs.
A link to read about it would be great.
A trivial explained example would be even better.
Thank you.</p>
| 9 | 2008-10-02T04:14:01Z | 160,898 | <p>First, a general definition:</p>
<blockquote>
<p>When a program or function statement
is executed, the current values of
formal parameters are saved (on the
stack) and within the scope of the
statement, they are bound to the
values of the actual arguments made in
the call. When the statement is
exited, the original values of those
formal arguments are restored. This
protocol is fully recursive. If within
the body of a statement, something is
done that causes the formal parameters
to be bound again, to new values, the
lambda-binding scheme guarantees that
this will all happen in an orderly
manner.</p>
</blockquote>
<p>Now, there is an excellent <a href="http://markmail.org/message/fypalne4rp5curta" rel="nofollow" title="Theoretical question about Lambda">python example in a discussion here</a>:</p>
<p>"...there is only one binding for <code>x</code>: doing <code>x = 7</code> just changes the value in the pre-existing binding. That's why</p>
<pre><code>def foo(x):
a = lambda: x
x = 7
b = lambda: x
return a,b
</code></pre>
<p>returns two functions that both return 7; if there was a new binding after the <code>x = 7</code>, the functions would return different values [assuming you don't call foo(7), of course. Also assuming nested_scopes]...."</p>
| 12 | 2008-10-02T04:38:59Z | [
"python",
"binding",
"lambda"
] |
What is "lambda binding" in Python? | 160,859 | <p>I understand what are lambda functions in Python, but I can't find what is the meaning of "lambda binding" by searching the Python docs.
A link to read about it would be great.
A trivial explained example would be even better.
Thank you.</p>
| 9 | 2008-10-02T04:14:01Z | 160,920 | <p>I've never heard that term, but one explanation could be the "default parameter" hack used to assign a value directly to a lambda's parameter. Using Swati's example:</p>
<pre><code>def foo(x):
a = lambda x=x: x
x = 7
b = lambda: x
return a,b
aa, bb = foo(4)
aa() # Prints 4
bb() # Prints 7
</code></pre>
| 6 | 2008-10-02T04:52:54Z | [
"python",
"binding",
"lambda"
] |
Emulation of lex like functionality in Perl or Python | 160,889 | <p>Here's the deal. Is there a way to have strings tokenized in a line based on multiple regexes?</p>
<p>One example:</p>
<p>I have to get all href tags, their corresponding text and some other text based on a different regex.
So I have 3 expressions and would like to tokenize the line and extract tokens of text matching every expression.</p>
<p>I have actually done this using flex (not to be confused with Adobe), which is an implementation of the good old lex. lex provides
an elegant way to do this by executing "actions" based on expressions. One can control the way
lex reading a file too (block / line based read).</p>
<p>The problem is that flex actually produces C/ C++ code which actually does the tokenizing job. I have a
make file which wraps all these things.
I was wondering if perl /python can in some way do the same thing. Its just that I would like to do everything
I like in a single programming language itself.</p>
<p>Tokenizing is just one of the things that I want to do as part of my application.</p>
<p>Apart from perl or python can any language (functional also) do this?</p>
<p>I did read about PLY and ANTLR here (<a href="http://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085">http://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085</a>).</p>
<p>But is there a way to do it naturally in python itself? pardon my ignorance, but are these tools used in any popular products / services?</p>
<p>Thank you.</p>
| 4 | 2008-10-02T04:34:06Z | 160,895 | <p>Have you looked at <a href="http://pyparsing.wikispaces.com/" rel="nofollow">PyParsing</a>?</p>
<p>From their homepage:</p>
<p>Here is a program to parse "Hello, World!" (or any greeting of the form ", !"):</p>
<pre><code>from pyparsing import Word, alphas
greet = Word( alphas ) + "," + Word( alphas ) + "!" # <-- grammar defined here
hello = "Hello, World!"
print hello, "->", greet.parseString( hello )
</code></pre>
<p>The program outputs the following:</p>
<pre><code>Hello, World! -> ['Hello', ',', 'World', '!']
</code></pre>
| 3 | 2008-10-02T04:37:53Z | [
"python",
"perl",
"parsing",
"lex"
] |
Emulation of lex like functionality in Perl or Python | 160,889 | <p>Here's the deal. Is there a way to have strings tokenized in a line based on multiple regexes?</p>
<p>One example:</p>
<p>I have to get all href tags, their corresponding text and some other text based on a different regex.
So I have 3 expressions and would like to tokenize the line and extract tokens of text matching every expression.</p>
<p>I have actually done this using flex (not to be confused with Adobe), which is an implementation of the good old lex. lex provides
an elegant way to do this by executing "actions" based on expressions. One can control the way
lex reading a file too (block / line based read).</p>
<p>The problem is that flex actually produces C/ C++ code which actually does the tokenizing job. I have a
make file which wraps all these things.
I was wondering if perl /python can in some way do the same thing. Its just that I would like to do everything
I like in a single programming language itself.</p>
<p>Tokenizing is just one of the things that I want to do as part of my application.</p>
<p>Apart from perl or python can any language (functional also) do this?</p>
<p>I did read about PLY and ANTLR here (<a href="http://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085">http://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085</a>).</p>
<p>But is there a way to do it naturally in python itself? pardon my ignorance, but are these tools used in any popular products / services?</p>
<p>Thank you.</p>
| 4 | 2008-10-02T04:34:06Z | 160,896 | <p>Sounds like you really just want to parse HTML, I recommend looking at any of the wonderful packages for doing so:</p>
<ul>
<li><a href="http://crummy.com/software/BeautifulSoup" rel="nofollow">BeautifulSoup</a></li>
<li><a href="http://codespeak.net/lxml/lxmlhtml.html" rel="nofollow">lxml.html</a></li>
<li><a href="http://code.google.com/p/html5lib/" rel="nofollow">html5lib</a></li>
</ul>
<p>Or! You can use a parser like one of the following:</p>
<ul>
<li><a href="http://pyparsing.wikispaces.com" rel="nofollow">PyParsing</a></li>
<li><a href="http://dparser.sourceforge.net/" rel="nofollow">DParser</a> - A GLR parser with good python bindings.</li>
<li><a href="http://www.antlr.org" rel="nofollow">ANTLR</a> - A recursive decent parser generator that can generate python code.</li>
</ul>
<p>This example is from the BeautifulSoup <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html" rel="nofollow">Documentation</a>:</p>
<pre><code>from BeautifulSoup import BeautifulSoup, SoupStrainer
import re
links = SoupStrainer('a')
[tag for tag in BeautifulSoup(doc, parseOnlyThese=links)]
# [<a href="http://www.bob.com/">success</a>,
# <a href="http://www.bob.com/plasma">experiments</a>,
# <a href="http://www.boogabooga.net/">BoogaBooga</a>]
linksToBob = SoupStrainer('a', href=re.compile('bob.com/'))
[tag for tag in BeautifulSoup(doc, parseOnlyThese=linksToBob)]
# [<a href="http://www.bob.com/">success</a>,
# <a href="http://www.bob.com/plasma">experiments</a>]
</code></pre>
| 5 | 2008-10-02T04:38:26Z | [
"python",
"perl",
"parsing",
"lex"
] |
Emulation of lex like functionality in Perl or Python | 160,889 | <p>Here's the deal. Is there a way to have strings tokenized in a line based on multiple regexes?</p>
<p>One example:</p>
<p>I have to get all href tags, their corresponding text and some other text based on a different regex.
So I have 3 expressions and would like to tokenize the line and extract tokens of text matching every expression.</p>
<p>I have actually done this using flex (not to be confused with Adobe), which is an implementation of the good old lex. lex provides
an elegant way to do this by executing "actions" based on expressions. One can control the way
lex reading a file too (block / line based read).</p>
<p>The problem is that flex actually produces C/ C++ code which actually does the tokenizing job. I have a
make file which wraps all these things.
I was wondering if perl /python can in some way do the same thing. Its just that I would like to do everything
I like in a single programming language itself.</p>
<p>Tokenizing is just one of the things that I want to do as part of my application.</p>
<p>Apart from perl or python can any language (functional also) do this?</p>
<p>I did read about PLY and ANTLR here (<a href="http://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085">http://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085</a>).</p>
<p>But is there a way to do it naturally in python itself? pardon my ignorance, but are these tools used in any popular products / services?</p>
<p>Thank you.</p>
| 4 | 2008-10-02T04:34:06Z | 160,922 | <p>Look at documentation for following modules on <a href="http://www.cpan.org/" rel="nofollow">CPAN</a></p>
<p><a href="http://search.cpan.org/search?query=HTML%3A%3ATreeBuilder&mode=all" rel="nofollow">HTML::TreeBuilder</a></p>
<p><a href="http://search.cpan.org/author/MSISK/HTML-TableExtract-2.10/lib/HTML/TableExtract.pm" rel="nofollow">HTML::TableExtract</a></p>
<p>and</p>
<p><a href="http://search.cpan.org/search?query=parse+recdescent&mode=all" rel="nofollow">Parse::RecDescent</a></p>
<p>I've used these modules to process quite large and complex web-pages.</p>
| 8 | 2008-10-02T04:53:03Z | [
"python",
"perl",
"parsing",
"lex"
] |
Emulation of lex like functionality in Perl or Python | 160,889 | <p>Here's the deal. Is there a way to have strings tokenized in a line based on multiple regexes?</p>
<p>One example:</p>
<p>I have to get all href tags, their corresponding text and some other text based on a different regex.
So I have 3 expressions and would like to tokenize the line and extract tokens of text matching every expression.</p>
<p>I have actually done this using flex (not to be confused with Adobe), which is an implementation of the good old lex. lex provides
an elegant way to do this by executing "actions" based on expressions. One can control the way
lex reading a file too (block / line based read).</p>
<p>The problem is that flex actually produces C/ C++ code which actually does the tokenizing job. I have a
make file which wraps all these things.
I was wondering if perl /python can in some way do the same thing. Its just that I would like to do everything
I like in a single programming language itself.</p>
<p>Tokenizing is just one of the things that I want to do as part of my application.</p>
<p>Apart from perl or python can any language (functional also) do this?</p>
<p>I did read about PLY and ANTLR here (<a href="http://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085">http://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085</a>).</p>
<p>But is there a way to do it naturally in python itself? pardon my ignorance, but are these tools used in any popular products / services?</p>
<p>Thank you.</p>
| 4 | 2008-10-02T04:34:06Z | 161,146 | <p>If you're specifically after parsing links out of web-pages, then Perl's <a href="http://search.cpan.org/perldoc?WWW::Mechanize" rel="nofollow">WWW::Mechanize</a> module will figure things out for you in a very elegant fashion. Here's a sample program that grabs the first page of Stack Overflow and parses out all the links, printing their text and corresponding URLs:</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use WWW::Mechanize;
my $mech = WWW::Mechanize->new;
$mech->get("http://stackoverflow.com/");
$mech->success or die "Oh no! Couldn't fetch stackoverflow.com";
foreach my $link ($mech->links) {
print "* [",$link->text, "] points to ", $link->url, "\n";
}
</code></pre>
<p>In the main loop, each <code>$link</code> is a <a href="http://search.cpan.org/perldoc?WWW::Mechanize::Link" rel="nofollow">WWW::Mechanize::Link</a> object, so you're not just constrained to getting the text and URL.</p>
<p>All the best,</p>
<p>Paul</p>
| 7 | 2008-10-02T06:52:06Z | [
"python",
"perl",
"parsing",
"lex"
] |
Emulation of lex like functionality in Perl or Python | 160,889 | <p>Here's the deal. Is there a way to have strings tokenized in a line based on multiple regexes?</p>
<p>One example:</p>
<p>I have to get all href tags, their corresponding text and some other text based on a different regex.
So I have 3 expressions and would like to tokenize the line and extract tokens of text matching every expression.</p>
<p>I have actually done this using flex (not to be confused with Adobe), which is an implementation of the good old lex. lex provides
an elegant way to do this by executing "actions" based on expressions. One can control the way
lex reading a file too (block / line based read).</p>
<p>The problem is that flex actually produces C/ C++ code which actually does the tokenizing job. I have a
make file which wraps all these things.
I was wondering if perl /python can in some way do the same thing. Its just that I would like to do everything
I like in a single programming language itself.</p>
<p>Tokenizing is just one of the things that I want to do as part of my application.</p>
<p>Apart from perl or python can any language (functional also) do this?</p>
<p>I did read about PLY and ANTLR here (<a href="http://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085">http://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085</a>).</p>
<p>But is there a way to do it naturally in python itself? pardon my ignorance, but are these tools used in any popular products / services?</p>
<p>Thank you.</p>
| 4 | 2008-10-02T04:34:06Z | 161,372 | <p>If your problem has anything at all to do with web scraping, I recommend looking at <a href="http://search.cpan.org/perldoc?Web::Scraper" rel="nofollow">Web::Scraper</a> , which provides easy element selection via XPath respectively CSS selectors. I have a (German) <a href="http://datenzoo.de/pub/gpw2008/web-scraper/web-scraper-talk.html" rel="nofollow">talk on Web::Scraper</a> , but if you run it through babelfish or just look at the code samples, that can help you to get a quick overview of the syntax.</p>
<p>Hand-parsing HTML is onerous and won't give you much over using one of the premade HTML parsers. If your HTML is of very limited variation, you can get by by using clever regular expressions, but if you're already breaking out hard-core parser tools, it sounds as if your HTML is far more regular than what is sane to parse with regular expressions.</p>
| 2 | 2008-10-02T08:37:58Z | [
"python",
"perl",
"parsing",
"lex"
] |
Emulation of lex like functionality in Perl or Python | 160,889 | <p>Here's the deal. Is there a way to have strings tokenized in a line based on multiple regexes?</p>
<p>One example:</p>
<p>I have to get all href tags, their corresponding text and some other text based on a different regex.
So I have 3 expressions and would like to tokenize the line and extract tokens of text matching every expression.</p>
<p>I have actually done this using flex (not to be confused with Adobe), which is an implementation of the good old lex. lex provides
an elegant way to do this by executing "actions" based on expressions. One can control the way
lex reading a file too (block / line based read).</p>
<p>The problem is that flex actually produces C/ C++ code which actually does the tokenizing job. I have a
make file which wraps all these things.
I was wondering if perl /python can in some way do the same thing. Its just that I would like to do everything
I like in a single programming language itself.</p>
<p>Tokenizing is just one of the things that I want to do as part of my application.</p>
<p>Apart from perl or python can any language (functional also) do this?</p>
<p>I did read about PLY and ANTLR here (<a href="http://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085">http://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085</a>).</p>
<p>But is there a way to do it naturally in python itself? pardon my ignorance, but are these tools used in any popular products / services?</p>
<p>Thank you.</p>
| 4 | 2008-10-02T04:34:06Z | 161,977 | <p>Also check out <a href="http://search.cpan.org/dist/pQuery/" rel="nofollow">pQuery</a> it as a really nice Perlish way of doing this kind of stuff....</p>
<pre><code>use pQuery;
pQuery( 'http://www.perl.com' )->find( 'a' )->each(
sub {
my $pQ = pQuery( $_ );
say $pQ->text, ' -> ', $pQ->toHtml;
}
);
# prints all HTML anchors on www.perl.com
# => link text -> anchor HTML
</code></pre>
<p>However if your requirement is beyond HTML/Web then here is the earlier "Hello World!" example in <a href="http://search.cpan.org/dist/Parse-RecDescent/lib/Parse/RecDescent.pm" rel="nofollow">Parse::RecDescent</a>...</p>
<pre><code>use strict;
use warnings;
use Parse::RecDescent;
my $grammar = q{
alpha : /\w+/
sep : /,|\s/
end : '!'
greet : alpha sep alpha end { shift @item; return \@item }
};
my $parse = Parse::RecDescent->new( $grammar );
my $hello = "Hello, World!";
print "$hello -> @{ $parse->greet( $hello ) }";
# => Hello, World! -> Hello , World !
</code></pre>
<p>Probably too much of a large hammer to crack this nut ;-)</p>
<p>/I3az/</p>
| 1 | 2008-10-02T12:19:37Z | [
"python",
"perl",
"parsing",
"lex"
] |
Emulation of lex like functionality in Perl or Python | 160,889 | <p>Here's the deal. Is there a way to have strings tokenized in a line based on multiple regexes?</p>
<p>One example:</p>
<p>I have to get all href tags, their corresponding text and some other text based on a different regex.
So I have 3 expressions and would like to tokenize the line and extract tokens of text matching every expression.</p>
<p>I have actually done this using flex (not to be confused with Adobe), which is an implementation of the good old lex. lex provides
an elegant way to do this by executing "actions" based on expressions. One can control the way
lex reading a file too (block / line based read).</p>
<p>The problem is that flex actually produces C/ C++ code which actually does the tokenizing job. I have a
make file which wraps all these things.
I was wondering if perl /python can in some way do the same thing. Its just that I would like to do everything
I like in a single programming language itself.</p>
<p>Tokenizing is just one of the things that I want to do as part of my application.</p>
<p>Apart from perl or python can any language (functional also) do this?</p>
<p>I did read about PLY and ANTLR here (<a href="http://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085">http://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085</a>).</p>
<p>But is there a way to do it naturally in python itself? pardon my ignorance, but are these tools used in any popular products / services?</p>
<p>Thank you.</p>
| 4 | 2008-10-02T04:34:06Z | 162,301 | <p>From <a href="http://perldoc.perl.org/perlop.html#Regexp-Quote-Like-Operators" rel="nofollow">perlop</a>:</p>
<blockquote>
<p>A useful idiom for lex -like scanners
is <code>/\G.../gc</code> . You can combine
several regexps like this to process a
string part-by-part, doing different
actions depending on which regexp
matched. Each regexp tries to match
where the previous one leaves off.</p>
<pre><code> LOOP:
{
print(" digits"), redo LOOP if /\G\d+\b[,.;]?\s*/gc;
print(" lowercase"), redo LOOP if /\G[a-z]+\b[,.;]?\s*/gc;
print(" UPPERCASE"), redo LOOP if /\G[A-Z]+\b[,.;]?\s*/gc;
print(" Capitalized"), redo LOOP if /\G[A-Z][a-z]+\b[,.;]?\s*/gc;
print(" MiXeD"), redo LOOP if /\G[A-Za-z]+\b[,.;]?\s*/gc;
print(" alphanumeric"), redo LOOP if /\G[A-Za-z0-9]+\b[,.;]?\s*/gc;
print(" line-noise"), redo LOOP if /\G[^A-Za-z0-9]+/gc;
print ". That's all!\n";
}
</code></pre>
</blockquote>
| 1 | 2008-10-02T13:36:36Z | [
"python",
"perl",
"parsing",
"lex"
] |
Emulation of lex like functionality in Perl or Python | 160,889 | <p>Here's the deal. Is there a way to have strings tokenized in a line based on multiple regexes?</p>
<p>One example:</p>
<p>I have to get all href tags, their corresponding text and some other text based on a different regex.
So I have 3 expressions and would like to tokenize the line and extract tokens of text matching every expression.</p>
<p>I have actually done this using flex (not to be confused with Adobe), which is an implementation of the good old lex. lex provides
an elegant way to do this by executing "actions" based on expressions. One can control the way
lex reading a file too (block / line based read).</p>
<p>The problem is that flex actually produces C/ C++ code which actually does the tokenizing job. I have a
make file which wraps all these things.
I was wondering if perl /python can in some way do the same thing. Its just that I would like to do everything
I like in a single programming language itself.</p>
<p>Tokenizing is just one of the things that I want to do as part of my application.</p>
<p>Apart from perl or python can any language (functional also) do this?</p>
<p>I did read about PLY and ANTLR here (<a href="http://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085">http://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085</a>).</p>
<p>But is there a way to do it naturally in python itself? pardon my ignorance, but are these tools used in any popular products / services?</p>
<p>Thank you.</p>
| 4 | 2008-10-02T04:34:06Z | 172,371 | <p>Modifying Bruno's example to include error checking:</p>
<pre><code>my $input = "...";
while (1) {
if ($input =~ /\G(\w+)/gc) { print "word: '$1'\n"; next }
if ($input =~ /\G(\s+)/gc) { print "whitespace: '$1'\n"; next }
if ($input !~ /\G\z/gc) { print "tokenizing error at character " . pos($input) . "\n" }
print "done!\n"; last;
}
</code></pre>
<p>(Note that using scalar //g is unfortunately the one place where you really can't avoid using the $1, etc. variables.)</p>
| 0 | 2008-10-05T18:07:23Z | [
"python",
"perl",
"parsing",
"lex"
] |
Django admin site not displaying ManyToManyField relationship | 160,905 | <p>I'm working on what I think is a pretty standard django site, but am having trouble getting my admin section to display the proper fields.</p>
<p>Here's my models.py:</p>
<pre><code>class Tech(models.Model):
name = models.CharField(max_length = 30)
class Project(models.Model):
title = models.CharField(max_length = 50)
techs = models.ManyToManyField(Tech)
</code></pre>
<p>In other words, a Project can have different Tech objects and different tech objects can belong to different Projects (Project X was created with Python and Django, Project Y was C# and SQL Server)</p>
<p>However, the admin site doesn't display any UI for the Tech objects. Here's my admin.py:</p>
<pre><code>class TechInline(admin.TabularInline):
model = Tech
extra = 5
class ProjectAdmin(admin.ModelAdmin):
fields = ['title']
inlines = []
list_display = ('title')
admin.site.register(Project, ProjectAdmin)
</code></pre>
<p>I've tried adding the <code>TechInline</code> class to the <code>inlines</code> list, but that causes a </p>
<pre><code><class 'home.projects.models.Tech'> has no ForeignKey to <class 'home.projects.models.Project'>
</code></pre>
<p>Error. Also tried adding <code>techs</code> to the <code>fields</code> list, but that gives a </p>
<blockquote>
<p>no such table: projects_project_techs</p>
</blockquote>
<p>Error. I verified, and there is no <code>projects_project_techs</code> table, but there is a <code>projects_tech</code> one. Did something perhaps get screwed up in my syncdb? </p>
<p>I am using Sqlite as my database if that helps.</p>
| 3 | 2008-10-02T04:43:28Z | 160,916 | <blockquote>
<p>I've tried adding the TechInline class to the inlines list, but that causes a</p>
<p>'TechInLine' not defined</p>
</blockquote>
<p>Is that a straight copy-paste? It looks like you just made a typo -- try <code>TechInline</code> instead of <code>TechInLine</code>.</p>
<p>If your syncdb didn't create the proper table, you can do it manually. Execute this command:</p>
<pre><code>python manage.py sqlreset <myapp>
</code></pre>
<p>And look for the definition for the <code>projects_project_techs</code> table. Copy and paste it into the client for your database.</p>
| 2 | 2008-10-02T04:48:29Z | [
"python",
"django"
] |
Django admin site not displaying ManyToManyField relationship | 160,905 | <p>I'm working on what I think is a pretty standard django site, but am having trouble getting my admin section to display the proper fields.</p>
<p>Here's my models.py:</p>
<pre><code>class Tech(models.Model):
name = models.CharField(max_length = 30)
class Project(models.Model):
title = models.CharField(max_length = 50)
techs = models.ManyToManyField(Tech)
</code></pre>
<p>In other words, a Project can have different Tech objects and different tech objects can belong to different Projects (Project X was created with Python and Django, Project Y was C# and SQL Server)</p>
<p>However, the admin site doesn't display any UI for the Tech objects. Here's my admin.py:</p>
<pre><code>class TechInline(admin.TabularInline):
model = Tech
extra = 5
class ProjectAdmin(admin.ModelAdmin):
fields = ['title']
inlines = []
list_display = ('title')
admin.site.register(Project, ProjectAdmin)
</code></pre>
<p>I've tried adding the <code>TechInline</code> class to the <code>inlines</code> list, but that causes a </p>
<pre><code><class 'home.projects.models.Tech'> has no ForeignKey to <class 'home.projects.models.Project'>
</code></pre>
<p>Error. Also tried adding <code>techs</code> to the <code>fields</code> list, but that gives a </p>
<blockquote>
<p>no such table: projects_project_techs</p>
</blockquote>
<p>Error. I verified, and there is no <code>projects_project_techs</code> table, but there is a <code>projects_tech</code> one. Did something perhaps get screwed up in my syncdb? </p>
<p>I am using Sqlite as my database if that helps.</p>
| 3 | 2008-10-02T04:43:28Z | 161,500 | <p>Assuming your app is called "projects", the default name for your techs table will be projects_tech and the projects table will be projects_project.</p>
<p>The many-to-many table should be something like projects_project_techs</p>
| 0 | 2008-10-02T09:27:51Z | [
"python",
"django"
] |
Django admin site not displaying ManyToManyField relationship | 160,905 | <p>I'm working on what I think is a pretty standard django site, but am having trouble getting my admin section to display the proper fields.</p>
<p>Here's my models.py:</p>
<pre><code>class Tech(models.Model):
name = models.CharField(max_length = 30)
class Project(models.Model):
title = models.CharField(max_length = 50)
techs = models.ManyToManyField(Tech)
</code></pre>
<p>In other words, a Project can have different Tech objects and different tech objects can belong to different Projects (Project X was created with Python and Django, Project Y was C# and SQL Server)</p>
<p>However, the admin site doesn't display any UI for the Tech objects. Here's my admin.py:</p>
<pre><code>class TechInline(admin.TabularInline):
model = Tech
extra = 5
class ProjectAdmin(admin.ModelAdmin):
fields = ['title']
inlines = []
list_display = ('title')
admin.site.register(Project, ProjectAdmin)
</code></pre>
<p>I've tried adding the <code>TechInline</code> class to the <code>inlines</code> list, but that causes a </p>
<pre><code><class 'home.projects.models.Tech'> has no ForeignKey to <class 'home.projects.models.Project'>
</code></pre>
<p>Error. Also tried adding <code>techs</code> to the <code>fields</code> list, but that gives a </p>
<blockquote>
<p>no such table: projects_project_techs</p>
</blockquote>
<p>Error. I verified, and there is no <code>projects_project_techs</code> table, but there is a <code>projects_tech</code> one. Did something perhaps get screwed up in my syncdb? </p>
<p>I am using Sqlite as my database if that helps.</p>
| 3 | 2008-10-02T04:43:28Z | 162,932 | <p>@<a href="#160916" rel="nofollow">John Millikin </a>- Thanks for the sqlreset tip, that put me on the right path. The sqlreset generated code that showed me that the <code>projects_project_techs</code> was never actually created. I ended up just deleting my deb.db database and regenerating it. <code>techs</code> then showed up as it should. </p>
<p>And just as a sidenote, I had to do an <code>admin.site.register(Tech)</code> to be able to create new instances of the class from the Project page too.</p>
<p>I'll probably post another question to see if there is a better way to implement model changes (since I'm pretty sure that is what caused my problem) without wiping the database.</p>
| 0 | 2008-10-02T15:17:50Z | [
"python",
"django"
] |
Library for converting a traceback to its exception? | 161,367 | <p><br />
Just a curiosity: is there an already-coded way to convert a printed traceback back to the exception that generated it? :) Or to a sys.exc_info-like structure?</p>
| 0 | 2008-10-02T08:35:39Z | 161,546 | <p>Converting a traceback to the exception object wouldn't be too hard, given common exception classes (parse the last line for the exception class and the arguments given to it at instantiation.) The traceback object (the third argument returned by sys.exc_info()) is an entirely different matter, though. The traceback object actually contains the chain of frame objects that constituted the stack at the time of the exception. Including local variables, global variables, et cetera. It is impossible to recreate that just from the displayed traceback. </p>
<p>The best you could do would be to parse each 'File "X", line N, in Y:' line and create fake frame objects that are almost entirely empty. There would be very little value in it, as basically the only thing you would be able to do with it would be to print it. What are you trying to accomplish?</p>
| 2 | 2008-10-02T09:48:57Z | [
"python"
] |
How would you implement ant-style patternsets in python to select groups of files? | 161,755 | <p>Ant has a nice way to select groups of files, most handily using ** to indicate a directory tree. E.g.</p>
<pre><code>**/CVS/* # All files immediately under a CVS directory.
mydir/mysubdir/** # All files recursively under mysubdir
</code></pre>
<p>More examples can be seen here:</p>
<p><a href="http://ant.apache.org/manual/dirtasks.html" rel="nofollow">http://ant.apache.org/manual/dirtasks.html</a></p>
<p>How would you implement this in python, so that you could do something like:</p>
<pre><code>files = get_files("**/CVS/*")
for file in files:
print file
=>
CVS/Repository
mydir/mysubdir/CVS/Entries
mydir/mysubdir/foo/bar/CVS/Entries
</code></pre>
| 3 | 2008-10-02T11:00:56Z | 161,858 | <p><code>os.walk</code> is your friend. Look at the example in the Python manual
(<a href="https://docs.python.org/2/library/os.html#os.walk" rel="nofollow">https://docs.python.org/2/library/os.html#os.walk</a>) and try to build something from that.</p>
<p>To match "<code>**/CVS/*</code>" against a file name you get, you can do something like this:</p>
<pre><code>def match(pattern, filename):
if pattern.startswith("**"):
return fnmatch.fnmatch(file, pattern[1:])
else:
return fnmatch.fnmatch(file, pattern)
</code></pre>
<p>In <code>fnmatch.fnmatch</code>, "*" matches anything (including slashes).</p>
| 2 | 2008-10-02T11:42:20Z | [
"python",
"file",
"ant"
] |
How would you implement ant-style patternsets in python to select groups of files? | 161,755 | <p>Ant has a nice way to select groups of files, most handily using ** to indicate a directory tree. E.g.</p>
<pre><code>**/CVS/* # All files immediately under a CVS directory.
mydir/mysubdir/** # All files recursively under mysubdir
</code></pre>
<p>More examples can be seen here:</p>
<p><a href="http://ant.apache.org/manual/dirtasks.html" rel="nofollow">http://ant.apache.org/manual/dirtasks.html</a></p>
<p>How would you implement this in python, so that you could do something like:</p>
<pre><code>files = get_files("**/CVS/*")
for file in files:
print file
=>
CVS/Repository
mydir/mysubdir/CVS/Entries
mydir/mysubdir/foo/bar/CVS/Entries
</code></pre>
| 3 | 2008-10-02T11:00:56Z | 161,891 | <p>Yup. Your best bet is, as has already been suggested, to work with 'os.walk'. Or, write wrappers around '<a href="http://docs.python.org/library/glob.html" rel="nofollow">glob</a>' and '<a href="http://docs.python.org/library/fnmatch.html" rel="nofollow">fnmatch</a>' modules, perhaps.</p>
| 0 | 2008-10-02T11:54:28Z | [
"python",
"file",
"ant"
] |
How would you implement ant-style patternsets in python to select groups of files? | 161,755 | <p>Ant has a nice way to select groups of files, most handily using ** to indicate a directory tree. E.g.</p>
<pre><code>**/CVS/* # All files immediately under a CVS directory.
mydir/mysubdir/** # All files recursively under mysubdir
</code></pre>
<p>More examples can be seen here:</p>
<p><a href="http://ant.apache.org/manual/dirtasks.html" rel="nofollow">http://ant.apache.org/manual/dirtasks.html</a></p>
<p>How would you implement this in python, so that you could do something like:</p>
<pre><code>files = get_files("**/CVS/*")
for file in files:
print file
=>
CVS/Repository
mydir/mysubdir/CVS/Entries
mydir/mysubdir/foo/bar/CVS/Entries
</code></pre>
| 3 | 2008-10-02T11:00:56Z | 162,716 | <p><a href="http://www.python.org/doc/2.6/library/os.html#os.walk" rel="nofollow">os.walk</a> is your best bet for this. I did the example below with .svn because I had that handy, and it worked great:</p>
<pre><code>import re
for (dirpath, dirnames, filenames) in os.walk("."):
if re.search(r'\.svn$', dirpath):
for file in filenames:
print file
</code></pre>
| 0 | 2008-10-02T14:47:57Z | [
"python",
"file",
"ant"
] |
How would you implement ant-style patternsets in python to select groups of files? | 161,755 | <p>Ant has a nice way to select groups of files, most handily using ** to indicate a directory tree. E.g.</p>
<pre><code>**/CVS/* # All files immediately under a CVS directory.
mydir/mysubdir/** # All files recursively under mysubdir
</code></pre>
<p>More examples can be seen here:</p>
<p><a href="http://ant.apache.org/manual/dirtasks.html" rel="nofollow">http://ant.apache.org/manual/dirtasks.html</a></p>
<p>How would you implement this in python, so that you could do something like:</p>
<pre><code>files = get_files("**/CVS/*")
for file in files:
print file
=>
CVS/Repository
mydir/mysubdir/CVS/Entries
mydir/mysubdir/foo/bar/CVS/Entries
</code></pre>
| 3 | 2008-10-02T11:00:56Z | 163,212 | <p>As soon as you come across a <code>**</code>, you're going to have to recurse through the whole directory structure, so I think at that point, the easiest method is to iterate through the directory with os.walk, construct a path, and then check if it matches the pattern. You can probably convert to a regex by something like:</p>
<pre><code>def glob_to_regex(pat, dirsep=os.sep):
dirsep = re.escape(dirsep)
print re.escape(pat)
regex = (re.escape(pat).replace("\\*\\*"+dirsep,".*")
.replace("\\*\\*",".*")
.replace("\\*","[^%s]*" % dirsep)
.replace("\\?","[^%s]" % dirsep))
return re.compile(regex+"$")
</code></pre>
<p>(Though note that this isn't that fully featured - it doesn't support <code>[a-z]</code> style glob patterns for instance, though this could probably be added). (The first <code>\*\*/</code> match is to cover cases like <code>\*\*/CVS</code> matching <code>./CVS</code>, as well as having just <code>\*\*</code> to match at the tail.)</p>
<p>However, obviously you don't want to recurse through everything below the current dir when not processing a <code>**</code> pattern, so I think you'll need a two-phase approach. I haven't tried implementing the below, and there are probably a few corner cases, but I think it should work:</p>
<ol>
<li><p>Split the pattern on your directory seperator. ie <code>pat.split('/') -> ['**','CVS','*']</code></p></li>
<li><p>Recurse through the directories, and look at the relevant part of the pattern for this level. ie. <code>n levels deep -> look at pat[n]</code>.</p></li>
<li><p>If <code>pat[n] == '**'</code> switch to the above strategy:</p>
<ul>
<li>Reconstruct the pattern with <code>dirsep.join(pat[n:])</code></li>
<li>Convert to a regex with <code>glob\_to\_regex()</code></li>
<li>Recursively <code>os.walk</code> through the current directory, building up the path relative to the level you started at. If the path matches the regex, yield it.</li>
</ul></li>
<li><p>If pat doesn't match <code>"**"</code>, and it is the last element in the pattern, then yield all files/dirs matching <code>glob.glob(os.path.join(curpath,pat[n]))</code></p></li>
<li><p>If pat doesn't match <code>"**"</code>, and it is NOT the last element in the pattern, then for each directory, check if it matches (with glob) <code>pat[n]</code>. If so, recurse down through it, incrementing depth (so it will look at <code>pat[n+1]</code>)</p></li>
</ol>
| 3 | 2008-10-02T16:07:32Z | [
"python",
"file",
"ant"
] |
How would you implement ant-style patternsets in python to select groups of files? | 161,755 | <p>Ant has a nice way to select groups of files, most handily using ** to indicate a directory tree. E.g.</p>
<pre><code>**/CVS/* # All files immediately under a CVS directory.
mydir/mysubdir/** # All files recursively under mysubdir
</code></pre>
<p>More examples can be seen here:</p>
<p><a href="http://ant.apache.org/manual/dirtasks.html" rel="nofollow">http://ant.apache.org/manual/dirtasks.html</a></p>
<p>How would you implement this in python, so that you could do something like:</p>
<pre><code>files = get_files("**/CVS/*")
for file in files:
print file
=>
CVS/Repository
mydir/mysubdir/CVS/Entries
mydir/mysubdir/foo/bar/CVS/Entries
</code></pre>
| 3 | 2008-10-02T11:00:56Z | 4,525,760 | <p>There's an implementation in the 'waf' build system source code.
<a href="http://code.google.com/p/waf/source/browse/trunk/waflib/Node.py?r=10755#471" rel="nofollow">http://code.google.com/p/waf/source/browse/trunk/waflib/Node.py?r=10755#471</a>
May be this should be wrapped up in a library of its own?</p>
| 1 | 2010-12-24T10:34:20Z | [
"python",
"file",
"ant"
] |
How would you implement ant-style patternsets in python to select groups of files? | 161,755 | <p>Ant has a nice way to select groups of files, most handily using ** to indicate a directory tree. E.g.</p>
<pre><code>**/CVS/* # All files immediately under a CVS directory.
mydir/mysubdir/** # All files recursively under mysubdir
</code></pre>
<p>More examples can be seen here:</p>
<p><a href="http://ant.apache.org/manual/dirtasks.html" rel="nofollow">http://ant.apache.org/manual/dirtasks.html</a></p>
<p>How would you implement this in python, so that you could do something like:</p>
<pre><code>files = get_files("**/CVS/*")
for file in files:
print file
=>
CVS/Repository
mydir/mysubdir/CVS/Entries
mydir/mysubdir/foo/bar/CVS/Entries
</code></pre>
| 3 | 2008-10-02T11:00:56Z | 10,597,029 | <p>Sorry, this is quite a long time after your OP. I have just released a Python package which does exactly this - it's called Formic and it's available at the <a href="http://pypi.python.org/pypi/formic" rel="nofollow">PyPI Cheeseshop</a>. With Formic, your problem is solved with:</p>
<pre><code>import formic
fileset = formic.FileSet(include="**/CVS/*", default_excludes=False)
for file_name in fileset.qualified_files():
print file_name
</code></pre>
<p>There is one slight complexity: default_excludes. Formic, just like Ant, excludes CVS directories by default (as for the most part collecting files from them for a build is dangerous), the default answer to the question would result in no files. Setting default_excludes=False disables this behaviour.</p>
| 4 | 2012-05-15T08:39:01Z | [
"python",
"file",
"ant"
] |
Interface to versioned dictionary | 162,656 | <p>I have an versioned document store which I want to access through an dict like interface.
Common usage is to access the latest revision (get, set, del), but one should be able to access specific revisions too (keys are always str/unicode or int).</p>
<pre><code>from UserDict import DictMixin
class VDict(DictMixin):
def __getitem__(self, key):
if isinstance(key, tuple):
docid, rev = key
else:
docid = key
rev = None # set to tip rev
print docid, rev
# return ...
In [1]: d = VDict()
In [2]: d[2]
2 None
In [3]: d[2, 1]
2 1
</code></pre>
<p>This solution is a little bit tricky and I'm not sure if it is a clean, understandable interface. Should I provide a function </p>
<pre><code>def getrev(self, docid, rev):
...
</code></pre>
<p>instead?</p>
| 1 | 2008-10-02T14:38:43Z | 162,707 | <p>Yes, provide a different API for getting different versions. Either a single methodcall for doing a retrieval of a particular item of a particular revision, or a methodcall for getting a 'view' of a particular revision, which you could then access like a normal dict, depending on whether such a 'view' would see much use. Or both, considering the dict-view solution would need some way to get a particular revision's item anyway:</p>
<pre><code>class RevisionView(object):
def __init__(self, db, revid):
self.db = db
self.revid = revid
def __getitem__(self, item):
self.db.getrev(item, self.revid)
</code></pre>
| 4 | 2008-10-02T14:46:31Z | [
"python"
] |
Subclassing a class with private members | 162,798 | <p>One of the really nice things about python is the simplicity with which you can name variables that have the same name as the accessor:</p>
<pre><code>self.__value = 1
def value():
return self.__value
</code></pre>
<p>Is there a simple way of providing access to the private members of a class that I wish to subclass? Often I wish to simply work with the raw data objects inside of a class without having to use accessors and mutators all the time.</p>
<p>I know this seems to go against the general idea of private and public, but usually the class I am trying to subclass is one of my own which I am quite happy to expose the members from to a subclass but not to an instance of that class. Is there a clean way of providing this distinction?</p>
| 1 | 2008-10-02T14:59:18Z | 162,854 | <p>Not conveniently, without further breaking encapsulation. The double-underscore attribute is name-mangled by prepending '_ClassName' for the class it is being accessed in. So, if you have a 'ContainerThing' class that has a '__value' attribute, the attribute is actually being stored as '<code>_ContainerThing__value</code>'. Changing the class name (or refactoring where the attribute is assigned to) would mean breaking all subclasses that try to access that attribute.</p>
<p>This is exactly why the double-underscore name-mangling (which is not really "private", just "inconvenient") is a bad idea to use. Just use a <em>single</em> leading underscore. Everyone will know not to touch your 'private' attribute and you will still be able to access it in subclasses and other situations where it's darned handy. The name-mangling of double-underscore attributes is useful only to avoid name-clashes for attributes that are truly specific to a particular class, which is extremely rare. It provides no extra 'security' since even the name-mangled attributes are trivially accessible.</p>
<p>For the record, '<code>__value</code>' and '<code>value</code>' (and '<code>_value</code>') are not the same name. The underscores are part of the name.</p>
| 5 | 2008-10-02T15:06:26Z | [
"python",
"oop",
"encapsulation"
] |
Subclassing a class with private members | 162,798 | <p>One of the really nice things about python is the simplicity with which you can name variables that have the same name as the accessor:</p>
<pre><code>self.__value = 1
def value():
return self.__value
</code></pre>
<p>Is there a simple way of providing access to the private members of a class that I wish to subclass? Often I wish to simply work with the raw data objects inside of a class without having to use accessors and mutators all the time.</p>
<p>I know this seems to go against the general idea of private and public, but usually the class I am trying to subclass is one of my own which I am quite happy to expose the members from to a subclass but not to an instance of that class. Is there a clean way of providing this distinction?</p>
| 1 | 2008-10-02T14:59:18Z | 163,571 | <p>Not sure of where to cite it from, but the following statement in regard to access protection is Pythonic canon: "We're all consenting adults here".</p>
<p>Just as Thomas Wouters has stated, a single leading underscore is the idiomatic way of marking an attribute as being a part of the object's internal state. Two underscores just provides name mangling to prevent easy access to the attribute.</p>
<p>After that, you should just expect that the client of your library won't go and shoot themselves in the foot by meddling with the "private" attributes.</p>
| 2 | 2008-10-02T17:32:12Z | [
"python",
"oop",
"encapsulation"
] |
Subclassing a class with private members | 162,798 | <p>One of the really nice things about python is the simplicity with which you can name variables that have the same name as the accessor:</p>
<pre><code>self.__value = 1
def value():
return self.__value
</code></pre>
<p>Is there a simple way of providing access to the private members of a class that I wish to subclass? Often I wish to simply work with the raw data objects inside of a class without having to use accessors and mutators all the time.</p>
<p>I know this seems to go against the general idea of private and public, but usually the class I am trying to subclass is one of my own which I am quite happy to expose the members from to a subclass but not to an instance of that class. Is there a clean way of providing this distinction?</p>
| 1 | 2008-10-02T14:59:18Z | 164,691 | <p>"I know this seems to go against the general idea of private and public" Not really "against", just different from C++ and Java.</p>
<p>Private -- as implemented in C++ and Java is not a very useful concept. It helps, sometimes, to isolate implementation details. But it is way overused.</p>
<p>Python names beginning with two <code>__</code> are special and you should not, as a normal thing, be defining attributes with names like this. Names with <code>__</code> are special and part of the implementation. And exposed for your use.</p>
<p>Names beginning with one <code>_</code> are "private". Sometimes they are concealed, a little. Most of the time, the "consenting adults" rule applies -- don't use them foolishly, they're subject to change without notice. </p>
<p>We put "private" in quotes because it's just an agreement between you and your users. You've marked things with <code>_</code>. Your users (and yourself) should honor that.</p>
<p>Often, we have method function names with a leading <code>_</code> to indicate that we consider them to be "private" and subject to change without notice.</p>
<p>The endless getters and setters that Java requires aren't as often used in Python. Python introspection is more flexible, you have access to an object's internal dictionary of attribute values, and you have first class <a href="http://docs.python.org/lib/built-in-funcs.html" rel="nofollow">functions</a> like <code>getattr()</code> and <code>setattr()</code>.</p>
<p>Further, you have the <code>property()</code> function which is often used to bind getters and setters to a single name that behaves like a simple attribute, but is actually well-defined method function calls.</p>
| 2 | 2008-10-02T21:28:20Z | [
"python",
"oop",
"encapsulation"
] |
Django and Python 2.6 | 162,808 | <p>I'm just starting to get into Django, and of course as of last night one of the two new Python versions went final (2.6 obviously ;)) so I'm wondering if 2.6 plus Django is ready for actual use or do the Django team need more time to finish with tweaks/cleanup? </p>
<p>All the google searches I did were inconclusive, I saw bits about some initial test runs on beta 2 but nothing more recent seemed to show up.</p>
<p>Edit: <a href="http://groups.google.com/group/django-developers/browse_thread/thread/a48f81d916f24a04" rel="nofollow">http://groups.google.com/group/django-developers/browse_thread/thread/a48f81d916f24a04</a></p>
<p>They've confirmed here 1.0 w/2.6 works fine as far as they know.</p>
| 5 | 2008-10-02T15:00:00Z | 163,163 | <p>The impression I get is that 2.6 should work fine with Django 1.0. As found here: <a href="http://simonwillison.net/2008/Oct/2/whatus/" rel="nofollow">http://simonwillison.net/2008/Oct/2/whatus/</a> </p>
| 7 | 2008-10-02T15:58:41Z | [
"python",
"django"
] |
Django and Python 2.6 | 162,808 | <p>I'm just starting to get into Django, and of course as of last night one of the two new Python versions went final (2.6 obviously ;)) so I'm wondering if 2.6 plus Django is ready for actual use or do the Django team need more time to finish with tweaks/cleanup? </p>
<p>All the google searches I did were inconclusive, I saw bits about some initial test runs on beta 2 but nothing more recent seemed to show up.</p>
<p>Edit: <a href="http://groups.google.com/group/django-developers/browse_thread/thread/a48f81d916f24a04" rel="nofollow">http://groups.google.com/group/django-developers/browse_thread/thread/a48f81d916f24a04</a></p>
<p>They've confirmed here 1.0 w/2.6 works fine as far as they know.</p>
| 5 | 2008-10-02T15:00:00Z | 249,483 | <p>Note that there is currently no python-mysql adapter for python2.6. If you need MySQL, stick with 2.5 for now.</p>
| 5 | 2008-10-30T07:23:45Z | [
"python",
"django"
] |
Django and Python 2.6 | 162,808 | <p>I'm just starting to get into Django, and of course as of last night one of the two new Python versions went final (2.6 obviously ;)) so I'm wondering if 2.6 plus Django is ready for actual use or do the Django team need more time to finish with tweaks/cleanup? </p>
<p>All the google searches I did were inconclusive, I saw bits about some initial test runs on beta 2 but nothing more recent seemed to show up.</p>
<p>Edit: <a href="http://groups.google.com/group/django-developers/browse_thread/thread/a48f81d916f24a04" rel="nofollow">http://groups.google.com/group/django-developers/browse_thread/thread/a48f81d916f24a04</a></p>
<p>They've confirmed here 1.0 w/2.6 works fine as far as they know.</p>
| 5 | 2008-10-02T15:00:00Z | 1,054,960 | <p>There is an unofficial build for mysqldb 1.2.2 win32 python 2.6 @ <a href="http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe" rel="nofollow">http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe</a></p>
| 2 | 2009-06-28T13:45:33Z | [
"python",
"django"
] |
urllib2 file name | 163,009 | <p>If I open a file using urllib2, like so:</p>
<pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip')
</code></pre>
<p>Is there an easy way to get the file name other then parsing the original URL?</p>
<p>EDIT: changed openfile to urlopen... not sure how that happened.</p>
<p>EDIT2: I ended up using:</p>
<pre><code>filename = url.split('/')[-1].split('#')[0].split('?')[0]
</code></pre>
<p>Unless I'm mistaken, this should strip out all potential queries as well.</p>
| 24 | 2008-10-02T15:27:04Z | 163,093 | <p>Do you mean <code>urllib2.urlopen</code>? There is no function called <code>openfile</code> in the <code>urllib2</code> module.</p>
<p>Anyway, use the <code>urllib2.urlparse</code> functions:</p>
<pre><code>>>> from urllib2 import urlparse
>>> print urlparse.urlsplit('http://example.com/somefile.zip')
('http', 'example.com', '/somefile.zip', '', '')
</code></pre>
<p>Voila.</p>
| 2 | 2008-10-02T15:42:59Z | [
"python",
"url",
"urllib2"
] |
urllib2 file name | 163,009 | <p>If I open a file using urllib2, like so:</p>
<pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip')
</code></pre>
<p>Is there an easy way to get the file name other then parsing the original URL?</p>
<p>EDIT: changed openfile to urlopen... not sure how that happened.</p>
<p>EDIT2: I ended up using:</p>
<pre><code>filename = url.split('/')[-1].split('#')[0].split('?')[0]
</code></pre>
<p>Unless I'm mistaken, this should strip out all potential queries as well.</p>
| 24 | 2008-10-02T15:27:04Z | 163,094 | <p>I think that "the file name" isn't a very well defined concept when it comes to http transfers. The server might (but is not required to) provide one as "content-disposition" header, you can try to get that with <code>remotefile.headers['Content-Disposition']</code>. If this fails, you probably have to parse the URI yourself.</p>
| 6 | 2008-10-02T15:43:10Z | [
"python",
"url",
"urllib2"
] |
urllib2 file name | 163,009 | <p>If I open a file using urllib2, like so:</p>
<pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip')
</code></pre>
<p>Is there an easy way to get the file name other then parsing the original URL?</p>
<p>EDIT: changed openfile to urlopen... not sure how that happened.</p>
<p>EDIT2: I ended up using:</p>
<pre><code>filename = url.split('/')[-1].split('#')[0].split('?')[0]
</code></pre>
<p>Unless I'm mistaken, this should strip out all potential queries as well.</p>
| 24 | 2008-10-02T15:27:04Z | 163,095 | <p>Did you mean <a href="http://www.python.org/doc/2.5.2/lib/module-urllib2.html#l2h-3928">urllib2.urlopen</a>?</p>
<p>You could potentially lift the <em>intended</em> filename <em>if</em> the server was sending a Content-Disposition header by checking <code>remotefile.info()['Content-Disposition']</code>, but as it is I think you'll just have to parse the url.</p>
<p>You could use <code>urlparse.urlsplit</code>, but if you have any URLs like at the second example, you'll end up having to pull the file name out yourself anyway:</p>
<pre><code>>>> urlparse.urlsplit('http://example.com/somefile.zip')
('http', 'example.com', '/somefile.zip', '', '')
>>> urlparse.urlsplit('http://example.com/somedir/somefile.zip')
('http', 'example.com', '/somedir/somefile.zip', '', '')
</code></pre>
<p>Might as well just do this:</p>
<pre><code>>>> 'http://example.com/somefile.zip'.split('/')[-1]
'somefile.zip'
>>> 'http://example.com/somedir/somefile.zip'.split('/')[-1]
'somefile.zip'
</code></pre>
| 37 | 2008-10-02T15:43:12Z | [
"python",
"url",
"urllib2"
] |
urllib2 file name | 163,009 | <p>If I open a file using urllib2, like so:</p>
<pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip')
</code></pre>
<p>Is there an easy way to get the file name other then parsing the original URL?</p>
<p>EDIT: changed openfile to urlopen... not sure how that happened.</p>
<p>EDIT2: I ended up using:</p>
<pre><code>filename = url.split('/')[-1].split('#')[0].split('?')[0]
</code></pre>
<p>Unless I'm mistaken, this should strip out all potential queries as well.</p>
| 24 | 2008-10-02T15:27:04Z | 163,107 | <p>I guess it depends what you mean by parsing. There is no way to get the filename without parsing the URL, i.e. the remote server doesn't give you a filename. However, you don't have to do much yourself, there's the <code>urlparse</code> module:</p>
<pre><code>In [9]: urlparse.urlparse('http://example.com/somefile.zip')
Out[9]: ('http', 'example.com', '/somefile.zip', '', '', '')
</code></pre>
| 1 | 2008-10-02T15:45:47Z | [
"python",
"url",
"urllib2"
] |
urllib2 file name | 163,009 | <p>If I open a file using urllib2, like so:</p>
<pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip')
</code></pre>
<p>Is there an easy way to get the file name other then parsing the original URL?</p>
<p>EDIT: changed openfile to urlopen... not sure how that happened.</p>
<p>EDIT2: I ended up using:</p>
<pre><code>filename = url.split('/')[-1].split('#')[0].split('?')[0]
</code></pre>
<p>Unless I'm mistaken, this should strip out all potential queries as well.</p>
| 24 | 2008-10-02T15:27:04Z | 163,108 | <pre><code>import os,urllib2
resp = urllib2.urlopen('http://www.example.com/index.html')
my_url = resp.geturl()
os.path.split(my_url)[1]
# 'index.html'
</code></pre>
<p>This is not openfile, but maybe still helps :)</p>
| 0 | 2008-10-02T15:45:48Z | [
"python",
"url",
"urllib2"
] |
urllib2 file name | 163,009 | <p>If I open a file using urllib2, like so:</p>
<pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip')
</code></pre>
<p>Is there an easy way to get the file name other then parsing the original URL?</p>
<p>EDIT: changed openfile to urlopen... not sure how that happened.</p>
<p>EDIT2: I ended up using:</p>
<pre><code>filename = url.split('/')[-1].split('#')[0].split('?')[0]
</code></pre>
<p>Unless I'm mistaken, this should strip out all potential queries as well.</p>
| 24 | 2008-10-02T15:27:04Z | 163,111 | <p>not that I know of.</p>
<p>but you can parse it easy enough like this:</p>
<p><code><pre>
<code>url = '<a href="http://example.com/somefile.zip" rel="nofollow">http://example.com/somefile.zip</a>'
</code>print url.split('/')[-1]
</pre></code></p>
| 1 | 2008-10-02T15:46:49Z | [
"python",
"url",
"urllib2"
] |
urllib2 file name | 163,009 | <p>If I open a file using urllib2, like so:</p>
<pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip')
</code></pre>
<p>Is there an easy way to get the file name other then parsing the original URL?</p>
<p>EDIT: changed openfile to urlopen... not sure how that happened.</p>
<p>EDIT2: I ended up using:</p>
<pre><code>filename = url.split('/')[-1].split('#')[0].split('?')[0]
</code></pre>
<p>Unless I'm mistaken, this should strip out all potential queries as well.</p>
| 24 | 2008-10-02T15:27:04Z | 163,202 | <p>If you only want the file name itself, assuming that there's no query variables at the end like <a href="http://example.com/somedir/somefile.zip?foo=bar">http://example.com/somedir/somefile.zip?foo=bar</a> then you can use os.path.basename for this: </p>
<pre><code>[user@host]$ python
Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04)
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.basename("http://example.com/somefile.zip")
'somefile.zip'
>>> os.path.basename("http://example.com/somedir/somefile.zip")
'somefile.zip'
>>> os.path.basename("http://example.com/somedir/somefile.zip?foo=bar")
'somefile.zip?foo=bar'
</code></pre>
<p>Some other posters mentioned using urlparse, which will work, but you'd still need to strip the leading directory from the file name. If you use os.path.basename() then you don't have to worry about that, since it returns only the final part of the URL or file path.</p>
| 10 | 2008-10-02T16:06:16Z | [
"python",
"url",
"urllib2"
] |
urllib2 file name | 163,009 | <p>If I open a file using urllib2, like so:</p>
<pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip')
</code></pre>
<p>Is there an easy way to get the file name other then parsing the original URL?</p>
<p>EDIT: changed openfile to urlopen... not sure how that happened.</p>
<p>EDIT2: I ended up using:</p>
<pre><code>filename = url.split('/')[-1].split('#')[0].split('?')[0]
</code></pre>
<p>Unless I'm mistaken, this should strip out all potential queries as well.</p>
| 24 | 2008-10-02T15:27:04Z | 15,733,928 | <p>Using <code>urlsplit</code> is the safest option:</p>
<pre><code>url = 'http://example.com/somefile.zip'
urlparse.urlsplit(url).path.split('/')[-1]
</code></pre>
| 4 | 2013-03-31T20:05:36Z | [
"python",
"url",
"urllib2"
] |
urllib2 file name | 163,009 | <p>If I open a file using urllib2, like so:</p>
<pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip')
</code></pre>
<p>Is there an easy way to get the file name other then parsing the original URL?</p>
<p>EDIT: changed openfile to urlopen... not sure how that happened.</p>
<p>EDIT2: I ended up using:</p>
<pre><code>filename = url.split('/')[-1].split('#')[0].split('?')[0]
</code></pre>
<p>Unless I'm mistaken, this should strip out all potential queries as well.</p>
| 24 | 2008-10-02T15:27:04Z | 22,053,032 | <p>using requests, but you can do it easy with urllib(2)</p>
<pre><code>import requests
from urllib import unquote
from urlparse import urlparse
sample = requests.get(url)
if sample.status_code == 200:
#has_key not work here, and this help avoid problem with names
if filename == False:
if 'content-disposition' in sample.headers.keys():
filename = sample.headers['content-disposition'].split('filename=')[-1].replace('"','').replace(';','')
else:
filename = urlparse(sample.url).query.split('/')[-1].split('=')[-1].split('&')[-1]
if not filename:
if url.split('/')[-1] != '':
filename = sample.url.split('/')[-1].split('=')[-1].split('&')[-1]
filename = unquote(filename)
</code></pre>
| 0 | 2014-02-26T20:54:44Z | [
"python",
"url",
"urllib2"
] |
urllib2 file name | 163,009 | <p>If I open a file using urllib2, like so:</p>
<pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip')
</code></pre>
<p>Is there an easy way to get the file name other then parsing the original URL?</p>
<p>EDIT: changed openfile to urlopen... not sure how that happened.</p>
<p>EDIT2: I ended up using:</p>
<pre><code>filename = url.split('/')[-1].split('#')[0].split('?')[0]
</code></pre>
<p>Unless I'm mistaken, this should strip out all potential queries as well.</p>
| 24 | 2008-10-02T15:27:04Z | 29,173,617 | <p>Just saw this I normally do..</p>
<pre><code>filename = url.split("?")[0].split("/")[-1]
</code></pre>
| 3 | 2015-03-20T18:38:47Z | [
"python",
"url",
"urllib2"
] |
urllib2 file name | 163,009 | <p>If I open a file using urllib2, like so:</p>
<pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip')
</code></pre>
<p>Is there an easy way to get the file name other then parsing the original URL?</p>
<p>EDIT: changed openfile to urlopen... not sure how that happened.</p>
<p>EDIT2: I ended up using:</p>
<pre><code>filename = url.split('/')[-1].split('#')[0].split('?')[0]
</code></pre>
<p>Unless I'm mistaken, this should strip out all potential queries as well.</p>
| 24 | 2008-10-02T15:27:04Z | 30,160,719 | <p>The <code>os.path.basename</code> function works not only for file paths, but also for urls, so you don't have to manually parse the URL yourself. Also, it's important to note that you should use <code>result.url</code> instead of the original url in order to follow redirect responses:</p>
<pre><code>import os
import urllib2
result = urllib2.urlopen(url)
real_url = urllib2.urlparse.urlparse(result.url)
filename = os.path.basename(real_url.path)
</code></pre>
| 2 | 2015-05-11T06:15:24Z | [
"python",
"url",
"urllib2"
] |
urllib2 file name | 163,009 | <p>If I open a file using urllib2, like so:</p>
<pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip')
</code></pre>
<p>Is there an easy way to get the file name other then parsing the original URL?</p>
<p>EDIT: changed openfile to urlopen... not sure how that happened.</p>
<p>EDIT2: I ended up using:</p>
<pre><code>filename = url.split('/')[-1].split('#')[0].split('?')[0]
</code></pre>
<p>Unless I'm mistaken, this should strip out all potential queries as well.</p>
| 24 | 2008-10-02T15:27:04Z | 32,512,647 | <p>You probably can use simple regular expression here. Something like:</p>
<pre><code>In [26]: import re
In [27]: pat = re.compile('.+[\/\?#=]([\w-]+\.[\w-]+(?:\.[\w-]+)?$)')
In [28]: test_set
['http://www.google.com/a341.tar.gz',
'http://www.google.com/a341.gz',
'http://www.google.com/asdasd/aadssd.gz',
'http://www.google.com/asdasd?aadssd.gz',
'http://www.google.com/asdasd#blah.gz',
'http://www.google.com/asdasd?filename=xxxbl.gz']
In [30]: for url in test_set:
....: match = pat.match(url)
....: if match and match.groups():
....: print(match.groups()[0])
....:
a341.tar.gz
a341.gz
aadssd.gz
aadssd.gz
blah.gz
xxxbl.gz
</code></pre>
| 0 | 2015-09-10T22:31:37Z | [
"python",
"url",
"urllib2"
] |
urllib2 file name | 163,009 | <p>If I open a file using urllib2, like so:</p>
<pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip')
</code></pre>
<p>Is there an easy way to get the file name other then parsing the original URL?</p>
<p>EDIT: changed openfile to urlopen... not sure how that happened.</p>
<p>EDIT2: I ended up using:</p>
<pre><code>filename = url.split('/')[-1].split('#')[0].split('?')[0]
</code></pre>
<p>Unless I'm mistaken, this should strip out all potential queries as well.</p>
| 24 | 2008-10-02T15:27:04Z | 36,557,581 | <p>Using <a href="https://docs.python.org/3/library/pathlib.html#pathlib.PurePosixPath" rel="nofollow">PurePosixPath</a> which is not operating systemâdependent and handles urls gracefully is the pythonic solution:</p>
<pre><code>>>> from pathlib import PurePosixPath
>>> path = PurePosixPath('http://example.com/somefile.zip')
>>> path.name
'somefile.zip'
>>> path = PurePosixPath('http://example.com/nested/somefile.zip')
>>> path.name
'somefile.zip'
</code></pre>
<p>Notice how there is no network traffic here or anything (i.e. those urls don't go anywhere) - just using standard parsing rules.</p>
| 0 | 2016-04-11T19:28:35Z | [
"python",
"url",
"urllib2"
] |
urllib2 file name | 163,009 | <p>If I open a file using urllib2, like so:</p>
<pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip')
</code></pre>
<p>Is there an easy way to get the file name other then parsing the original URL?</p>
<p>EDIT: changed openfile to urlopen... not sure how that happened.</p>
<p>EDIT2: I ended up using:</p>
<pre><code>filename = url.split('/')[-1].split('#')[0].split('?')[0]
</code></pre>
<p>Unless I'm mistaken, this should strip out all potential queries as well.</p>
| 24 | 2008-10-02T15:27:04Z | 36,917,997 | <p>You could also combine both of the two best-rated answers :
Using urllib2.urlparse.urlsplit() to get the path part of the URL, and then os.path.basename for the actual file name.</p>
<p>Full code would be :</p>
<pre><code>>>> remotefile=urllib2.urlopen(url)
>>> try:
>>> filename=remotefile.info()['Content-Disposition']
>>> except KeyError:
>>> filename=os.path.basename(urllib2.urlparse.urlsplit(url).path)
</code></pre>
| 0 | 2016-04-28T14:41:39Z | [
"python",
"url",
"urllib2"
] |
Python - How do I pass a string into subprocess.Popen (using the stdin argument)? | 163,542 | <p>If I do the following:</p>
<pre><code>import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]
</code></pre>
<p>I get:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
(p2cread, p2cwrite,
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'
</code></pre>
<p>Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen. How do I work around this?</p>
| 175 | 2008-10-02T17:25:23Z | 163,556 | <p>I figured out this workaround:</p>
<pre><code>>>> p = subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
>>> p.stdin.write('one\ntwo\nthree\nfour\nfive\nsix\n')
>>> p.communicate()[0]
'four\nfive\n'
>>> p.stdin.close()
</code></pre>
<p>Is there a better one?</p>
| 21 | 2008-10-02T17:27:55Z | [
"python",
"subprocess",
"stdin"
] |
Python - How do I pass a string into subprocess.Popen (using the stdin argument)? | 163,542 | <p>If I do the following:</p>
<pre><code>import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]
</code></pre>
<p>I get:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
(p2cread, p2cwrite,
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'
</code></pre>
<p>Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen. How do I work around this?</p>
| 175 | 2008-10-02T17:25:23Z | 163,870 | <p>"Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen"</p>
<p>:-)</p>
<p>I'm afraid not. The pipe is a low-level OS concept, so it absolutely requires a file object that is represented by an OS-level file descriptor. Your workaround is the right one.</p>
| 12 | 2008-10-02T18:33:23Z | [
"python",
"subprocess",
"stdin"
] |
Python - How do I pass a string into subprocess.Popen (using the stdin argument)? | 163,542 | <p>If I do the following:</p>
<pre><code>import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]
</code></pre>
<p>I get:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
(p2cread, p2cwrite,
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'
</code></pre>
<p>Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen. How do I work around this?</p>
| 175 | 2008-10-02T17:25:23Z | 165,662 | <p><a href="https://docs.python.org/3/library/subprocess.html?highlight=subprocess#subprocess.Popen.communicate"><code>Popen.communicate()</code></a> documentation:</p>
<blockquote>
<p>Note that if you want to send data to
the processâs stdin, you need to
create the Popen object with
stdin=PIPE. Similarly, to get anything
other than None in the result tuple,
you need to give stdout=PIPE and/or
stderr=PIPE too.</p>
<p><strong>Replacing os.popen*</strong></p>
</blockquote>
<pre><code> pipe = os.popen(cmd, 'w', bufsize)
# ==>
pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
</code></pre>
<blockquote>
<p><strong>Warning</strong> Use communicate() rather than
stdin.write(), stdout.read() or
stderr.read() to avoid deadlocks due
to any of the other OS pipe buffers
filling up and blocking the child
process.</p>
</blockquote>
<p>So your example could be written as follows:</p>
<pre><code>from subprocess import Popen, PIPE, STDOUT
p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0]
print(grep_stdout.decode())
# -> four
# -> five
# ->
</code></pre>
| 194 | 2008-10-03T04:11:07Z | [
"python",
"subprocess",
"stdin"
] |
Python - How do I pass a string into subprocess.Popen (using the stdin argument)? | 163,542 | <p>If I do the following:</p>
<pre><code>import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]
</code></pre>
<p>I get:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
(p2cread, p2cwrite,
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'
</code></pre>
<p>Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen. How do I work around this?</p>
| 175 | 2008-10-02T17:25:23Z | 732,822 | <pre><code>p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
p.stdin.write('one\n')
time.sleep(0.5)
p.stdin.write('two\n')
time.sleep(0.5)
p.stdin.write('three\n')
time.sleep(0.5)
testresult = p.communicate()[0]
time.sleep(0.5)
print(testresult)
</code></pre>
| 2 | 2009-04-09T04:39:40Z | [
"python",
"subprocess",
"stdin"
] |
Python - How do I pass a string into subprocess.Popen (using the stdin argument)? | 163,542 | <p>If I do the following:</p>
<pre><code>import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]
</code></pre>
<p>I get:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
(p2cread, p2cwrite,
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'
</code></pre>
<p>Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen. How do I work around this?</p>
| 175 | 2008-10-02T17:25:23Z | 10,134,899 | <pre><code>from subprocess import Popen, PIPE
from tempfile import SpooledTemporaryFile as tempfile
f = tempfile()
f.write('one\ntwo\nthree\nfour\nfive\nsix\n')
f.seek(0)
print Popen(['/bin/grep','f'],stdout=PIPE,stdin=f).stdout.read()
f.close()
</code></pre>
| 7 | 2012-04-13T03:36:37Z | [
"python",
"subprocess",
"stdin"
] |
Python - How do I pass a string into subprocess.Popen (using the stdin argument)? | 163,542 | <p>If I do the following:</p>
<pre><code>import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]
</code></pre>
<p>I get:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
(p2cread, p2cwrite,
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'
</code></pre>
<p>Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen. How do I work around this?</p>
| 175 | 2008-10-02T17:25:23Z | 17,109,481 | <pre><code>"""
Ex: Dialog (2-way) with a Popen()
"""
p = subprocess.Popen('Your Command Here',
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=PIPE,
shell=True,
bufsize=0)
p.stdin.write('START\n')
out = p.stdout.readline()
while out:
line = out
line = line.rstrip("\n")
if "WHATEVER1" in line:
pr = 1
p.stdin.write('DO 1\n')
out = p.stdout.readline()
continue
if "WHATEVER2" in line:
pr = 2
p.stdin.write('DO 2\n')
out = p.stdout.readline()
continue
"""
..........
"""
out = p.stdout.readline()
p.wait()
</code></pre>
| 4 | 2013-06-14T13:20:23Z | [
"python",
"subprocess",
"stdin"
] |
Python - How do I pass a string into subprocess.Popen (using the stdin argument)? | 163,542 | <p>If I do the following:</p>
<pre><code>import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]
</code></pre>
<p>I get:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
(p2cread, p2cwrite,
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'
</code></pre>
<p>Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen. How do I work around this?</p>
| 175 | 2008-10-02T17:25:23Z | 23,740,991 | <p>Beware that <code>Popen.communicate(input=s)</code>may give you trouble if<code>s</code>is too big, because apparently the parent process will buffer it <em>before</em> forking the child subprocess, meaning it needs "twice as much" used memory at that point (at least according to the "under the hood" explanation and linked documentation found <a href="http://stackoverflow.com/a/13329386/2426246">here</a>). In my particular case,<code>s</code>was a generator that was first fully expanded and only then written to<code>stdin</code> so the parent process was huge right before the child was spawned,
and no memory was left to fork it:</p>
<p><code>File "/opt/local/stow/python-2.7.2/lib/python2.7/subprocess.py", line 1130, in _execute_child
self.pid = os.fork()
OSError: [Errno 12] Cannot allocate memory</code></p>
| 4 | 2014-05-19T14:56:38Z | [
"python",
"subprocess",
"stdin"
] |
Python - How do I pass a string into subprocess.Popen (using the stdin argument)? | 163,542 | <p>If I do the following:</p>
<pre><code>import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]
</code></pre>
<p>I get:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
(p2cread, p2cwrite,
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'
</code></pre>
<p>Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen. How do I work around this?</p>
| 175 | 2008-10-02T17:25:23Z | 24,982,453 | <p>I am using python3 and found out that you need to encode your string before you can pass it into stdin:</p>
<pre><code>p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
out, err = p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n'.encode())
print(out)
</code></pre>
| 12 | 2014-07-27T15:29:17Z | [
"python",
"subprocess",
"stdin"
] |
Python - How do I pass a string into subprocess.Popen (using the stdin argument)? | 163,542 | <p>If I do the following:</p>
<pre><code>import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]
</code></pre>
<p>I get:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
(p2cread, p2cwrite,
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'
</code></pre>
<p>Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen. How do I work around this?</p>
| 175 | 2008-10-02T17:25:23Z | 33,482,438 | <p>I'm a bit surprised nobody suggested creating a pipe, which is in my opinion the far simplest way to pass a string to stdin of a subprocess:</p>
<pre><code>read, write = os.pipe()
os.write(write, "stdin input here")
os.close(write)
subprocess.check_call(['your-command'], stdin=read)
</code></pre>
| 9 | 2015-11-02T16:34:03Z | [
"python",
"subprocess",
"stdin"
] |
Apache sockets not closing? | 163,603 | <p>I have a web application written using CherryPy, which is run locally on <code>127.0.0.1:4321</code>. We use mod-rewrite and mod-proxy to have Apache act as a reverse proxy; Apache also handles our SSL encryption and may eventually be used to transfer all of our static content.</p>
<p>This all works just fine for small workloads. However, I recently used <code>urllib2</code> to write a stress-testing script that would simulate a workload of 100 clients. After some time, each client gets a 503 error from Apache, indicating that Apache cannot connect to <code>127.0.0.1:4321</code>. CherryPy is functioning properly, but my Apache error log reveals lines like the following:</p>
<p><code>[Thu Oct 02 12:55:44 2008] [error] (OS 10048)Only one usage of each socket address (protocol/network address/port) is normally permitted. : proxy: HTTP: attempt to connect to 127.0.0.1:4321 (*) failed</code></p>
<p>Googling for this error reveals that Apache has probably run out of socket file descriptors. Since I only have 100 clients running, this implies that the connections are not being closed, either between my <code>urllib2</code> connection and Apache (I am definitely calling <code>.close()</code> on the return value of <code>urlopen</code>), or between Apache and CherryPy.</p>
<p>I've confirmed that my <code>urllib2</code> request is sending an HTTP <code>Connection: close</code> header, although Apache is configured with <code>KeepAlive On</code> if that matters.</p>
<p>In case it matters, I'm using Python 2.5, Apache 2.2, CherryPy 3.0.3, and the server is running on Windows Server 2003.</p>
<p>So what's my next step to stop this problem?</p>
| 4 | 2008-10-02T17:40:38Z | 164,293 | <p>You might run the netstat command and see if you have a bunch of sockets in the TIME_WAIT state. Depending on your MaxUserPort setting you might be severly limited in the number of ports available to use. In addition the TcpTimedWaitDelay is usually set to 240 seconds so any sockets that are used cannot be reused for four minutes.</p>
<p>There's more good information here --> <a href="http://smallvoid.com/article/winnt-tcpip-max-limit.html">http://smallvoid.com/article/winnt-tcpip-max-limit.html</a></p>
| 5 | 2008-10-02T20:02:22Z | [
"python",
"apache",
"urllib2",
"cherrypy",
"mod-proxy"
] |
Apache sockets not closing? | 163,603 | <p>I have a web application written using CherryPy, which is run locally on <code>127.0.0.1:4321</code>. We use mod-rewrite and mod-proxy to have Apache act as a reverse proxy; Apache also handles our SSL encryption and may eventually be used to transfer all of our static content.</p>
<p>This all works just fine for small workloads. However, I recently used <code>urllib2</code> to write a stress-testing script that would simulate a workload of 100 clients. After some time, each client gets a 503 error from Apache, indicating that Apache cannot connect to <code>127.0.0.1:4321</code>. CherryPy is functioning properly, but my Apache error log reveals lines like the following:</p>
<p><code>[Thu Oct 02 12:55:44 2008] [error] (OS 10048)Only one usage of each socket address (protocol/network address/port) is normally permitted. : proxy: HTTP: attempt to connect to 127.0.0.1:4321 (*) failed</code></p>
<p>Googling for this error reveals that Apache has probably run out of socket file descriptors. Since I only have 100 clients running, this implies that the connections are not being closed, either between my <code>urllib2</code> connection and Apache (I am definitely calling <code>.close()</code> on the return value of <code>urlopen</code>), or between Apache and CherryPy.</p>
<p>I've confirmed that my <code>urllib2</code> request is sending an HTTP <code>Connection: close</code> header, although Apache is configured with <code>KeepAlive On</code> if that matters.</p>
<p>In case it matters, I'm using Python 2.5, Apache 2.2, CherryPy 3.0.3, and the server is running on Windows Server 2003.</p>
<p>So what's my next step to stop this problem?</p>
| 4 | 2008-10-02T17:40:38Z | 164,769 | <p><code>SetEnv proxy-nokeepalive 1</code> would probably tell you right away if the problem is keepalive between Apache and CP. See the <a href="http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#envsettings">mod_proxy docs</a> for more info.</p>
| 5 | 2008-10-02T21:52:03Z | [
"python",
"apache",
"urllib2",
"cherrypy",
"mod-proxy"
] |
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields? | 163,823 | <p>I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField).</p>
<p>With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display". I've tried all of the obvious methods for doing so (see below), but nothing seems to work. Any suggestions?</p>
<pre><code>class PersonAdmin(admin.ModelAdmin):
list_display = ['book.author',]
</code></pre>
| 150 | 2008-10-02T18:26:19Z | 163,968 | <p>According to the documentation, you can only display the <code>__unicode__</code> representation of a ForeignKey:</p>
<p><a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#list-display">http://docs.djangoproject.com/en/dev/ref/contrib/admin/#list-display</a></p>
<p>Seems odd that it doesn't support the <code>'book__author'</code> style format which is used everywhere else in the DB API.</p>
<p>Turns out there's <a href="http://code.djangoproject.com/ticket/5863">a ticket for this feature</a>, which is marked as Won't Fix.</p>
| 19 | 2008-10-02T18:53:23Z | [
"python",
"django",
"django-admin",
"modeladmin"
] |
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields? | 163,823 | <p>I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField).</p>
<p>With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display". I've tried all of the obvious methods for doing so (see below), but nothing seems to work. Any suggestions?</p>
<pre><code>class PersonAdmin(admin.ModelAdmin):
list_display = ['book.author',]
</code></pre>
| 150 | 2008-10-02T18:26:19Z | 164,631 | <p>As another option, you can do look ups like:</p>
<pre><code>class UserAdmin(admin.ModelAdmin):
list_display = (..., 'get_author')
def get_author(self, obj):
return obj.book.author
get_author.short_description = 'Author'
get_author.admin_order_field = 'book__author'
</code></pre>
| 240 | 2008-10-02T21:11:56Z | [
"python",
"django",
"django-admin",
"modeladmin"
] |
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields? | 163,823 | <p>I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField).</p>
<p>With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display". I've tried all of the obvious methods for doing so (see below), but nothing seems to work. Any suggestions?</p>
<pre><code>class PersonAdmin(admin.ModelAdmin):
list_display = ['book.author',]
</code></pre>
| 150 | 2008-10-02T18:26:19Z | 475,086 | <p>This one's already accepted, but if there are any other dummies out there (like me) that didn't immediately get it from the <a href="http://stackoverflow.com/a/164631/58668">presently accepted answer</a>, here's a bit more detail. </p>
<p>The model class referenced by the <code>ForeignKey</code> needs to have a <code>__unicode__</code> method within it, like here: </p>
<pre><code>class Category(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
</code></pre>
<p>That made the difference for me, and should apply to the above scenario. This works on Django 1.0.2.</p>
| 4 | 2009-01-23T23:40:30Z | [
"python",
"django",
"django-admin",
"modeladmin"
] |
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields? | 163,823 | <p>I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField).</p>
<p>With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display". I've tried all of the obvious methods for doing so (see below), but nothing seems to work. Any suggestions?</p>
<pre><code>class PersonAdmin(admin.ModelAdmin):
list_display = ['book.author',]
</code></pre>
| 150 | 2008-10-02T18:26:19Z | 496,453 | <p>You can show whatever you want in list display by using a callable. It would look like this:</p>
<pre>
def book_author(object):
return object.book.author
class PersonAdmin(admin.ModelAdmin):
list_display = [book_author,]</pre>
| 9 | 2009-01-30T17:41:43Z | [
"python",
"django",
"django-admin",
"modeladmin"
] |
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields? | 163,823 | <p>I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField).</p>
<p>With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display". I've tried all of the obvious methods for doing so (see below), but nothing seems to work. Any suggestions?</p>
<pre><code>class PersonAdmin(admin.ModelAdmin):
list_display = ['book.author',]
</code></pre>
| 150 | 2008-10-02T18:26:19Z | 679,791 | <p>AlexRobbins' answer worked for me, except that the first two lines need to be in the model (perhaps this was assumed?), and should reference self:</p>
<pre><code>def book_author(self):
return self.book.author
</code></pre>
<p>Then the admin part works nicely.</p>
| 0 | 2009-03-25T00:27:08Z | [
"python",
"django",
"django-admin",
"modeladmin"
] |
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields? | 163,823 | <p>I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField).</p>
<p>With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display". I've tried all of the obvious methods for doing so (see below), but nothing seems to work. Any suggestions?</p>
<pre><code>class PersonAdmin(admin.ModelAdmin):
list_display = ['book.author',]
</code></pre>
| 150 | 2008-10-02T18:26:19Z | 3,351,431 | <p>Like the rest, I went with callables too. But they have one downside: by default, you can't order on them. Fortunately, there is a solution for that:</p>
<pre><code>def author(self):
return self.book.author
author.admin_order_field = 'book__author'
</code></pre>
| 51 | 2010-07-28T09:13:55Z | [
"python",
"django",
"django-admin",
"modeladmin"
] |
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields? | 163,823 | <p>I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField).</p>
<p>With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display". I've tried all of the obvious methods for doing so (see below), but nothing seems to work. Any suggestions?</p>
<pre><code>class PersonAdmin(admin.ModelAdmin):
list_display = ['book.author',]
</code></pre>
| 150 | 2008-10-02T18:26:19Z | 14,677,451 | <p>I just posted a snippet that makes admin.ModelAdmin support '__' syntax:</p>
<p><a href="http://djangosnippets.org/snippets/2887/">http://djangosnippets.org/snippets/2887/</a></p>
<p>So you can do:</p>
<pre><code>class PersonAdmin(RelatedFieldAdmin):
list_display = ['book__author',]
</code></pre>
<p>This is basically just doing the same thing described in the other answers, but it automatically takes care of (1) setting admin_order_field (2) setting short_description and (3) modifying the queryset to avoid a database hit for each row.</p>
| 9 | 2013-02-03T21:21:58Z | [
"python",
"django",
"django-admin",
"modeladmin"
] |
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields? | 163,823 | <p>I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField).</p>
<p>With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display". I've tried all of the obvious methods for doing so (see below), but nothing seems to work. Any suggestions?</p>
<pre><code>class PersonAdmin(admin.ModelAdmin):
list_display = ['book.author',]
</code></pre>
| 150 | 2008-10-02T18:26:19Z | 21,456,615 | <p>if you try it in Inline, you wont succeed unless:</p>
<p>in your inline:</p>
<pre><code>class AddInline(admin.TabularInline):
readonly_fields = ['localname',]
model = MyModel
fields = ('localname',)
</code></pre>
<p>in your model (MyModel):</p>
<pre><code>class MyModel(models.Model):
localization = models.ForeignKey(Localizations)
def localname(self):
return self.localization.name
</code></pre>
| 2 | 2014-01-30T12:30:33Z | [
"python",
"django",
"django-admin",
"modeladmin"
] |
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields? | 163,823 | <p>I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField).</p>
<p>With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display". I've tried all of the obvious methods for doing so (see below), but nothing seems to work. Any suggestions?</p>
<pre><code>class PersonAdmin(admin.ModelAdmin):
list_display = ['book.author',]
</code></pre>
| 150 | 2008-10-02T18:26:19Z | 23,747,842 | <p>Despite all the great answers above and due to me being new to Django, I was still stuck. Here's my explanation from a very newbie perspective.</p>
<p><strong>models.py</strong></p>
<pre><code>class Author(models.Model):
name = models.CharField(max_length=255)
class Book(models.Model):
author = models.ForeignKey(Author)
title = models.CharField(max_length=255)
</code></pre>
<p><strong>admin.py (Incorrect Way)</strong> - you think it would work by using 'model__field' to reference, but it doesn't</p>
<pre><code>class BookAdmin(admin.ModelAdmin):
model = Book
list_display = ['title', 'author__name', ]
admin.site.register(Book, BookAdmin)
</code></pre>
<p><strong>admin.py (Correct Way)</strong> - this is how you reference a foreign key name the Django way</p>
<pre><code>class BookAdmin(admin.ModelAdmin):
model = Book
list_display = ['title', 'get_name', ]
def get_name(self, obj):
return obj.author.name
get_name.admin_order_field = 'author' #Allows column order sorting
get_name.short_description = 'Author Name' #Renames column head
#Filtering on side - for some reason, this works
#list_filter = ['title', 'author__name']
admin.site.register(Book, BookAdmin)
</code></pre>
<p>For additional reference, see the Django model link <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#list-display">here</a></p>
| 52 | 2014-05-19T21:55:14Z | [
"python",
"django",
"django-admin",
"modeladmin"
] |
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields? | 163,823 | <p>I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField).</p>
<p>With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display". I've tried all of the obvious methods for doing so (see below), but nothing seems to work. Any suggestions?</p>
<pre><code>class PersonAdmin(admin.ModelAdmin):
list_display = ['book.author',]
</code></pre>
| 150 | 2008-10-02T18:26:19Z | 28,190,954 | <p>Please note that adding the <code>get_author</code> function would slow the list_display in the admin, because showing each person would make a SQL query.</p>
<p>To avoid this, you need to modify <code>get_queryset</code> method in PersonAdmin, for example:</p>
<pre><code>def get_queryset(self, request):
return super(PersonAdmin,self).get_queryset(request).select_related('book')
</code></pre>
<blockquote>
<p>Before: 73 queries in 36.02ms (67 duplicated queries in admin)</p>
<p>After: 6 queries in 10.81ms</p>
</blockquote>
| 7 | 2015-01-28T11:20:40Z | [
"python",
"django",
"django-admin",
"modeladmin"
] |
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields? | 163,823 | <p>I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField).</p>
<p>With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display". I've tried all of the obvious methods for doing so (see below), but nothing seems to work. Any suggestions?</p>
<pre><code>class PersonAdmin(admin.ModelAdmin):
list_display = ['book.author',]
</code></pre>
| 150 | 2008-10-02T18:26:19Z | 34,735,225 | <p>If you have a lot of relation attribute fields to use in <code>list_display</code> and do not want create a function (and it's attributes) for each one, a dirt but simple solution would be override the <code>ModelAdmin</code> instace <code>__getattr__</code> method, creating the callables on the fly:</p>
<pre class="lang-py prettyprint-override"><code>class DynamicLookupMixin(object):
'''
a mixin to add dynamic callable attributes like 'book__author' which
return a function that return the instance.book.author value
'''
def __getattr__(self, attr):
if ('__' in attr
and not attr.startswith('_')
and not attr.endswith('_boolean')
and not attr.endswith('_short_description')):
def dyn_lookup(instance):
# traverse all __ lookups
return reduce(lambda parent, child: getattr(parent, child),
attr.split('__'),
instance)
# get admin_order_field, boolean and short_description
dyn_lookup.admin_order_field = attr
dyn_lookup.boolean = getattr(self, '{}_boolean'.format(attr), False)
dyn_lookup.short_description = getattr(
self, '{}_short_description'.format(attr),
attr.replace('_', ' ').capitalize())
return dyn_lookup
# not dynamic lookup, default behaviour
return self.__getattribute__(attr)
# use examples
@admin.register(models.Person)
class PersonAdmin(admin.ModelAdmin, DynamicLookupMixin):
list_display = ['book__author', 'book__publisher__name',
'book__publisher__country']
# custom short description
book__publisher__country_short_description = 'Publisher Country'
@admin.register(models.Product)
class ProductAdmin(admin.ModelAdmin, DynamicLookupMixin):
list_display = ('name', 'category__is_new')
# to show as boolean field
category__is_new_boolean = True
</code></pre>
<p>As <a href="https://gist.github.com/cauethenorio/9db40c59cf406bf328fd" rel="nofollow">gist here</a></p>
<p>Callable especial attributes like <code>boolean</code> and <code>short_description</code> must be defined as <code>ModelAdmin</code> attributes, eg <code>book__author_verbose_name = 'Author name'</code> and <code>category__is_new_boolean = True</code>.</p>
<p>The callable <code>admin_order_field</code> attribute is defined automatically.</p>
<p>Don't forget to use the <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_select_related" rel="nofollow" title="list_select_related">list_select_related</a> attribute in your <code>ModelAdmin</code> to make Django avoid aditional queries.</p>
| 1 | 2016-01-12T03:42:30Z | [
"python",
"django",
"django-admin",
"modeladmin"
] |
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields? | 163,823 | <p>I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField).</p>
<p>With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display". I've tried all of the obvious methods for doing so (see below), but nothing seems to work. Any suggestions?</p>
<pre><code>class PersonAdmin(admin.ModelAdmin):
list_display = ['book.author',]
</code></pre>
| 150 | 2008-10-02T18:26:19Z | 37,497,913 | <p>There is a very easy to use package available in PyPI that handles exactly that: <a href="https://pypi.python.org/pypi/django-related-admin" rel="nofollow">django-related-admin</a>. You can also <a href="https://github.com/PetrDlouhy/django-related-admin" rel="nofollow">see the code in GitHub</a>.</p>
<p>Using this, what you want to achieve is as simple as:</p>
<pre><code>class PersonAdmin(RelatedFieldAdmin):
list_display = ['book__author',]
</code></pre>
<p>Both links contain full details of installation and usage so I won't paste them here in case they change.</p>
<p>Just as a side note, if you're already using something other than <code>model.Admin</code> (e.g. I was using <code>SimpleHistoryAdmin</code> instead), you can do this: <code>class MyAdmin(SimpleHistoryAdmin, RelatedFieldAdmin)</code>.</p>
| 3 | 2016-05-28T10:30:55Z | [
"python",
"django",
"django-admin",
"modeladmin"
] |
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields? | 163,823 | <p>I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField).</p>
<p>With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display". I've tried all of the obvious methods for doing so (see below), but nothing seems to work. Any suggestions?</p>
<pre><code>class PersonAdmin(admin.ModelAdmin):
list_display = ['book.author',]
</code></pre>
| 150 | 2008-10-02T18:26:19Z | 39,642,294 | <p>I prefer this:</p>
<pre><code>class CoolAdmin(admin.ModelAdmin):
list_display = ('pk', 'submodel__field')
@staticmethod
def submodel__field(obj):
return obj.submodel.field
</code></pre>
| 0 | 2016-09-22T14:48:41Z | [
"python",
"django",
"django-admin",
"modeladmin"
] |
WPF Alternative for python | 163,881 | <p>Is there any alternative for WPF (windows presentation foundation) in python? </p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa970268.aspx#Programming_with_WPF">http://msdn.microsoft.com/en-us/library/aa970268.aspx#Programming_with_WPF</a> </p>
| 4 | 2008-10-02T18:35:16Z | 163,892 | <p>You might want to look at <a href="http://www.pygtk.org/" rel="nofollow">pygtk</a> and <a href="http://glade.gnome.org/" rel="nofollow">glade</a>. <a href="http://www.learningpython.com/2006/05/07/creating-a-gui-using-pygtk-and-glade/" rel="nofollow">Here</a> is a tutorial.</p>
<p>There is a long <a href="http://wiki.python.org/moin/GuiProgramming" rel="nofollow">list of alternatives</a> on the <a href="http://wiki.python.org/moin/FrontPage" rel="nofollow">Python Wiki</a>.</p>
| 3 | 2008-10-02T18:38:46Z | [
"python",
"user-interface"
] |
WPF Alternative for python | 163,881 | <p>Is there any alternative for WPF (windows presentation foundation) in python? </p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa970268.aspx#Programming_with_WPF">http://msdn.microsoft.com/en-us/library/aa970268.aspx#Programming_with_WPF</a> </p>
| 4 | 2008-10-02T18:35:16Z | 163,905 | <p>Here is a list of <a href="http://wiki.python.org/moin/GuiProgramming">Python GUI Toolkits</a>.</p>
<p>Also, you can <a href="http://stevegilham.blogspot.com/2007/07/hello-wpf-in-ironpython.html">use IronPython to work with WPF directly</a>. </p>
| 6 | 2008-10-02T18:41:08Z | [
"python",
"user-interface"
] |
WPF Alternative for python | 163,881 | <p>Is there any alternative for WPF (windows presentation foundation) in python? </p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa970268.aspx#Programming_with_WPF">http://msdn.microsoft.com/en-us/library/aa970268.aspx#Programming_with_WPF</a> </p>
| 4 | 2008-10-02T18:35:16Z | 163,911 | <p>Try <a href="http://www.ibm.com/developerworks/linux/library/l-qt/" rel="nofollow">PyQt</a> which binds python to QT graphics library. There are some other links at the end of that article:</p>
<ul>
<li>Anygui</li>
<li>PyGTK</li>
<li>FXPy</li>
<li>wxPython</li>
<li>win32ui </li>
</ul>
| 1 | 2008-10-02T18:42:38Z | [
"python",
"user-interface"
] |
WPF Alternative for python | 163,881 | <p>Is there any alternative for WPF (windows presentation foundation) in python? </p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa970268.aspx#Programming_with_WPF">http://msdn.microsoft.com/en-us/library/aa970268.aspx#Programming_with_WPF</a> </p>
| 4 | 2008-10-02T18:35:16Z | 163,935 | <p>If you are on Windows and you want to use WPF (as opposed to an alternative), you can use it with <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython" rel="nofollow">IronPython</a> - a .NET version of python.</p>
<p>Here's a quick example: <a href="http://stevegilham.blogspot.com/2007/07/hello-wpf-in-ironpython.html" rel="nofollow">http://stevegilham.blogspot.com/2007/07/hello-wpf-in-ironpython.html</a></p>
| 1 | 2008-10-02T18:47:36Z | [
"python",
"user-interface"
] |
How do I deploy a Python desktop application? | 164,137 | <p>I have started on a personal python application that runs on the desktop. I am using wxPython as a GUI toolkit. Should there be a demand for this type of application, I would possibly like to commercialize it.</p>
<p>I have no knowledge of deploying "real-life" Python applications, though I have used <a href="http://www.py2exe.org/"><code>py2exe</code></a> in the past with varied success. How would I obfuscate the code? Can I somehow deploy only the bytecode?</p>
<p>An ideal solution would not jeopardize my intellectual property (source code), would not require a direct installation of Python (though I'm sure it will need to have some embedded interpreter), and would be cross-platform (Windows, Mac, and Linux). Does anyone know of any tools or resources in this area?</p>
<p>Thanks.</p>
| 28 | 2008-10-02T19:31:51Z | 164,272 | <p>Wow, there are a lot of questions in there:</p>
<ul>
<li><p>It is possible to run the bytecode (.pyc) file directly from the Python interpreter, but I haven't seen any bytecode obfuscation tools available.</p></li>
<li><p>I'm not aware of any "all in one" deployment solution, but:</p>
<ul>
<li><p>For Windows you could use NSIS(<a href="http://nsis.sourceforge.net/Main_Page" rel="nofollow">http://nsis.sourceforge.net/Main_Page</a>). The problem here is that while OSX/*nix comes with python, Windows doesn't. If you're not willing to build a binary with py2exe, I'm not sure what the licensing issues would be surrounding distribution of the Python runtime environment (not to mention the technical ones).</p></li>
<li><p>You could package up the OS X distribution using the "bundle" format, and *NIX has it's own conventions for installing software-- typically a "make install" script.</p></li>
</ul></li>
</ul>
<p>Hope that was helpful.</p>
| 2 | 2008-10-02T19:56:36Z | [
"python",
"deployment"
] |
How do I deploy a Python desktop application? | 164,137 | <p>I have started on a personal python application that runs on the desktop. I am using wxPython as a GUI toolkit. Should there be a demand for this type of application, I would possibly like to commercialize it.</p>
<p>I have no knowledge of deploying "real-life" Python applications, though I have used <a href="http://www.py2exe.org/"><code>py2exe</code></a> in the past with varied success. How would I obfuscate the code? Can I somehow deploy only the bytecode?</p>
<p>An ideal solution would not jeopardize my intellectual property (source code), would not require a direct installation of Python (though I'm sure it will need to have some embedded interpreter), and would be cross-platform (Windows, Mac, and Linux). Does anyone know of any tools or resources in this area?</p>
<p>Thanks.</p>
| 28 | 2008-10-02T19:31:51Z | 164,291 | <p>You can distribute the compiled Python bytecode (.pyc files) instead of the source. You can't prevent decompilation in Python (or any other language, really). You could use an obfuscator like <a href="http://www.lysator.liu.se/~astrand/projects/pyobfuscate/" rel="nofollow">pyobfuscate</a> to make it more annoying for competitors to decipher your decompiled source.</p>
<p>As Alex Martelli says <a href="http://mail.python.org/pipermail/python-list/2006-April/1079623.html" rel="nofollow">in this thread</a>, if you want to keep your code a secret, you shouldn't run it on other people's machines.</p>
<p>IIRC, the last time I used <a href="http://python.net/crew/atuining/cx_Freeze/" rel="nofollow">cx_Freeze</a> it created a DLL for Windows that removed the necessity for a native Python installation. This is at least worth checking out.</p>
| 12 | 2008-10-02T20:02:01Z | [
"python",
"deployment"
] |
How do I deploy a Python desktop application? | 164,137 | <p>I have started on a personal python application that runs on the desktop. I am using wxPython as a GUI toolkit. Should there be a demand for this type of application, I would possibly like to commercialize it.</p>
<p>I have no knowledge of deploying "real-life" Python applications, though I have used <a href="http://www.py2exe.org/"><code>py2exe</code></a> in the past with varied success. How would I obfuscate the code? Can I somehow deploy only the bytecode?</p>
<p>An ideal solution would not jeopardize my intellectual property (source code), would not require a direct installation of Python (though I'm sure it will need to have some embedded interpreter), and would be cross-platform (Windows, Mac, and Linux). Does anyone know of any tools or resources in this area?</p>
<p>Thanks.</p>
| 28 | 2008-10-02T19:31:51Z | 166,332 | <p>Maybe IronPython can provide something for you? I bet those .exe/.dll-files can be pretty locked down. Not sure how such features work on mono, thus no idea how this works on Linux/OS X...</p>
| 1 | 2008-10-03T10:57:05Z | [
"python",
"deployment"
] |
How do I deploy a Python desktop application? | 164,137 | <p>I have started on a personal python application that runs on the desktop. I am using wxPython as a GUI toolkit. Should there be a demand for this type of application, I would possibly like to commercialize it.</p>
<p>I have no knowledge of deploying "real-life" Python applications, though I have used <a href="http://www.py2exe.org/"><code>py2exe</code></a> in the past with varied success. How would I obfuscate the code? Can I somehow deploy only the bytecode?</p>
<p>An ideal solution would not jeopardize my intellectual property (source code), would not require a direct installation of Python (though I'm sure it will need to have some embedded interpreter), and would be cross-platform (Windows, Mac, and Linux). Does anyone know of any tools or resources in this area?</p>
<p>Thanks.</p>
| 28 | 2008-10-02T19:31:51Z | 464,932 | <p>I have been using py2exe with good success on Windows. The code needs to be modified a bit so that the code analysis picks up all modules needed, but apart from that, it works.</p>
<p>As for Linux, there are several important distribution formats:</p>
<ul>
<li>DEB (Debian, Ubuntu and other derivatives)</li>
<li>RPM (RedHat, Fedora, openSuSE)</li>
</ul>
<p>DEBs aren't particularly difficult to make, especially when you're already using distutils/setuptools. Some hints are given in <a href="http://wiki.debian.org/DebianPython/NewPolicy" rel="nofollow">the policy document</a>, examples for packaging Python applications can be found in the <a href="http://svn.debian.org/wsvn/python-apps/packages/" rel="nofollow">repository</a>. </p>
<p>I don't have any experience with RPM, but I'm sure there are enough examples to be found.</p>
| 0 | 2009-01-21T11:37:20Z | [
"python",
"deployment"
] |
Change Django Templates Based on User-Agent | 164,427 | <p>I've made a Django site, but I've drank the Koolaid and I want to make an <em>IPhone</em> version. After putting much thought into I've come up with two options:</p>
<ol>
<li>Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework.</li>
<li>Find some time of middleware that reads the user-agent, and changes the template directories dynamically.</li>
</ol>
<p>I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation <a href="http://docs.djangoproject.com/en/dev/topics/settings/">discourages changing settings on the fly</a>. I found a <a href="http://www.djangosnippets.org/snippets/1098/">snippet</a> that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user.</p>
<p>Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites?</p>
<p><strong>Update</strong></p>
<p>I went with a combination of middleware and tweaking the template call.</p>
<p>For the middleware, I used <a href="http://code.google.com/p/minidetector/">minidetector</a>. I like it because it detects a <a href="http://www.youtube.com/watch?v=b6E682C7Jj4">plethora</a> of mobile user-agents. All I have to do is check request.mobile in my views.</p>
<p>For the template call tweak:</p>
<pre><code> def check_mobile(request, template_name):
if request.mobile:
return 'mobile-%s'%template_name
return template_name
</code></pre>
<p>I use this for any view that I know I have both versions.</p>
<p><strong>TODO:</strong></p>
<ul>
<li>Figure out how to access <em>request.mobile</em> in an extended version of render_to_response so I don't have to use check_mobile('template_name.html')</li>
<li>Using the previous automagically fallback to the regular template if no mobile version exists.</li>
</ul>
| 38 | 2008-10-02T20:30:09Z | 164,507 | <p>Rather than changing the template directories dynamically you could modify the request and add a value that lets your view know if the user is on an iphone or not. Then wrap render_to_response (or whatever you are using for creating HttpResponse objects) to grab the iphone version of the template instead of the standard html version if they are using an iphone. </p>
| 18 | 2008-10-02T20:44:38Z | [
"python",
"django",
"django-templates",
"mobile-website",
"django-middleware"
] |
Change Django Templates Based on User-Agent | 164,427 | <p>I've made a Django site, but I've drank the Koolaid and I want to make an <em>IPhone</em> version. After putting much thought into I've come up with two options:</p>
<ol>
<li>Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework.</li>
<li>Find some time of middleware that reads the user-agent, and changes the template directories dynamically.</li>
</ol>
<p>I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation <a href="http://docs.djangoproject.com/en/dev/topics/settings/">discourages changing settings on the fly</a>. I found a <a href="http://www.djangosnippets.org/snippets/1098/">snippet</a> that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user.</p>
<p>Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites?</p>
<p><strong>Update</strong></p>
<p>I went with a combination of middleware and tweaking the template call.</p>
<p>For the middleware, I used <a href="http://code.google.com/p/minidetector/">minidetector</a>. I like it because it detects a <a href="http://www.youtube.com/watch?v=b6E682C7Jj4">plethora</a> of mobile user-agents. All I have to do is check request.mobile in my views.</p>
<p>For the template call tweak:</p>
<pre><code> def check_mobile(request, template_name):
if request.mobile:
return 'mobile-%s'%template_name
return template_name
</code></pre>
<p>I use this for any view that I know I have both versions.</p>
<p><strong>TODO:</strong></p>
<ul>
<li>Figure out how to access <em>request.mobile</em> in an extended version of render_to_response so I don't have to use check_mobile('template_name.html')</li>
<li>Using the previous automagically fallback to the regular template if no mobile version exists.</li>
</ul>
| 38 | 2008-10-02T20:30:09Z | 164,616 | <p>How about redirecting user to i.xxx.com after parsing his UA in some middleware? I highly doubt that mobile users care how url look like, still they can access your site using main url.</p>
| 1 | 2008-10-02T21:08:31Z | [
"python",
"django",
"django-templates",
"mobile-website",
"django-middleware"
] |
Change Django Templates Based on User-Agent | 164,427 | <p>I've made a Django site, but I've drank the Koolaid and I want to make an <em>IPhone</em> version. After putting much thought into I've come up with two options:</p>
<ol>
<li>Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework.</li>
<li>Find some time of middleware that reads the user-agent, and changes the template directories dynamically.</li>
</ol>
<p>I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation <a href="http://docs.djangoproject.com/en/dev/topics/settings/">discourages changing settings on the fly</a>. I found a <a href="http://www.djangosnippets.org/snippets/1098/">snippet</a> that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user.</p>
<p>Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites?</p>
<p><strong>Update</strong></p>
<p>I went with a combination of middleware and tweaking the template call.</p>
<p>For the middleware, I used <a href="http://code.google.com/p/minidetector/">minidetector</a>. I like it because it detects a <a href="http://www.youtube.com/watch?v=b6E682C7Jj4">plethora</a> of mobile user-agents. All I have to do is check request.mobile in my views.</p>
<p>For the template call tweak:</p>
<pre><code> def check_mobile(request, template_name):
if request.mobile:
return 'mobile-%s'%template_name
return template_name
</code></pre>
<p>I use this for any view that I know I have both versions.</p>
<p><strong>TODO:</strong></p>
<ul>
<li>Figure out how to access <em>request.mobile</em> in an extended version of render_to_response so I don't have to use check_mobile('template_name.html')</li>
<li>Using the previous automagically fallback to the regular template if no mobile version exists.</li>
</ul>
| 38 | 2008-10-02T20:30:09Z | 189,367 | <p>You should take a look at the <a href="http://code.google.com/p/django-mobileadmin/" rel="nofollow">django-mobileadmin</a> source code, which solved exactly this problem.</p>
| 2 | 2008-10-09T22:00:13Z | [
"python",
"django",
"django-templates",
"mobile-website",
"django-middleware"
] |
Change Django Templates Based on User-Agent | 164,427 | <p>I've made a Django site, but I've drank the Koolaid and I want to make an <em>IPhone</em> version. After putting much thought into I've come up with two options:</p>
<ol>
<li>Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework.</li>
<li>Find some time of middleware that reads the user-agent, and changes the template directories dynamically.</li>
</ol>
<p>I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation <a href="http://docs.djangoproject.com/en/dev/topics/settings/">discourages changing settings on the fly</a>. I found a <a href="http://www.djangosnippets.org/snippets/1098/">snippet</a> that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user.</p>
<p>Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites?</p>
<p><strong>Update</strong></p>
<p>I went with a combination of middleware and tweaking the template call.</p>
<p>For the middleware, I used <a href="http://code.google.com/p/minidetector/">minidetector</a>. I like it because it detects a <a href="http://www.youtube.com/watch?v=b6E682C7Jj4">plethora</a> of mobile user-agents. All I have to do is check request.mobile in my views.</p>
<p>For the template call tweak:</p>
<pre><code> def check_mobile(request, template_name):
if request.mobile:
return 'mobile-%s'%template_name
return template_name
</code></pre>
<p>I use this for any view that I know I have both versions.</p>
<p><strong>TODO:</strong></p>
<ul>
<li>Figure out how to access <em>request.mobile</em> in an extended version of render_to_response so I don't have to use check_mobile('template_name.html')</li>
<li>Using the previous automagically fallback to the regular template if no mobile version exists.</li>
</ul>
| 38 | 2008-10-02T20:30:09Z | 207,954 | <p>Other way would be creating your own template loader that loads templates specific to user agent. This is pretty generic technique and can be use to dynamically determine what template has to be loaded depending on other factors too, like requested language (good companion to existing Django i18n machinery).</p>
<p>Django Book has a <a href="http://www.djangobook.com/en/1.0/chapter10/#cn234" rel="nofollow">section on this subject</a>.</p>
| 2 | 2008-10-16T09:41:23Z | [
"python",
"django",
"django-templates",
"mobile-website",
"django-middleware"
] |
Change Django Templates Based on User-Agent | 164,427 | <p>I've made a Django site, but I've drank the Koolaid and I want to make an <em>IPhone</em> version. After putting much thought into I've come up with two options:</p>
<ol>
<li>Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework.</li>
<li>Find some time of middleware that reads the user-agent, and changes the template directories dynamically.</li>
</ol>
<p>I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation <a href="http://docs.djangoproject.com/en/dev/topics/settings/">discourages changing settings on the fly</a>. I found a <a href="http://www.djangosnippets.org/snippets/1098/">snippet</a> that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user.</p>
<p>Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites?</p>
<p><strong>Update</strong></p>
<p>I went with a combination of middleware and tweaking the template call.</p>
<p>For the middleware, I used <a href="http://code.google.com/p/minidetector/">minidetector</a>. I like it because it detects a <a href="http://www.youtube.com/watch?v=b6E682C7Jj4">plethora</a> of mobile user-agents. All I have to do is check request.mobile in my views.</p>
<p>For the template call tweak:</p>
<pre><code> def check_mobile(request, template_name):
if request.mobile:
return 'mobile-%s'%template_name
return template_name
</code></pre>
<p>I use this for any view that I know I have both versions.</p>
<p><strong>TODO:</strong></p>
<ul>
<li>Figure out how to access <em>request.mobile</em> in an extended version of render_to_response so I don't have to use check_mobile('template_name.html')</li>
<li>Using the previous automagically fallback to the regular template if no mobile version exists.</li>
</ul>
| 38 | 2008-10-02T20:30:09Z | 216,377 | <p>I'm developing djangobile, a django mobile extension: <a href="http://code.google.com/p/djangobile/" rel="nofollow">http://code.google.com/p/djangobile/</a></p>
| 3 | 2008-10-19T12:46:33Z | [
"python",
"django",
"django-templates",
"mobile-website",
"django-middleware"
] |
Change Django Templates Based on User-Agent | 164,427 | <p>I've made a Django site, but I've drank the Koolaid and I want to make an <em>IPhone</em> version. After putting much thought into I've come up with two options:</p>
<ol>
<li>Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework.</li>
<li>Find some time of middleware that reads the user-agent, and changes the template directories dynamically.</li>
</ol>
<p>I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation <a href="http://docs.djangoproject.com/en/dev/topics/settings/">discourages changing settings on the fly</a>. I found a <a href="http://www.djangosnippets.org/snippets/1098/">snippet</a> that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user.</p>
<p>Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites?</p>
<p><strong>Update</strong></p>
<p>I went with a combination of middleware and tweaking the template call.</p>
<p>For the middleware, I used <a href="http://code.google.com/p/minidetector/">minidetector</a>. I like it because it detects a <a href="http://www.youtube.com/watch?v=b6E682C7Jj4">plethora</a> of mobile user-agents. All I have to do is check request.mobile in my views.</p>
<p>For the template call tweak:</p>
<pre><code> def check_mobile(request, template_name):
if request.mobile:
return 'mobile-%s'%template_name
return template_name
</code></pre>
<p>I use this for any view that I know I have both versions.</p>
<p><strong>TODO:</strong></p>
<ul>
<li>Figure out how to access <em>request.mobile</em> in an extended version of render_to_response so I don't have to use check_mobile('template_name.html')</li>
<li>Using the previous automagically fallback to the regular template if no mobile version exists.</li>
</ul>
| 38 | 2008-10-02T20:30:09Z | 299,780 | <p>There is a nice article which explains how to render the same data by different templates
<a href="http://www.postneo.com/2006/07/26/acknowledging-the-mobile-web-with-django" rel="nofollow">http://www.postneo.com/2006/07/26/acknowledging-the-mobile-web-with-django</a></p>
<p>You still need to automatically redirect the user to mobile site however and this can be done using several methods (your check_mobile trick will work too)</p>
| 2 | 2008-11-18T19:06:33Z | [
"python",
"django",
"django-templates",
"mobile-website",
"django-middleware"
] |
Change Django Templates Based on User-Agent | 164,427 | <p>I've made a Django site, but I've drank the Koolaid and I want to make an <em>IPhone</em> version. After putting much thought into I've come up with two options:</p>
<ol>
<li>Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework.</li>
<li>Find some time of middleware that reads the user-agent, and changes the template directories dynamically.</li>
</ol>
<p>I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation <a href="http://docs.djangoproject.com/en/dev/topics/settings/">discourages changing settings on the fly</a>. I found a <a href="http://www.djangosnippets.org/snippets/1098/">snippet</a> that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user.</p>
<p>Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites?</p>
<p><strong>Update</strong></p>
<p>I went with a combination of middleware and tweaking the template call.</p>
<p>For the middleware, I used <a href="http://code.google.com/p/minidetector/">minidetector</a>. I like it because it detects a <a href="http://www.youtube.com/watch?v=b6E682C7Jj4">plethora</a> of mobile user-agents. All I have to do is check request.mobile in my views.</p>
<p>For the template call tweak:</p>
<pre><code> def check_mobile(request, template_name):
if request.mobile:
return 'mobile-%s'%template_name
return template_name
</code></pre>
<p>I use this for any view that I know I have both versions.</p>
<p><strong>TODO:</strong></p>
<ul>
<li>Figure out how to access <em>request.mobile</em> in an extended version of render_to_response so I don't have to use check_mobile('template_name.html')</li>
<li>Using the previous automagically fallback to the regular template if no mobile version exists.</li>
</ul>
| 38 | 2008-10-02T20:30:09Z | 433,216 | <p>This article might be useful: <a href="http://mobiforge.com/developing/story/build-a-mobile-and-desktop-friendly-application-django-15-minutes-or-less" rel="nofollow">Build a Mobile and Desktop-Friendly Application in Django in 15 Minutes</a></p>
| 4 | 2009-01-11T17:04:52Z | [
"python",
"django",
"django-templates",
"mobile-website",
"django-middleware"
] |
Change Django Templates Based on User-Agent | 164,427 | <p>I've made a Django site, but I've drank the Koolaid and I want to make an <em>IPhone</em> version. After putting much thought into I've come up with two options:</p>
<ol>
<li>Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework.</li>
<li>Find some time of middleware that reads the user-agent, and changes the template directories dynamically.</li>
</ol>
<p>I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation <a href="http://docs.djangoproject.com/en/dev/topics/settings/">discourages changing settings on the fly</a>. I found a <a href="http://www.djangosnippets.org/snippets/1098/">snippet</a> that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user.</p>
<p>Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites?</p>
<p><strong>Update</strong></p>
<p>I went with a combination of middleware and tweaking the template call.</p>
<p>For the middleware, I used <a href="http://code.google.com/p/minidetector/">minidetector</a>. I like it because it detects a <a href="http://www.youtube.com/watch?v=b6E682C7Jj4">plethora</a> of mobile user-agents. All I have to do is check request.mobile in my views.</p>
<p>For the template call tweak:</p>
<pre><code> def check_mobile(request, template_name):
if request.mobile:
return 'mobile-%s'%template_name
return template_name
</code></pre>
<p>I use this for any view that I know I have both versions.</p>
<p><strong>TODO:</strong></p>
<ul>
<li>Figure out how to access <em>request.mobile</em> in an extended version of render_to_response so I don't have to use check_mobile('template_name.html')</li>
<li>Using the previous automagically fallback to the regular template if no mobile version exists.</li>
</ul>
| 38 | 2008-10-02T20:30:09Z | 3,487,254 | <p>Detect the user agent in middleware, switch the url bindings, profit!</p>
<p>How? Django request objects have a .urlconf attribute, which can be set by middleware.</p>
<p>From django docs:</p>
<blockquote>
<p>Django determines the root URLconf
module to use. Ordinarily, this is the
value of the ROOT_URLCONF setting, but
if the incoming HttpRequest object has
an attribute called urlconf (set by
middleware request processing), its
value will be used in place of the
ROOT_URLCONF setting.</p>
</blockquote>
<ol>
<li><p>In yourproj/middlware.py, write a class that checks the http_user_agent string:</p>
<pre><code>import re
MOBILE_AGENT_RE=re.compile(r".*(iphone|mobile|androidtouch)",re.IGNORECASE)
class MobileMiddleware(object):
def process_request(self,request):
if MOBILE_AGENT_RE.match(request.META['HTTP_USER_AGENT']):
request.urlconf="yourproj.mobile_urls"
</code></pre></li>
<li><p>Don't forget to add this to MIDDLEWARE_CLASSES in settings.py:</p>
<pre><code>MIDDLEWARE_CLASSES= [...
'yourproj.middleware.MobileMiddleware',
...]
</code></pre></li>
<li><p>Create a mobile urlconf, yourproj/mobile_urls.py:</p>
<pre><code>urlpatterns=patterns('',('r'/?$', 'mobile.index'), ...)
</code></pre></li>
</ol>
| 9 | 2010-08-15T11:57:53Z | [
"python",
"django",
"django-templates",
"mobile-website",
"django-middleware"
] |
Change Django Templates Based on User-Agent | 164,427 | <p>I've made a Django site, but I've drank the Koolaid and I want to make an <em>IPhone</em> version. After putting much thought into I've come up with two options:</p>
<ol>
<li>Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework.</li>
<li>Find some time of middleware that reads the user-agent, and changes the template directories dynamically.</li>
</ol>
<p>I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation <a href="http://docs.djangoproject.com/en/dev/topics/settings/">discourages changing settings on the fly</a>. I found a <a href="http://www.djangosnippets.org/snippets/1098/">snippet</a> that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user.</p>
<p>Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites?</p>
<p><strong>Update</strong></p>
<p>I went with a combination of middleware and tweaking the template call.</p>
<p>For the middleware, I used <a href="http://code.google.com/p/minidetector/">minidetector</a>. I like it because it detects a <a href="http://www.youtube.com/watch?v=b6E682C7Jj4">plethora</a> of mobile user-agents. All I have to do is check request.mobile in my views.</p>
<p>For the template call tweak:</p>
<pre><code> def check_mobile(request, template_name):
if request.mobile:
return 'mobile-%s'%template_name
return template_name
</code></pre>
<p>I use this for any view that I know I have both versions.</p>
<p><strong>TODO:</strong></p>
<ul>
<li>Figure out how to access <em>request.mobile</em> in an extended version of render_to_response so I don't have to use check_mobile('template_name.html')</li>
<li>Using the previous automagically fallback to the regular template if no mobile version exists.</li>
</ul>
| 38 | 2008-10-02T20:30:09Z | 4,152,279 | <p>best possible scenario: use minidetector to add the extra info to the request, then use django's built in request context to pass it to your templates like so</p>
<pre><code>from django.shortcuts import render_to_response
from django.template import RequestContext
def my_view_on_mobile_and_desktop(request)
.....
render_to_response('regular_template.html',
{'my vars to template':vars},
context_instance=RequestContext(request))
</code></pre>
<p>then in your template you are able to introduce stuff like:</p>
<pre><code><html>
<head>
{% block head %}
<title>blah</title>
{% if request.mobile %}
<link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-mobile.css">
{% else %}
<link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-desktop.css">
{% endif %}
</head>
<body>
<div id="navigation">
{% include "_navigation.html" %}
</div>
{% if not request.mobile %}
<div id="sidebar">
<p> sidebar content not fit for mobile </p>
</div>
{% endif %>
<div id="content">
<article>
{% if not request.mobile %}
<aside>
<p> aside content </p>
</aside>
{% endif %}
<p> article content </p>
</aricle>
</div>
</body>
</html>
</code></pre>
| 1 | 2010-11-11T07:43:09Z | [
"python",
"django",
"django-templates",
"mobile-website",
"django-middleware"
] |
Change Django Templates Based on User-Agent | 164,427 | <p>I've made a Django site, but I've drank the Koolaid and I want to make an <em>IPhone</em> version. After putting much thought into I've come up with two options:</p>
<ol>
<li>Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework.</li>
<li>Find some time of middleware that reads the user-agent, and changes the template directories dynamically.</li>
</ol>
<p>I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation <a href="http://docs.djangoproject.com/en/dev/topics/settings/">discourages changing settings on the fly</a>. I found a <a href="http://www.djangosnippets.org/snippets/1098/">snippet</a> that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user.</p>
<p>Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites?</p>
<p><strong>Update</strong></p>
<p>I went with a combination of middleware and tweaking the template call.</p>
<p>For the middleware, I used <a href="http://code.google.com/p/minidetector/">minidetector</a>. I like it because it detects a <a href="http://www.youtube.com/watch?v=b6E682C7Jj4">plethora</a> of mobile user-agents. All I have to do is check request.mobile in my views.</p>
<p>For the template call tweak:</p>
<pre><code> def check_mobile(request, template_name):
if request.mobile:
return 'mobile-%s'%template_name
return template_name
</code></pre>
<p>I use this for any view that I know I have both versions.</p>
<p><strong>TODO:</strong></p>
<ul>
<li>Figure out how to access <em>request.mobile</em> in an extended version of render_to_response so I don't have to use check_mobile('template_name.html')</li>
<li>Using the previous automagically fallback to the regular template if no mobile version exists.</li>
</ul>
| 38 | 2008-10-02T20:30:09Z | 14,510,830 | <p>A simple solution is to create a wrapper around <code>django.shortcuts.render</code>. I put mine in a <code>utils</code> library in the root of my application. The wrapper works by automatically rendering templates in either a "mobile" or "desktop" folder.</p>
<p>In <code>utils.shortcuts</code>:</p>
<blockquote>
<pre><code>from django.shortcuts import render
from user_agents import parse
def my_render(request, *args, **kwargs):
"""
An extension of django.shortcuts.render.
Appends 'mobile/' or 'desktop/' to a given template location
to render the appropriate template for mobile or desktop
depends on user_agents python library
https://github.com/selwin/python-user-agents
"""
template_location = args[0]
args_list = list(args)
ua_string = request.META['HTTP_USER_AGENT']
user_agent = parse(ua_string)
if user_agent.is_mobile:
args_list[0] = 'mobile/' + template_location
args = tuple(args_list)
return render(request, *args, **kwargs)
else:
args_list[0] = 'desktop/' + template_location
args = tuple(args_list)
return render(request, *args, **kwargs)
</code></pre>
</blockquote>
<p>In <code>view</code>:</p>
<blockquote>
<pre><code>from utils.shortcuts import my_render
def home(request): return my_render(request, 'home.html')
</code></pre>
</blockquote>
| 0 | 2013-01-24T21:09:45Z | [
"python",
"django",
"django-templates",
"mobile-website",
"django-middleware"
] |
Programmatically launching standalone Adobe flashplayer on Linux/X11 | 164,460 | <p>The standalone flashplayer takes no arguments other than a .swf file when you launch it from the command line. I need the player to go full screen, no window borders and such. This can be accomplished by hitting ctrl+f once the program has started. I want to do this programmatically as I need it to launch into full screen without any human interaction.</p>
<p>My guess is that I need to some how get a handle to the window and then send it an event that looks like the "ctrl+f" keystroke. </p>
<p>If it makes any difference, it looks like flashplayer is a gtk application and I have python with pygtk installed.</p>
<p><b>UPDATE</b> (the solution I used... thanks to ypnos' answer):</p>
<pre><code>./flashplayer http://example.com/example.swf & sleep 3 && ~/xsendkey -window "Adobe Flash Player 10" Control+F
</code></pre>
| 7 | 2008-10-02T20:36:02Z | 164,681 | <p>I've actually done this a long time ago, but it wasn't petty. What we did is use the <a href="http://sawfish.wikia.com/wiki/Main_Page" rel="nofollow">Sawfish window manager</a> and wrote a hook to recognize the flashplayer window, then strip all the decorations and snap it full screen.</p>
<p>This may be possible without using the window manager, by registering for X window creation events from an external application, but I'm not familiar enough with X11 to tell you how that would be done.</p>
<p>Another option would be to write a pygtk application that embedded the standalone flash player inside a gtk.Socket and then resized itself. After a bit of thought, this might be your best bet.</p>
| 1 | 2008-10-02T21:26:19Z | [
"python",
"linux",
"adobe",
"x11",
"flash-player"
] |
Programmatically launching standalone Adobe flashplayer on Linux/X11 | 164,460 | <p>The standalone flashplayer takes no arguments other than a .swf file when you launch it from the command line. I need the player to go full screen, no window borders and such. This can be accomplished by hitting ctrl+f once the program has started. I want to do this programmatically as I need it to launch into full screen without any human interaction.</p>
<p>My guess is that I need to some how get a handle to the window and then send it an event that looks like the "ctrl+f" keystroke. </p>
<p>If it makes any difference, it looks like flashplayer is a gtk application and I have python with pygtk installed.</p>
<p><b>UPDATE</b> (the solution I used... thanks to ypnos' answer):</p>
<pre><code>./flashplayer http://example.com/example.swf & sleep 3 && ~/xsendkey -window "Adobe Flash Player 10" Control+F
</code></pre>
| 7 | 2008-10-02T20:36:02Z | 165,089 | <p>You can use a dedicated application which sends the keystroke to the window manager, which should then pass it to flash, if the window starts as being the active window on the screen. This is quite error prone, though, due to delays between starting flash and when the window will show up.</p>
<p>For example, your script could do something like this:
flashplayer *.swf
sleep 3 && xsendkey Control+F</p>
<p>The application xsendkey can be found here: <a href="http://people.csail.mit.edu/adonovan/hacks/xsendkey.html" rel="nofollow">http://people.csail.mit.edu/adonovan/hacks/xsendkey.html</a>
Without given a specific window, it will send it to the root window, which is handled by your window manager. You could also try to figure out the Window id first, using xprop or something related to it.</p>
<p>Another option is a Window manager, which is able to remember your settings and automatically apply them. Fluxbos for example provides this feature. You could set fluxbox to make the Window decor-less and stretch it over the whole screen, if flashplayer supports being resized. This is also not-so-nice, as it would probably affect all the flashplayer windows you open ever.</p>
| 7 | 2008-10-02T23:44:15Z | [
"python",
"linux",
"adobe",
"x11",
"flash-player"
] |
Programmatically launching standalone Adobe flashplayer on Linux/X11 | 164,460 | <p>The standalone flashplayer takes no arguments other than a .swf file when you launch it from the command line. I need the player to go full screen, no window borders and such. This can be accomplished by hitting ctrl+f once the program has started. I want to do this programmatically as I need it to launch into full screen without any human interaction.</p>
<p>My guess is that I need to some how get a handle to the window and then send it an event that looks like the "ctrl+f" keystroke. </p>
<p>If it makes any difference, it looks like flashplayer is a gtk application and I have python with pygtk installed.</p>
<p><b>UPDATE</b> (the solution I used... thanks to ypnos' answer):</p>
<pre><code>./flashplayer http://example.com/example.swf & sleep 3 && ~/xsendkey -window "Adobe Flash Player 10" Control+F
</code></pre>
| 7 | 2008-10-02T20:36:02Z | 277,865 | <pre><code>nspluginplayer --fullscreen src=path/to/flashfile.swf
</code></pre>
<p>which is from the http://gwenole.beauchesne.info//en/projects/nspluginwrapper</p>
| 1 | 2008-11-10T13:40:49Z | [
"python",
"linux",
"adobe",
"x11",
"flash-player"
] |
Programmatically launching standalone Adobe flashplayer on Linux/X11 | 164,460 | <p>The standalone flashplayer takes no arguments other than a .swf file when you launch it from the command line. I need the player to go full screen, no window borders and such. This can be accomplished by hitting ctrl+f once the program has started. I want to do this programmatically as I need it to launch into full screen without any human interaction.</p>
<p>My guess is that I need to some how get a handle to the window and then send it an event that looks like the "ctrl+f" keystroke. </p>
<p>If it makes any difference, it looks like flashplayer is a gtk application and I have python with pygtk installed.</p>
<p><b>UPDATE</b> (the solution I used... thanks to ypnos' answer):</p>
<pre><code>./flashplayer http://example.com/example.swf & sleep 3 && ~/xsendkey -window "Adobe Flash Player 10" Control+F
</code></pre>
| 7 | 2008-10-02T20:36:02Z | 2,276,508 | <p>I've done this using openbox using a similar mechanism to the one that bmdhacks mentions. The thing that I did note from this was that the standalone flash player performed considerably worse fullscreen than the same player in a maximised undecorated window. (that, annoyingly is not properly fullscreen because of the menubar). I was wondering about running it with a custom gtk theme to make the menu invisible. That's just a performance issue though. If fullscreen currently works ok, then it's unneccisarily complicated. I was running on an OLPC XO, performance is more of an issue there.</p>
<p>I didn't have much luck with nspluginplayer (too buggy I think).</p>
<p>Ultimately I had the luxury of making the flash that was running so I could simply place code into the flash itself. By a similar token, Since you can embed flash within flash, it should be possible to make a little stub swf that goes fullscreen automatically and contains the target sfw.</p>
| 0 | 2010-02-16T21:31:19Z | [
"python",
"linux",
"adobe",
"x11",
"flash-player"
] |
Programmatically launching standalone Adobe flashplayer on Linux/X11 | 164,460 | <p>The standalone flashplayer takes no arguments other than a .swf file when you launch it from the command line. I need the player to go full screen, no window borders and such. This can be accomplished by hitting ctrl+f once the program has started. I want to do this programmatically as I need it to launch into full screen without any human interaction.</p>
<p>My guess is that I need to some how get a handle to the window and then send it an event that looks like the "ctrl+f" keystroke. </p>
<p>If it makes any difference, it looks like flashplayer is a gtk application and I have python with pygtk installed.</p>
<p><b>UPDATE</b> (the solution I used... thanks to ypnos' answer):</p>
<pre><code>./flashplayer http://example.com/example.swf & sleep 3 && ~/xsendkey -window "Adobe Flash Player 10" Control+F
</code></pre>
| 7 | 2008-10-02T20:36:02Z | 3,994,891 | <p>You have to use Acton script 3 cmd:</p>
<pre><code>stage.displayState = StageDisplayState.FULL_SCREEN;
</code></pre>
<p>See Adobe Action script 3 programming.</p>
<p>But be careful : in full screen, you will lose display performances!</p>
<p>I've got this problem ... more under Linux!!!</p>
| 0 | 2010-10-22T07:57:47Z | [
"python",
"linux",
"adobe",
"x11",
"flash-player"
] |
Programmatically launching standalone Adobe flashplayer on Linux/X11 | 164,460 | <p>The standalone flashplayer takes no arguments other than a .swf file when you launch it from the command line. I need the player to go full screen, no window borders and such. This can be accomplished by hitting ctrl+f once the program has started. I want to do this programmatically as I need it to launch into full screen without any human interaction.</p>
<p>My guess is that I need to some how get a handle to the window and then send it an event that looks like the "ctrl+f" keystroke. </p>
<p>If it makes any difference, it looks like flashplayer is a gtk application and I have python with pygtk installed.</p>
<p><b>UPDATE</b> (the solution I used... thanks to ypnos' answer):</p>
<pre><code>./flashplayer http://example.com/example.swf & sleep 3 && ~/xsendkey -window "Adobe Flash Player 10" Control+F
</code></pre>
| 7 | 2008-10-02T20:36:02Z | 10,877,411 | <blockquote>
<p>Another option would be to write a pygtk application that embedded the standalone flash player inside a gtk.Socket and then resized itself. After a bit of thought, this might be your best bet.</p>
</blockquote>
<p>This is exactly what I did. In addition to that, my player scales flash content via Xcomposite, Xfixes and Cairo. A .deb including python source be found here:
<a href="http://www.crutzi.info/crutziplayer" rel="nofollow">http://www.crutzi.info/crutziplayer</a></p>
| 1 | 2012-06-04T06:56:19Z | [
"python",
"linux",
"adobe",
"x11",
"flash-player"
] |
How would I package and sell a Django app? | 164,901 | <p>Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves.</p>
<p>My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound like a good idea as the people I sell it to too could just make copies of them and pass them on.</p>
<p>I think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same (LAMP) setup.</p>
| 30 | 2008-10-02T22:27:56Z | 164,920 | <p>The way I'd go about it is this:</p>
<ol>
<li>Encrypt all of the code</li>
<li>Write an installer that contacts the server with the machine's hostname and license file and gets the decryption key, then decrypts the code and compiles it to python bytecode</li>
<li>Add (in the installer) a module that checks the machine's hostname and license file on import and dies if it doesn't match</li>
</ol>
<p>This way the user only has to contact the server when the hostname changes and on first install, but you get a small layer of security. You could change the hostname to something more complex, but there's really no need -- anyone that wants to pirate this will do so, but a simple mechanism like that will keep honest people honest.</p>
| 11 | 2008-10-02T22:40:24Z | [
"python",
"django",
"distribution",
"piracy-prevention"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.