title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How to get field names when running plain sql query in django
805,660
<p>In one of my django views I query database using plain sql (not orm) and return results. </p> <pre><code>sql = "select * from foo_bar" cursor = connection.cursor() cursor.execute(sql) rows = cursor.fetchall() </code></pre> <p>I am getting the data fine, but not the column names. How can I get the field names of the result set that is returned?</p>
5
2009-04-30T06:49:33Z
805,778
<p>According to <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">PEP 249</a>, you can try using <code>cursor.description</code>, but this is not entirely reliable.</p>
7
2009-04-30T07:30:21Z
[ "python", "django" ]
How to get field names when running plain sql query in django
805,660
<p>In one of my django views I query database using plain sql (not orm) and return results. </p> <pre><code>sql = "select * from foo_bar" cursor = connection.cursor() cursor.execute(sql) rows = cursor.fetchall() </code></pre> <p>I am getting the data fine, but not the column names. How can I get the field names of the result set that is returned?</p>
5
2009-04-30T06:49:33Z
14,215,488
<p>I have found a nice solution in Doug Hellmann's blog:</p> <p><a href="http://doughellmann.com/2007/12/30/using-raw-sql-in-django.html" rel="nofollow">http://doughellmann.com/2007/12/30/using-raw-sql-in-django.html</a></p> <pre><code>from itertools import * from django.db import connection def query_to_dicts(query_string, *query_args): """Run a simple query and produce a generator that returns the results as a bunch of dictionaries with keys for the column values selected. """ cursor = connection.cursor() cursor.execute(query_string, query_args) col_names = [desc[0] for desc in cursor.description] while True: row = cursor.fetchone() if row is None: break row_dict = dict(izip(col_names, row)) yield row_dict return </code></pre> <p>Example usage:</p> <pre><code> row_dicts = query_to_dicts("""select * from table""") </code></pre>
3
2013-01-08T12:58:21Z
[ "python", "django" ]
How to get field names when running plain sql query in django
805,660
<p>In one of my django views I query database using plain sql (not orm) and return results. </p> <pre><code>sql = "select * from foo_bar" cursor = connection.cursor() cursor.execute(sql) rows = cursor.fetchall() </code></pre> <p>I am getting the data fine, but not the column names. How can I get the field names of the result set that is returned?</p>
5
2009-04-30T06:49:33Z
25,330,129
<p>On the <a href="https://docs.djangoproject.com/en/dev/topics/db/sql/#executing-custom-sql-directly" rel="nofollow">Django docs</a>, there's a pretty simple method provided (which does indeed use <code>cursor.description</code>, as Ignacio answered).</p> <pre><code>def dictfetchall(cursor): "Returns all rows from a cursor as a dict" desc = cursor.description return [ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ] </code></pre>
4
2014-08-15T16:15:44Z
[ "python", "django" ]
how to avoid hard-coding urls in webapp templates
805,751
<p>I'm developing software on google app engine. I'm using the webapp framework. is there any way to avoid hard-coding urls in the html templates? django provides a solution, but I couldn't find one for webapp. thanks in advance..</p>
3
2009-04-30T07:20:16Z
806,422
<p>WebApp is really very basic.</p> <p>Django <code>url</code> templatetag is closely tied to its idea of URL resolving by matching regex patterns. As WebApp does not have any serious URL resolver, I imagine this would be really hard task to implement something in this line.</p> <p>But you are not totally out of luck. <a href="http://werkzeug.pocoo.org/" rel="nofollow">Werkzeug</a> has very easy to understand yet powerful URL routing mechanism that allows for reversing urls. You can try to base your implementation on this one (or throw away WebApp and use Werkzeug ;), it's really worth a try).</p>
1
2009-04-30T11:12:41Z
[ "python", "google-app-engine", "url", "templates", "web-applications" ]
how to avoid hard-coding urls in webapp templates
805,751
<p>I'm developing software on google app engine. I'm using the webapp framework. is there any way to avoid hard-coding urls in the html templates? django provides a solution, but I couldn't find one for webapp. thanks in advance..</p>
3
2009-04-30T07:20:16Z
5,691,622
<p>Webapp uses Django templates so: check out <a href="http://docs.djangoproject.com/en/1.3/ref/templates/builtin/#ref-templates-builtin-tags" rel="nofollow">Django templates here</a></p> <p>The Django solution <em>is</em> the web app solution.</p>
0
2011-04-17T05:08:25Z
[ "python", "google-app-engine", "url", "templates", "web-applications" ]
Sphinx automated image numbering/captions?
805,943
<p>Is there a way to automatically generate an image/figure caption using sphinx?</p> <p>I currently have rest-sphinx files I'm converting to html and (latex)pdf using sphinx.</p> <p>I'd like an easy way for users to reference a specific image in the resulting html/pdf files. For example, if a user is refering to the documentation in an email, "In 'Image 65' it says XXX, but this doesn't work for me".</p> <p>I've tried using <a href="http://docutils.sourceforge.net/docs/ref/rst/directives.html#id15" rel="nofollow">figure</a> where it appears to allow you to apply a caption to an image, but this has to be manually added. (And I have problems getting it to work with substitution for some reason).</p> <p>Is there a rest-sphinx method I'm overlooking that would achieve this? Or, is there a way to modify/edit sphinx's existing templates to add this ability?</p>
3
2009-04-30T08:37:39Z
806,080
<p>Sphinx consumes reStructuredText as templated by <a href="http://jinja.pocoo.org/2/documentation/" rel="nofollow">Jinja</a>. According to the Sphinx documentation though, you <a href="http://sphinx.pocoo.org/templating.html" rel="nofollow">have other templating options</a>.</p> <p>You should be able to use Jinja's <a href="http://jinja.pocoo.org/2/documentation/templates#list-of-control-structures" rel="nofollow">control structures</a> in a custom template to achieve the effect you're after.</p>
2
2009-04-30T09:23:29Z
[ "python", "templates", "python-sphinx" ]
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
<p>What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. </p> <p>Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks). </p>
19
2009-04-30T08:43:03Z
806,004
<p>Several years ago, I more or less learned web app programming on the job. C was the main language I knew, so I wrote the (fairly large-scale) web app in C. Bad mistake. C's string handling and memory management is tedious, and together with my lack of experience in web apps, it quickly became a hard-to-maintain project.</p> <p>C++ would be significantly better, mainly because <code>std::string</code> is much nicer than <code>char*</code>.</p> <p>However, now I'd use Python every time (though PHP is not a terrible choice, and perhaps easier to get started with). Python's string handling is awesome, and it handles Unicode seamlessly. Python has much better web tools and frameworks than C++, and its regex handling and standard libraries (urllib, email, etc) work very well. And you don't have to worry about memory management.</p> <p>I'd probably only use C or C++ for a web app if I was severely RAM-constrained (like on an embedded micro) or if I worked at Google and was coding a search engine that was going to have to respond to thousands of queries per second.</p>
20
2009-04-30T09:00:35Z
[ "php", "c++", "python", "perl", "fastcgi" ]
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
<p>What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. </p> <p>Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks). </p>
19
2009-04-30T08:43:03Z
806,037
<p>Using C++ is likely to result in a radically faster application than PHP, Perl or Python and somewhat faster than C# or Java - unless it spends most of its time waiting for the DB, in which case there won't be a difference. This is actually the most common case.</p> <p>On the other hand, due to the reasons benhoyt mentioned, developing a web app in C++ will take longer and will be harder to maintain. Furthermore, it's far more likely to contain serious security holes (nowadys everyone worries most about SQL injection and XSS - but if they were writing their webapps in C++ it would be buffer overflows and it would be their entire networks getting p0wned rather than just the data).</p> <p>And that's why almost nobody writes web apps in C++ these days.</p>
11
2009-04-30T09:08:44Z
[ "php", "c++", "python", "perl", "fastcgi" ]
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
<p>What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. </p> <p>Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks). </p>
19
2009-04-30T08:43:03Z
806,042
<p>You can use FastCGI with PHP/Python/Ruby/Perl to get runtime performance that should be enough until your site grows really big. And even then, you can make architectural improvements (database tuning, caching etc) to scale even more without abandoning scripting languages. Some pretty large sites are done in PHP/Python/Ruby/Perl.</p> <p>The big gain you get by using high-level languages is programmer performance. And that is what you should worry about first. It will be more important to respond quickly to feature demands from users, than to trim some milliseconds off the page response time.</p>
2
2009-04-30T09:09:41Z
[ "php", "c++", "python", "perl", "fastcgi" ]
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
<p>What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. </p> <p>Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks). </p>
19
2009-04-30T08:43:03Z
806,135
<p>I think that someone should be a pioneer in Webapp/C++ topic, to test the ground and provide proof of concept solutions.</p> <p>With arrival of STL and development of Boost parsing text happened to be extremely easy with C++. Two years ago, if I would have to parse CSV data I would use Python or PHP. Now I use C++ with STL/Boost. Reading CSV file into vectors? No problem, simple getline + boost::split + lexical_cast. Computing sum of data in a vector of pairs? No problem:</p> <pre><code>pair&lt;int, double&gt; sum_int_double(pair&lt;int,double&gt; &amp; total, pair&lt;struct in_addr, pair&lt;int,double&gt; &gt; &amp; a) { total.first += a.second.first; total.second += a.second.second; return total; } pair&lt;int,double&gt; mixedSum = accumulate(mixedVec.begin(), mixedVec.end(), emptyPair, sum_int_double); </code></pre> <p>Transferring data from map into vector of pairs? No problem:</p> <pre><code>mixedVec.assign(amap.begin(), amap.end()); </code></pre> <p>Everything is well defined and sharp. String operations, regexps, algorithms, OOP, etc. everything is well defined and mature in C++. If your app will be real app-like, and not parsing text-based, then C++ also good choice with its OOP features.</p>
8
2009-04-30T09:39:25Z
[ "php", "c++", "python", "perl", "fastcgi" ]
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
<p>What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. </p> <p>Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks). </p>
19
2009-04-30T08:43:03Z
806,181
<p>Having a FastCGI web application (no matter C++, PHP, Perl, Python, Ruby etc.) gives you better initial startup time than a CGI application. By <em>initial startup time</em> I mean the time elapsed between the time the web server receives the request and the time the the first code line you've written is run, so the initial startup time is the minimum time visitors of your web application have to wait for each request. It is not unusual to have an initial startup time of 1 second, especially if your application is large or you are using a large framework (such as Ruby on Rails). FastCGI keeps your applications running after it has responded to the first request, so FastCGI reduces the initial startup time of all subsequent requests (except for the very first one), usually down to a few milliseconds.</p> <p>If you use PHP, usually its default configuration provides a good enough initial response time (even without FastCGI), but please make sure you use a PHP accelerator on your production server (see <a href="http://en.wikipedia.org/wiki/PHP%5Faccelerator" rel="nofollow">http://en.wikipedia.org/wiki/PHP_accelerator</a>) to get better performance.</p> <p>Most programming languages and frameworks let you run the same application in different server modes (such as CGI, FastCGI, built-in webserver, Apache module), by changing the application's configurations, without changing the code. FastCGI is usually not the best choice while writing the application, because after you change the code, you may have to restart the application so it picks up your changes, but it is usually cumbersome to restart a FastCGI application. Restarting CGI or a built-in webserver is much easier. You should set up FastCGI only in the production configuration.</p>
4
2009-04-30T09:50:21Z
[ "php", "c++", "python", "perl", "fastcgi" ]
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
<p>What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. </p> <p>Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks). </p>
19
2009-04-30T08:43:03Z
806,195
<p>scripting languages may be slower than C, but is this a problem? almost never. and if the performance becomes a problem, you start to translate only the critical parts.</p> <p>twitter/ruby is a good example; ruby is slow. some of the language features (that make ruby nice in the first place) just prevent different kinds of optimization (there is a great article by the jruby guy about this ... was it ola bini? can't remember).</p> <p>still, twitter is powered by ruby, because ruby is <em>fast enough</em>. not long ago, "the blogs" reported twitter migrating to scala for performance reasons ... the truth was, only the messaging queue (and other parts of the backend) moved to scala. yahoo runs on a mixture of languages; php for the frontend, other, faster languages are used where performance is critical.</p> <p>so, why is performance not that important? there are several reasons:</p> <ul> <li>database bottleneck: not the scripting is slow, the database is</li> <li>clientside bottleneck: rendering in the browser takes longer than the request. optimize the server side, and nobody will notice</li> <li>horizontal scaling: often it's cheaper to add another server and thus triple the requests/sec than to optimize the app</li> <li>developer time and maintenance are the most expensive parts of your project. you'll get more cheap python devs that maintain your app than web-enabled c-coders in less time</li> <li>no compiling, short dev cycles</li> </ul> <p>another pro-scripting point: many of the scripting languages support inlining or inclusion of fast (C) code:</p> <ul> <li>python, inline c</li> <li>php: extensions in c</li> <li>server-side javascript via rhino: direct access to java/jvm <em>(a good example for this is orf.at, one of the biggest websites in austria, powered by <a href="http://dev.helma.org/">helma</a> - serverside jvm-interpreted javascript!)</em></li> </ul> <p>i think, especially in web developement the pros of high-level scripting far outweight the cons.</p>
30
2009-04-30T09:54:56Z
[ "php", "c++", "python", "perl", "fastcgi" ]
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
<p>What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. </p> <p>Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks). </p>
19
2009-04-30T08:43:03Z
806,257
<p>If you want to be able to implement web services in an existing running process (e.g. daemon), which is written in C/C++. It makes sense to make that process implement the FastCGI protocol for that interface. Get Apache to deal with HTTP (2-way SSL etc) to the outside world and field requests through FastCGI through a socket. If you do this in PHP, you have to get PHP to talk to your process, which means maintaining PHP code as well as your process.</p>
6
2009-04-30T10:10:36Z
[ "php", "c++", "python", "perl", "fastcgi" ]
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
<p>What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. </p> <p>Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks). </p>
19
2009-04-30T08:43:03Z
806,293
<p>The question is "where's the value created?"</p> <p>If you think the value is created in Memory management, careful class design and getting the nightly build to work, then use C++. You'll get to spend lots of time writing a lot of code to do important things like deleting objects that are no longer referenced.</p> <p>If you think the value is in deploying applications that people can use, then use Python with the Django framework. The Django tutorial shows you that within about 20 minutes you can have an application up and running. It's production-ready, and you could focus on important things:</p> <ul> <li><p>The model. Just write the model in Python, and the ORM layer handles all of the database interaction for you. No SQL. No manual mapping. </p></li> <li><p>The presentation. Just design your pages in HTML with a few <code>{{}}</code> "fill in a value here" and a few <code>{% for thing in object_list %}</code> constructs and your pages are ready to go. No string manipulation. </p></li> <li><p>The view functions. Write simple Python functions to encapsulate the processing part of your site. Not validation (those are in forms), not presentation (that was in the templates), not the underlying model (that was in the model classes), but a little bit of authorization checking, query processing and response formulation. Since Python has a rich set of collection classes, this code winds up being very short and to the point.</p></li> <li><p>Other stuff. URL mappings are Python regexes. Forms are matched to your model; you can subclass the defaults to add customized input validation and processing.</p></li> <li><p>Wonderful unit testing framework for low-level model features as well as end-to-end operations.</p></li> </ul> <p>No memory management, no scrupulous class design with abstracts and interfaces. No worrying about how to optimize string manipulation. No nightly build. Just create the stuff of real value.</p>
7
2009-04-30T10:21:35Z
[ "php", "c++", "python", "perl", "fastcgi" ]
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
<p>What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. </p> <p>Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks). </p>
19
2009-04-30T08:43:03Z
806,412
<p>There are people who asked this before: <a href="http://cppcms.sourceforge.net/wikipp/en/page/main" rel="nofollow">http://cppcms.sourceforge.net/wikipp/en/page/main</a></p> <p>CppCMS project provides a framework for web development using C++.</p> <p>You can take a look on following benchmarks to understand what is the difference: <a href="http://cppcms.sourceforge.net/wikipp/en/page/benchmarks" rel="nofollow">http://cppcms.sourceforge.net/wikipp/en/page/benchmarks</a> -- about two orders of magnitude.</p> <p>The problem of PHP/Python that they are very slow, there are many problems in caching data in FastCGI process of PHP.</p> <p>The biggest issue of C++ is a low amount of resources of development for Web in C++. However, taking a framework like CppCMS makes the life much simpler.</p>
3
2009-04-30T11:07:42Z
[ "php", "c++", "python", "perl", "fastcgi" ]
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
<p>What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. </p> <p>Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks). </p>
19
2009-04-30T08:43:03Z
806,988
<p>There is a middle ground here. Python (and I believe Perl and Ruby) allow you to call functions from C. 99 times out of 100, you won't need to. But it's nice to know that the option is there if you need it.</p> <p>Usually for webapps, the speed of the programming language simply isn't an issue. In the time it takes to execute a single database query, a processor can execute a few billion instructions. It's about the same for sending and receiving http data.</p>
3
2009-04-30T13:45:47Z
[ "php", "c++", "python", "perl", "fastcgi" ]
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
<p>What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. </p> <p>Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks). </p>
19
2009-04-30T08:43:03Z
1,321,663
<p>Too bad there are no benchmarks of C/C++ vs Perl CGI.<br /> Without FastCGI I think C/C++ would be a lot faster, with FastCGI possibly it'll be faster (but maybe a little less - all the initialization part is executed once).<br /> Again this is very <em>application</em> dependent, so some sort of benchmarks for different dynamic web pages should be provided.</p> <p>Personally I think that if your company has resources it should/could invest in C/C++ (given that they have to find proper ones...), otherwise is better to stick to a scripting language.<br /> Naturally if you want to deploy <em>fast</em> applications you should use C/C++.</p> <p>At the end of the day the compiled language is faster. But probably finding good C/C++ devs is hard nowdays?</p> <p>Cheers,</p>
1
2009-08-24T10:47:50Z
[ "php", "c++", "python", "perl", "fastcgi" ]
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
<p>What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. </p> <p>Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks). </p>
19
2009-04-30T08:43:03Z
1,470,204
<p>Well... You will save memory and CPU power with C/C++ vs Python/Perl/Ruby/Java/.NET. If the resources saved by using C/C++ represents a large fraction of the total resources available (a FastCGI running on the embedded board of a robot), then yeah, C/C++. Else, why bother ?</p>
2
2009-09-24T07:20:51Z
[ "php", "c++", "python", "perl", "fastcgi" ]
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
<p>What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. </p> <p>Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks). </p>
19
2009-04-30T08:43:03Z
1,979,362
<p>Probably someone of you could be interesting in Wt [1], a web toolkit entirely written in C++. It could be an alternative to cppCMS. I'm trying both in these christmas holidays..</p> <p>[1] <a href="http://www.webtoolkit.eu/wt" rel="nofollow">http://www.webtoolkit.eu/wt</a></p>
2
2009-12-30T10:00:47Z
[ "php", "c++", "python", "perl", "fastcgi" ]
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
<p>What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. </p> <p>Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks). </p>
19
2009-04-30T08:43:03Z
9,231,448
<p>C++ is a strongly typed language...i.e. you can declare ints, floats, etc....generally you can program more efficiently than you can with weakly typed languages. Facebook reported a 50% improvement when switching from PHP to C++. I would consider scripting languages to be prototyping languages...when you want production level efficiency use a compiled language.</p>
1
2012-02-10T16:48:03Z
[ "php", "c++", "python", "perl", "fastcgi" ]
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
<p>What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. </p> <p>Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks). </p>
19
2009-04-30T08:43:03Z
9,242,626
<p>My every search through Google indicates C/C++ gives best performance for web apps that need functionality such as searching for information in web pages or getting information from a database. </p>
0
2012-02-11T18:04:15Z
[ "php", "c++", "python", "perl", "fastcgi" ]
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
<p>What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. </p> <p>Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks). </p>
19
2009-04-30T08:43:03Z
9,242,979
<p>There are some new answers for this.</p> <ol> <li>If you need a compiled application, you might find that <a href="http://golang.org" rel="nofollow">Google's Go language</a> is a nice compiled language with modern features.</li> <li>Writing an application in a scripting language (I use Perl) can be done through frameworks like <a href="http://mojolicio.us" rel="nofollow"><code>Mojolicious</code></a> or <a href="http://perldancer.org" rel="nofollow"><code>Dancer</code></a>, and then by employing a <a href="http://plackperl.org" rel="nofollow">PSGI/Plack</a> controller it can run on CGI, FastCGI, mod_perl, native servers (like Hypnotoad from Mojolicious) or cloud deployment, all without modification. Similar concepts exist for other scripting languages.</li> </ol>
0
2012-02-11T18:44:30Z
[ "php", "c++", "python", "perl", "fastcgi" ]
How to hash a large object (dataset) in Python?
806,151
<p>I would like to calculate a hash of a Python class containing a dataset for Machine Learning. The hash is meant to be used for caching, so I was thinking of <code>md5</code> or <code>sha1</code>. The problem is that most of the data is stored in NumPy arrays; these do not provide a <code>__hash__()</code> member. Currently I do a <code>pickle.dumps()</code> for each member and calculate a hash based on these strings. However, I found the following links indicating that the same object could lead to different serialization strings:</p> <ul> <li><a href="http://www.gossamer-threads.com/lists/python/python/735907">Hash of None varies per machine</a></li> <li><a href="http://www.aminus.org/blogs/index.php/2007/11/03/pickle%5Fdumps%5Fnot%5Fsuitable%5Ffor%5Fhashing?blog=2">Pickle.dumps not suitable for hashing</a></li> </ul> <p>What would be the best method to calculate a hash for a Python class containing Numpy arrays?</p>
25
2009-04-30T09:43:57Z
806,286
<p>What's the format of the data in the arrays? Couldn't you just iterate through the arrays, convert them into a string (via some reproducible means) and then feed that into your hash via update?</p> <p>e.g.</p> <pre><code>import hashlib m = hashlib.md5() # or sha1 etc for value in array: # array contains the data m.update(str(value)) </code></pre> <p>Don't forget though that numpy arrays won't provide <code>__hash__()</code> because they are mutable. So be careful not to modify the arrays after your calculated your hash (as it will no longer be the same).</p>
3
2009-04-30T10:17:59Z
[ "python", "hash", "numpy", "sha1", "pickle" ]
How to hash a large object (dataset) in Python?
806,151
<p>I would like to calculate a hash of a Python class containing a dataset for Machine Learning. The hash is meant to be used for caching, so I was thinking of <code>md5</code> or <code>sha1</code>. The problem is that most of the data is stored in NumPy arrays; these do not provide a <code>__hash__()</code> member. Currently I do a <code>pickle.dumps()</code> for each member and calculate a hash based on these strings. However, I found the following links indicating that the same object could lead to different serialization strings:</p> <ul> <li><a href="http://www.gossamer-threads.com/lists/python/python/735907">Hash of None varies per machine</a></li> <li><a href="http://www.aminus.org/blogs/index.php/2007/11/03/pickle%5Fdumps%5Fnot%5Fsuitable%5Ffor%5Fhashing?blog=2">Pickle.dumps not suitable for hashing</a></li> </ul> <p>What would be the best method to calculate a hash for a Python class containing Numpy arrays?</p>
25
2009-04-30T09:43:57Z
806,342
<p>Thanks to John Montgomery I think I have found a solution, and I think it has less overhead than converting every number in possibly <em>huge</em> arrays to strings:</p> <p>I can create a byte-view of the arrays and use these to update the hash. And somehow this seems to give the same digest as directly updating using the array:</p> <pre><code>&gt;&gt;&gt; import hashlib &gt;&gt;&gt; import numpy &gt;&gt;&gt; a = numpy.random.rand(10, 100) &gt;&gt;&gt; b = a.view(numpy.uint8) &gt;&gt;&gt; print a.dtype, b.dtype # a and b have a different data type float64 uint8 &gt;&gt;&gt; hashlib.sha1(a).hexdigest() # byte view sha1 '794de7b1316b38d989a9040e6e26b9256ca3b5eb' &gt;&gt;&gt; hashlib.sha1(b).hexdigest() # array sha1 '794de7b1316b38d989a9040e6e26b9256ca3b5eb' </code></pre>
23
2009-04-30T10:42:19Z
[ "python", "hash", "numpy", "sha1", "pickle" ]
How to hash a large object (dataset) in Python?
806,151
<p>I would like to calculate a hash of a Python class containing a dataset for Machine Learning. The hash is meant to be used for caching, so I was thinking of <code>md5</code> or <code>sha1</code>. The problem is that most of the data is stored in NumPy arrays; these do not provide a <code>__hash__()</code> member. Currently I do a <code>pickle.dumps()</code> for each member and calculate a hash based on these strings. However, I found the following links indicating that the same object could lead to different serialization strings:</p> <ul> <li><a href="http://www.gossamer-threads.com/lists/python/python/735907">Hash of None varies per machine</a></li> <li><a href="http://www.aminus.org/blogs/index.php/2007/11/03/pickle%5Fdumps%5Fnot%5Fsuitable%5Ffor%5Fhashing?blog=2">Pickle.dumps not suitable for hashing</a></li> </ul> <p>What would be the best method to calculate a hash for a Python class containing Numpy arrays?</p>
25
2009-04-30T09:43:57Z
1,315,493
<p>array.data is always hashable, because it's a buffer object. easy :) (unless you care about the difference between differently-shaped arrays with the exact same data, etc.. (ie this is suitable unless shape, byteorder, and other array 'parameters' must also figure into the hash)</p>
1
2009-08-22T08:29:55Z
[ "python", "hash", "numpy", "sha1", "pickle" ]
How to hash a large object (dataset) in Python?
806,151
<p>I would like to calculate a hash of a Python class containing a dataset for Machine Learning. The hash is meant to be used for caching, so I was thinking of <code>md5</code> or <code>sha1</code>. The problem is that most of the data is stored in NumPy arrays; these do not provide a <code>__hash__()</code> member. Currently I do a <code>pickle.dumps()</code> for each member and calculate a hash based on these strings. However, I found the following links indicating that the same object could lead to different serialization strings:</p> <ul> <li><a href="http://www.gossamer-threads.com/lists/python/python/735907">Hash of None varies per machine</a></li> <li><a href="http://www.aminus.org/blogs/index.php/2007/11/03/pickle%5Fdumps%5Fnot%5Fsuitable%5Ffor%5Fhashing?blog=2">Pickle.dumps not suitable for hashing</a></li> </ul> <p>What would be the best method to calculate a hash for a Python class containing Numpy arrays?</p>
25
2009-04-30T09:43:57Z
5,463,871
<p>Here is how I do it in <a href="http://luispedro.org/software/jug" rel="nofollow" title="jug homepage">jug</a> (git HEAD at the time of this answer):</p> <pre><code>e = some_array_object M = hashlib.md5() M.update('np.ndarray') M.update(pickle.dumps(e.dtype)) M.update(pickle.dumps(e.shape)) try: buffer = e.data M.update(buffer) except: M.update(e.copy().data) </code></pre> <p>The reason is that <code>e.data</code> is only available for some arrays (contiguous arrays). Same thing with <code>a.view(np.uint8)</code> (which fails with a non-descriptive type error if the array is not contiguous).</p>
2
2011-03-28T19:14:09Z
[ "python", "hash", "numpy", "sha1", "pickle" ]
How to hash a large object (dataset) in Python?
806,151
<p>I would like to calculate a hash of a Python class containing a dataset for Machine Learning. The hash is meant to be used for caching, so I was thinking of <code>md5</code> or <code>sha1</code>. The problem is that most of the data is stored in NumPy arrays; these do not provide a <code>__hash__()</code> member. Currently I do a <code>pickle.dumps()</code> for each member and calculate a hash based on these strings. However, I found the following links indicating that the same object could lead to different serialization strings:</p> <ul> <li><a href="http://www.gossamer-threads.com/lists/python/python/735907">Hash of None varies per machine</a></li> <li><a href="http://www.aminus.org/blogs/index.php/2007/11/03/pickle%5Fdumps%5Fnot%5Fsuitable%5Ffor%5Fhashing?blog=2">Pickle.dumps not suitable for hashing</a></li> </ul> <p>What would be the best method to calculate a hash for a Python class containing Numpy arrays?</p>
25
2009-04-30T09:43:57Z
5,465,268
<p>There is a package for memoizing functions that use numpy arrays as inputs <a href="http://packages.python.org/joblib/memory.html" rel="nofollow">joblib</a>. Found from <a href="http://stackoverflow.com/questions/5362781/numpy-ndarray-memoization">this</a> question. </p>
3
2011-03-28T21:27:04Z
[ "python", "hash", "numpy", "sha1", "pickle" ]
How to hash a large object (dataset) in Python?
806,151
<p>I would like to calculate a hash of a Python class containing a dataset for Machine Learning. The hash is meant to be used for caching, so I was thinking of <code>md5</code> or <code>sha1</code>. The problem is that most of the data is stored in NumPy arrays; these do not provide a <code>__hash__()</code> member. Currently I do a <code>pickle.dumps()</code> for each member and calculate a hash based on these strings. However, I found the following links indicating that the same object could lead to different serialization strings:</p> <ul> <li><a href="http://www.gossamer-threads.com/lists/python/python/735907">Hash of None varies per machine</a></li> <li><a href="http://www.aminus.org/blogs/index.php/2007/11/03/pickle%5Fdumps%5Fnot%5Fsuitable%5Ffor%5Fhashing?blog=2">Pickle.dumps not suitable for hashing</a></li> </ul> <p>What would be the best method to calculate a hash for a Python class containing Numpy arrays?</p>
25
2009-04-30T09:43:57Z
19,457,314
<p>Fastest by some margin seems to be:</p> <blockquote> <blockquote> <blockquote> <p>hash(iter(a))</p> </blockquote> </blockquote> </blockquote> <p>a is a numpy ndarray.</p> <p>Obviously not secure hashing, but it should be good for caching etc.</p>
1
2013-10-18T19:08:40Z
[ "python", "hash", "numpy", "sha1", "pickle" ]
How to hash a large object (dataset) in Python?
806,151
<p>I would like to calculate a hash of a Python class containing a dataset for Machine Learning. The hash is meant to be used for caching, so I was thinking of <code>md5</code> or <code>sha1</code>. The problem is that most of the data is stored in NumPy arrays; these do not provide a <code>__hash__()</code> member. Currently I do a <code>pickle.dumps()</code> for each member and calculate a hash based on these strings. However, I found the following links indicating that the same object could lead to different serialization strings:</p> <ul> <li><a href="http://www.gossamer-threads.com/lists/python/python/735907">Hash of None varies per machine</a></li> <li><a href="http://www.aminus.org/blogs/index.php/2007/11/03/pickle%5Fdumps%5Fnot%5Fsuitable%5Ffor%5Fhashing?blog=2">Pickle.dumps not suitable for hashing</a></li> </ul> <p>What would be the best method to calculate a hash for a Python class containing Numpy arrays?</p>
25
2009-04-30T09:43:57Z
35,059,367
<p>Using Numpy 1.10.1 and python 2.7.6, you can now simply hash numpy arrays using hashlib if the array is C-contiguous (use <code>numpy.ascontiguousarray()</code> if not), e.g.</p> <pre><code>&gt;&gt;&gt; h = hashlib.md5() &gt;&gt;&gt; arr = numpy.arange(101) &gt;&gt;&gt; h.update(arr) &gt;&gt;&gt; print(h.hexdigest()) e62b430ff0f714181a18ea1a821b0918 </code></pre>
1
2016-01-28T10:50:28Z
[ "python", "hash", "numpy", "sha1", "pickle" ]
Can I encrypt email and decrypt it back using python default library set?
806,739
<p>Of course similar questions have been asked in stackoverflow but I don't want to use any third party library like Crypto or something. So I need to generate a ciphertext from a user email and decrypt it back to plaintext. How can I do this in python?</p>
6
2009-04-30T12:54:26Z
806,765
<p>Yes, you can. Read <a href="http://www.amk.ca/python/code/crypto.html" rel="nofollow">http://www.amk.ca/python/code/crypto.html</a> You'll find an answer there ;)</p> <p>You're question is not concrete enough to say more. You may want to read <a href="http://en.wikipedia.org/wiki/Cryptography#Modern_cryptography" rel="nofollow">http://en.wikipedia.org/wiki/Cryptography#Modern_cryptography</a></p> <p>Cheers, Tuergeist</p> <p>Update: No, you cannot. (with build in functionality due to export restrictions, see <a href="http://docs.python.org/library/crypto.html" rel="nofollow">http://docs.python.org/library/crypto.html</a>) But you can, if you're implementing you own algorithm (bad idea). So, the BEST solution is, to use the extension recommended by python core developers. See post above.</p> <p>Cheers again.</p>
3
2009-04-30T12:59:17Z
[ "python", "encryption" ]
Can I encrypt email and decrypt it back using python default library set?
806,739
<p>Of course similar questions have been asked in stackoverflow but I don't want to use any third party library like Crypto or something. So I need to generate a ciphertext from a user email and decrypt it back to plaintext. How can I do this in python?</p>
6
2009-04-30T12:54:26Z
806,955
<p>A third-party system is your best bet.<br /> If you really can't/don't want to use a third-party, maybe something simple would suffice.</p> <p>One of the simpler algorithms is the <a href="http://en.wikipedia.org/wiki/Tiny%5FEncryption%5FAlgorithm" rel="nofollow">Tiny Encryption Algorithm</a> (TEA). <a href="http://code.activestate.com/recipes/496737/" rel="nofollow">Here's an example of a Python implementation that you could start with.</a></p>
4
2009-04-30T13:38:11Z
[ "python", "encryption" ]
Can I encrypt email and decrypt it back using python default library set?
806,739
<p>Of course similar questions have been asked in stackoverflow but I don't want to use any third party library like Crypto or something. So I need to generate a ciphertext from a user email and decrypt it back to plaintext. How can I do this in python?</p>
6
2009-04-30T12:54:26Z
815,176
<p>If what you mean is that you want to roll your own encryption system, you could try using the built-in hmac and hashlib modules. (hashlib is new for 2.5, so if you must use an earlier Python, your hash choices are the older md5 and sha modules.)</p> <p>If you are opposed to <em>installing</em> a third-party library but are OK with using third-party algorithms or even "lightweight" third-party implementations of algorithms (e.g. published Python source code which resides in a single .py file that you can incorporate or import yourself without using setup.py or other <em>formal</em> installation), then I highly recommend you do so.</p> <p>The smallest and user-friendliest of these that I am aware of is <a href="http://www.nightsong.com/phr/crypto/p3.py" rel="nofollow">p3.py by Paul Rubin</a>. You could also try using <a href="http://bitconjurer.org/rijndael.py" rel="nofollow">rijndael.py</a>, which is an implementation of the AES algorithm.</p>
1
2009-05-02T16:47:55Z
[ "python", "encryption" ]
Django: Redirect to previous page after login
806,835
<p>I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I have to somehow pass the url of the current page to the view that handles the login form but I can't really get it to work.</p> <p>EDIT: I figured it out. I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks!</p> <p>EDIT 2: My explanation did not seem to be clear so as requested here is my code: Lets say we are on a page foo.html and we are not logged in. Now we would like to have a link on foo.html that links to login.html. There we can login and are then redirected back to foo.html. The link on foo.html looks like this:</p> <pre><code> &lt;a href='/login/?next={{ request.path }}'&gt;Login&lt;/a&gt; </code></pre> <p>Now I wrote a custom login view that looks somewhat like this:</p> <pre><code>def login_view(request): redirect_to = request.REQUEST.get('next', '') if request.method=='POST': #create login form... if valid login credentials have been entered: return HttpResponseRedirect(redirect_to) #... return render_to_response('login.html', locals()) </code></pre> <p>And the important line in login.html:</p> <pre><code>&lt;form method="post" action="./?next={{ redirect_to }}"&gt; </code></pre> <p>So yeah thats pretty much it, hope that makes it clear.</p>
129
2009-04-30T13:14:14Z
806,912
<p>Django's built-in authentication works the way you want.</p> <p>Their login pages include a <code>next</code> query string which is the page to return to after login.</p> <p>Look at <a href="http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.login_required">http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.login_required</a> </p>
13
2009-04-30T13:30:58Z
[ "python", "django" ]
Django: Redirect to previous page after login
806,835
<p>I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I have to somehow pass the url of the current page to the view that handles the login form but I can't really get it to work.</p> <p>EDIT: I figured it out. I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks!</p> <p>EDIT 2: My explanation did not seem to be clear so as requested here is my code: Lets say we are on a page foo.html and we are not logged in. Now we would like to have a link on foo.html that links to login.html. There we can login and are then redirected back to foo.html. The link on foo.html looks like this:</p> <pre><code> &lt;a href='/login/?next={{ request.path }}'&gt;Login&lt;/a&gt; </code></pre> <p>Now I wrote a custom login view that looks somewhat like this:</p> <pre><code>def login_view(request): redirect_to = request.REQUEST.get('next', '') if request.method=='POST': #create login form... if valid login credentials have been entered: return HttpResponseRedirect(redirect_to) #... return render_to_response('login.html', locals()) </code></pre> <p>And the important line in login.html:</p> <pre><code>&lt;form method="post" action="./?next={{ redirect_to }}"&gt; </code></pre> <p>So yeah thats pretty much it, hope that makes it clear.</p>
129
2009-04-30T13:14:14Z
806,918
<p>See django docs for <a href="http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.views.login" rel="nofollow">views.login()</a>, you supply a 'next' value (as a hidden field) on the input form to redirect to after a successful login.</p>
0
2009-04-30T13:31:30Z
[ "python", "django" ]
Django: Redirect to previous page after login
806,835
<p>I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I have to somehow pass the url of the current page to the view that handles the login form but I can't really get it to work.</p> <p>EDIT: I figured it out. I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks!</p> <p>EDIT 2: My explanation did not seem to be clear so as requested here is my code: Lets say we are on a page foo.html and we are not logged in. Now we would like to have a link on foo.html that links to login.html. There we can login and are then redirected back to foo.html. The link on foo.html looks like this:</p> <pre><code> &lt;a href='/login/?next={{ request.path }}'&gt;Login&lt;/a&gt; </code></pre> <p>Now I wrote a custom login view that looks somewhat like this:</p> <pre><code>def login_view(request): redirect_to = request.REQUEST.get('next', '') if request.method=='POST': #create login form... if valid login credentials have been entered: return HttpResponseRedirect(redirect_to) #... return render_to_response('login.html', locals()) </code></pre> <p>And the important line in login.html:</p> <pre><code>&lt;form method="post" action="./?next={{ redirect_to }}"&gt; </code></pre> <p>So yeah thats pretty much it, hope that makes it clear.</p>
129
2009-04-30T13:14:14Z
807,044
<p>I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks!</p>
1
2009-04-30T13:58:45Z
[ "python", "django" ]
Django: Redirect to previous page after login
806,835
<p>I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I have to somehow pass the url of the current page to the view that handles the login form but I can't really get it to work.</p> <p>EDIT: I figured it out. I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks!</p> <p>EDIT 2: My explanation did not seem to be clear so as requested here is my code: Lets say we are on a page foo.html and we are not logged in. Now we would like to have a link on foo.html that links to login.html. There we can login and are then redirected back to foo.html. The link on foo.html looks like this:</p> <pre><code> &lt;a href='/login/?next={{ request.path }}'&gt;Login&lt;/a&gt; </code></pre> <p>Now I wrote a custom login view that looks somewhat like this:</p> <pre><code>def login_view(request): redirect_to = request.REQUEST.get('next', '') if request.method=='POST': #create login form... if valid login credentials have been entered: return HttpResponseRedirect(redirect_to) #... return render_to_response('login.html', locals()) </code></pre> <p>And the important line in login.html:</p> <pre><code>&lt;form method="post" action="./?next={{ redirect_to }}"&gt; </code></pre> <p>So yeah thats pretty much it, hope that makes it clear.</p>
129
2009-04-30T13:14:14Z
808,096
<p>This may not be a "best practice", but I've successfully used this before:</p> <pre><code>return HttpResponseRedirect(request.META.get('HTTP_REFERER','/')) </code></pre>
24
2009-04-30T17:22:31Z
[ "python", "django" ]
Django: Redirect to previous page after login
806,835
<p>I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I have to somehow pass the url of the current page to the view that handles the login form but I can't really get it to work.</p> <p>EDIT: I figured it out. I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks!</p> <p>EDIT 2: My explanation did not seem to be clear so as requested here is my code: Lets say we are on a page foo.html and we are not logged in. Now we would like to have a link on foo.html that links to login.html. There we can login and are then redirected back to foo.html. The link on foo.html looks like this:</p> <pre><code> &lt;a href='/login/?next={{ request.path }}'&gt;Login&lt;/a&gt; </code></pre> <p>Now I wrote a custom login view that looks somewhat like this:</p> <pre><code>def login_view(request): redirect_to = request.REQUEST.get('next', '') if request.method=='POST': #create login form... if valid login credentials have been entered: return HttpResponseRedirect(redirect_to) #... return render_to_response('login.html', locals()) </code></pre> <p>And the important line in login.html:</p> <pre><code>&lt;form method="post" action="./?next={{ redirect_to }}"&gt; </code></pre> <p>So yeah thats pretty much it, hope that makes it clear.</p>
129
2009-04-30T13:14:14Z
1,711,592
<p>You do not need to make an extra view for this, the functionality is already built in.</p> <p>First each page with a login link needs to know the current path, and the easiest way is to add the request context preprosessor to settings.py (the 4 first are default), then the request object will be available in each request:</p> <p><strong>settings.py:</strong></p> <pre><code>TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.request", ) </code></pre> <p>Then add in the template you want the Login link:</p> <p><strong>base.html:</strong></p> <pre><code>&lt;a href="{% url django.contrib.auth.views.login %}?next={{request.path}}"&gt;Login&lt;/a&gt; </code></pre> <p>This will add a GET argument to the login page that points back to the current page.</p> <p>The login template can then be as simple as this:</p> <p><strong>registration/login.html:</strong></p> <pre><code>{% block content %} &lt;form method="post" action=""&gt; {{form.as_p}} &lt;input type="submit" value="Login"&gt; &lt;/form&gt; {% endblock %} </code></pre>
105
2009-11-10T22:09:23Z
[ "python", "django" ]
Django: Redirect to previous page after login
806,835
<p>I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I have to somehow pass the url of the current page to the view that handles the login form but I can't really get it to work.</p> <p>EDIT: I figured it out. I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks!</p> <p>EDIT 2: My explanation did not seem to be clear so as requested here is my code: Lets say we are on a page foo.html and we are not logged in. Now we would like to have a link on foo.html that links to login.html. There we can login and are then redirected back to foo.html. The link on foo.html looks like this:</p> <pre><code> &lt;a href='/login/?next={{ request.path }}'&gt;Login&lt;/a&gt; </code></pre> <p>Now I wrote a custom login view that looks somewhat like this:</p> <pre><code>def login_view(request): redirect_to = request.REQUEST.get('next', '') if request.method=='POST': #create login form... if valid login credentials have been entered: return HttpResponseRedirect(redirect_to) #... return render_to_response('login.html', locals()) </code></pre> <p>And the important line in login.html:</p> <pre><code>&lt;form method="post" action="./?next={{ redirect_to }}"&gt; </code></pre> <p>So yeah thats pretty much it, hope that makes it clear.</p>
129
2009-04-30T13:14:14Z
2,388,056
<p>I encountered the same problem. This solution allows me to keep using the generic login view:</p> <pre><code>urlpatterns += patterns('django.views.generic.simple', (r'^accounts/profile/$', 'redirect_to', {'url': 'generic_account_url'}), ) </code></pre>
1
2010-03-05T16:00:32Z
[ "python", "django" ]
Django: Redirect to previous page after login
806,835
<p>I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I have to somehow pass the url of the current page to the view that handles the login form but I can't really get it to work.</p> <p>EDIT: I figured it out. I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks!</p> <p>EDIT 2: My explanation did not seem to be clear so as requested here is my code: Lets say we are on a page foo.html and we are not logged in. Now we would like to have a link on foo.html that links to login.html. There we can login and are then redirected back to foo.html. The link on foo.html looks like this:</p> <pre><code> &lt;a href='/login/?next={{ request.path }}'&gt;Login&lt;/a&gt; </code></pre> <p>Now I wrote a custom login view that looks somewhat like this:</p> <pre><code>def login_view(request): redirect_to = request.REQUEST.get('next', '') if request.method=='POST': #create login form... if valid login credentials have been entered: return HttpResponseRedirect(redirect_to) #... return render_to_response('login.html', locals()) </code></pre> <p>And the important line in login.html:</p> <pre><code>&lt;form method="post" action="./?next={{ redirect_to }}"&gt; </code></pre> <p>So yeah thats pretty much it, hope that makes it clear.</p>
129
2009-04-30T13:14:14Z
9,110,314
<p>In <code>registration/login.html</code> (nested within <code>templates</code> folder) if you insert the following line, the page will render like Django's original admin login page:</p> <pre><code>{% include "admin/login.html" %} </code></pre> <p><b>Note: The file should contain above lines only.</b></p>
1
2012-02-02T09:59:51Z
[ "python", "django" ]
Django: Redirect to previous page after login
806,835
<p>I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I have to somehow pass the url of the current page to the view that handles the login form but I can't really get it to work.</p> <p>EDIT: I figured it out. I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks!</p> <p>EDIT 2: My explanation did not seem to be clear so as requested here is my code: Lets say we are on a page foo.html and we are not logged in. Now we would like to have a link on foo.html that links to login.html. There we can login and are then redirected back to foo.html. The link on foo.html looks like this:</p> <pre><code> &lt;a href='/login/?next={{ request.path }}'&gt;Login&lt;/a&gt; </code></pre> <p>Now I wrote a custom login view that looks somewhat like this:</p> <pre><code>def login_view(request): redirect_to = request.REQUEST.get('next', '') if request.method=='POST': #create login form... if valid login credentials have been entered: return HttpResponseRedirect(redirect_to) #... return render_to_response('login.html', locals()) </code></pre> <p>And the important line in login.html:</p> <pre><code>&lt;form method="post" action="./?next={{ redirect_to }}"&gt; </code></pre> <p>So yeah thats pretty much it, hope that makes it clear.</p>
129
2009-04-30T13:14:14Z
13,595,154
<p>To support full urls with param/values you'd need:</p> <pre><code>?next={{ request.get_full_path|urlencode }} </code></pre> <p>instead of just:</p> <pre><code>?next={{ request.path }} </code></pre>
17
2012-11-27T23:33:01Z
[ "python", "django" ]
Django: Redirect to previous page after login
806,835
<p>I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I have to somehow pass the url of the current page to the view that handles the login form but I can't really get it to work.</p> <p>EDIT: I figured it out. I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks!</p> <p>EDIT 2: My explanation did not seem to be clear so as requested here is my code: Lets say we are on a page foo.html and we are not logged in. Now we would like to have a link on foo.html that links to login.html. There we can login and are then redirected back to foo.html. The link on foo.html looks like this:</p> <pre><code> &lt;a href='/login/?next={{ request.path }}'&gt;Login&lt;/a&gt; </code></pre> <p>Now I wrote a custom login view that looks somewhat like this:</p> <pre><code>def login_view(request): redirect_to = request.REQUEST.get('next', '') if request.method=='POST': #create login form... if valid login credentials have been entered: return HttpResponseRedirect(redirect_to) #... return render_to_response('login.html', locals()) </code></pre> <p>And the important line in login.html:</p> <pre><code>&lt;form method="post" action="./?next={{ redirect_to }}"&gt; </code></pre> <p>So yeah thats pretty much it, hope that makes it clear.</p>
129
2009-04-30T13:14:14Z
16,597,099
<p>You can also do this</p> <pre><code>&lt;input type="hidden" name="text" value="{% url 'dashboard' %}" /&gt; </code></pre>
-2
2013-05-16T20:42:24Z
[ "python", "django" ]
Python equivalent of Perl's while (<>) {...}?
807,173
<p>I write a lot of little scripts that process files on a line-by-line basis. In Perl, I use</p> <pre><code>while (&lt;&gt;) { do stuff; } </code></pre> <p>This is handy because it doesn't care where the input comes from (a file or stdin).</p> <p>In Python I use this</p> <pre><code>if len(sys.argv) == 2: # there's a command line argument sys.stdin = file(sys.argv[1]) for line in sys.stdin.readlines(): do stuff </code></pre> <p>which doesn't seem very elegant. Is there a Python idiom that easily handles file/stdin input?</p>
20
2009-04-30T14:23:46Z
807,190
<p>The fileinput module in the standard library is just what you want:</p> <pre><code>import fileinput for line in fileinput.input(): ... </code></pre>
48
2009-04-30T14:26:51Z
[ "python", "stdin" ]
Python equivalent of Perl's while (<>) {...}?
807,173
<p>I write a lot of little scripts that process files on a line-by-line basis. In Perl, I use</p> <pre><code>while (&lt;&gt;) { do stuff; } </code></pre> <p>This is handy because it doesn't care where the input comes from (a file or stdin).</p> <p>In Python I use this</p> <pre><code>if len(sys.argv) == 2: # there's a command line argument sys.stdin = file(sys.argv[1]) for line in sys.stdin.readlines(): do stuff </code></pre> <p>which doesn't seem very elegant. Is there a Python idiom that easily handles file/stdin input?</p>
20
2009-04-30T14:23:46Z
807,196
<pre><code>import fileinput for line in fileinput.input(): process(line) </code></pre> <p>This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty.</p>
15
2009-04-30T14:27:48Z
[ "python", "stdin" ]
Python equivalent of Perl's while (<>) {...}?
807,173
<p>I write a lot of little scripts that process files on a line-by-line basis. In Perl, I use</p> <pre><code>while (&lt;&gt;) { do stuff; } </code></pre> <p>This is handy because it doesn't care where the input comes from (a file or stdin).</p> <p>In Python I use this</p> <pre><code>if len(sys.argv) == 2: # there's a command line argument sys.stdin = file(sys.argv[1]) for line in sys.stdin.readlines(): do stuff </code></pre> <p>which doesn't seem very elegant. Is there a Python idiom that easily handles file/stdin input?</p>
20
2009-04-30T14:23:46Z
807,210
<p><a href="http://docs.python.org/library/fileinput.html">fileinput</a> defaults to stdin, so would make it slightly more concise.</p> <p>If you do a lot of command-line stuff, though, this <a href="http://code.activestate.com/recipes/276960/">piping hack</a> is very neat.</p>
7
2009-04-30T14:31:06Z
[ "python", "stdin" ]
Where is the phpMailer php class equivalent for Python?
807,302
<p>i'm new with python.. Actually, i'm trying to send featured email with python: html body, text alternative body, and attachment.</p> <p>So, i've found this <a href="http://code.activestate.com/recipes/67083/" rel="nofollow" title="tutorial 1">tutorial</a> and adapted it with the gmail authentication (tutorial found <a href="http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html" rel="nofollow" title="tutorial 2">here</a>)</p> <p>The code i have atm, is that:</p> <pre><code>def createhtmlmail (html, text, subject): """Create a mime-message that will render HTML in popular MUAs, text in better ones""" import MimeWriter import mimetools import cStringIO from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders import os out = cStringIO.StringIO() # output buffer for our message htmlin = cStringIO.StringIO(html) txtin = cStringIO.StringIO(text) writer = MimeWriter.MimeWriter(out) # # set up some basic headers... we put subject here # because smtplib.sendmail expects it to be in the # message body # writer.addheader("Subject", subject) writer.addheader("MIME-Version", "1.0") # # start the multipart section of the message # multipart/alternative seems to work better # on some MUAs than multipart/mixed # writer.startmultipartbody("alternative") writer.flushheaders() # # the plain text section # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") pout = subpart.startbody("text/plain", [("charset", 'us-ascii')]) mimetools.encode(txtin, pout, 'quoted-printable') txtin.close() # # start the html subpart of the message # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") # # returns us a file-ish object we can write to # pout = subpart.startbody("text/html", [("charset", 'us-ascii')]) mimetools.encode(htmlin, pout, 'quoted-printable') htmlin.close() # # Now that we're done, close our writer and # return the message body # writer.lastpart() msg = out.getvalue() out.close() return msg import smtplib f = open("/path/to/html/version.html", 'r') html = f.read() f.close() f = open("/path/to/txt/version.txt", 'r') text = f.read() subject = "Prova email html da python, con allegato!" message = createhtmlmail(html, text, subject) gmail_user = "thegmailaccount@gmail.com" gmail_pwd = "thegmailpassword" server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.ehlo() server.login(gmail_user, gmail_pwd) server.sendmail(gmail_user, "example@example.com", message) server.close() </code></pre> <p>and that works.. now only miss the attachment.. And i am not able to add the attachment (from <a href="http://snippets.dzone.com/posts/show/757" rel="nofollow" title="attachments">this</a> post)</p> <p>So, why there is not a python class like phpMailer for php? Is it because, for a medium-able python programmer sending a html email with attachment and alt text body is so easy that a class is not needed? Or is because i just didn't find it?</p> <p>If i'll be able to wrote a class like that, when i'll be enough good with python, would that be useful for someone?</p>
3
2009-04-30T14:48:42Z
807,362
<p>I recommend reading the <a href="http://james.apache.org/server/rfclist/smtp/rfc0821.txt" rel="nofollow">SMTP rfc</a>. A google search shows that this can easily be done by using the MimeMultipart class which you are importing but never using. Here are <a href="http://docs.python.org/library/email-examples.html" rel="nofollow">some examples</a> on Python's documentation site.</p>
0
2009-04-30T15:00:06Z
[ "python", "email", "phpmailer" ]
Where is the phpMailer php class equivalent for Python?
807,302
<p>i'm new with python.. Actually, i'm trying to send featured email with python: html body, text alternative body, and attachment.</p> <p>So, i've found this <a href="http://code.activestate.com/recipes/67083/" rel="nofollow" title="tutorial 1">tutorial</a> and adapted it with the gmail authentication (tutorial found <a href="http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html" rel="nofollow" title="tutorial 2">here</a>)</p> <p>The code i have atm, is that:</p> <pre><code>def createhtmlmail (html, text, subject): """Create a mime-message that will render HTML in popular MUAs, text in better ones""" import MimeWriter import mimetools import cStringIO from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders import os out = cStringIO.StringIO() # output buffer for our message htmlin = cStringIO.StringIO(html) txtin = cStringIO.StringIO(text) writer = MimeWriter.MimeWriter(out) # # set up some basic headers... we put subject here # because smtplib.sendmail expects it to be in the # message body # writer.addheader("Subject", subject) writer.addheader("MIME-Version", "1.0") # # start the multipart section of the message # multipart/alternative seems to work better # on some MUAs than multipart/mixed # writer.startmultipartbody("alternative") writer.flushheaders() # # the plain text section # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") pout = subpart.startbody("text/plain", [("charset", 'us-ascii')]) mimetools.encode(txtin, pout, 'quoted-printable') txtin.close() # # start the html subpart of the message # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") # # returns us a file-ish object we can write to # pout = subpart.startbody("text/html", [("charset", 'us-ascii')]) mimetools.encode(htmlin, pout, 'quoted-printable') htmlin.close() # # Now that we're done, close our writer and # return the message body # writer.lastpart() msg = out.getvalue() out.close() return msg import smtplib f = open("/path/to/html/version.html", 'r') html = f.read() f.close() f = open("/path/to/txt/version.txt", 'r') text = f.read() subject = "Prova email html da python, con allegato!" message = createhtmlmail(html, text, subject) gmail_user = "thegmailaccount@gmail.com" gmail_pwd = "thegmailpassword" server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.ehlo() server.login(gmail_user, gmail_pwd) server.sendmail(gmail_user, "example@example.com", message) server.close() </code></pre> <p>and that works.. now only miss the attachment.. And i am not able to add the attachment (from <a href="http://snippets.dzone.com/posts/show/757" rel="nofollow" title="attachments">this</a> post)</p> <p>So, why there is not a python class like phpMailer for php? Is it because, for a medium-able python programmer sending a html email with attachment and alt text body is so easy that a class is not needed? Or is because i just didn't find it?</p> <p>If i'll be able to wrote a class like that, when i'll be enough good with python, would that be useful for someone?</p>
3
2009-04-30T14:48:42Z
807,475
<p>Django includes the class you need in core, <a href="http://docs.djangoproject.com/en/dev/topics/email/#sending-alternative-content-types" rel="nofollow">docs here</a></p> <pre><code>from django.core.mail import EmailMultiAlternatives subject, from_email, to = 'hello', 'from@example.com', 'to@example.com' text_content = 'This is an important message.' html_content = '&lt;p&gt;This is an &lt;strong&gt;important&lt;/strong&gt; message.&lt;/p&gt;' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.attach_file('/path/to/file.jpg') msg.send() </code></pre> <p>In my settings I have:</p> <pre><code>#GMAIL STUFF EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'name@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 </code></pre>
2
2009-04-30T15:22:33Z
[ "python", "email", "phpmailer" ]
Where is the phpMailer php class equivalent for Python?
807,302
<p>i'm new with python.. Actually, i'm trying to send featured email with python: html body, text alternative body, and attachment.</p> <p>So, i've found this <a href="http://code.activestate.com/recipes/67083/" rel="nofollow" title="tutorial 1">tutorial</a> and adapted it with the gmail authentication (tutorial found <a href="http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html" rel="nofollow" title="tutorial 2">here</a>)</p> <p>The code i have atm, is that:</p> <pre><code>def createhtmlmail (html, text, subject): """Create a mime-message that will render HTML in popular MUAs, text in better ones""" import MimeWriter import mimetools import cStringIO from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders import os out = cStringIO.StringIO() # output buffer for our message htmlin = cStringIO.StringIO(html) txtin = cStringIO.StringIO(text) writer = MimeWriter.MimeWriter(out) # # set up some basic headers... we put subject here # because smtplib.sendmail expects it to be in the # message body # writer.addheader("Subject", subject) writer.addheader("MIME-Version", "1.0") # # start the multipart section of the message # multipart/alternative seems to work better # on some MUAs than multipart/mixed # writer.startmultipartbody("alternative") writer.flushheaders() # # the plain text section # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") pout = subpart.startbody("text/plain", [("charset", 'us-ascii')]) mimetools.encode(txtin, pout, 'quoted-printable') txtin.close() # # start the html subpart of the message # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") # # returns us a file-ish object we can write to # pout = subpart.startbody("text/html", [("charset", 'us-ascii')]) mimetools.encode(htmlin, pout, 'quoted-printable') htmlin.close() # # Now that we're done, close our writer and # return the message body # writer.lastpart() msg = out.getvalue() out.close() return msg import smtplib f = open("/path/to/html/version.html", 'r') html = f.read() f.close() f = open("/path/to/txt/version.txt", 'r') text = f.read() subject = "Prova email html da python, con allegato!" message = createhtmlmail(html, text, subject) gmail_user = "thegmailaccount@gmail.com" gmail_pwd = "thegmailpassword" server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.ehlo() server.login(gmail_user, gmail_pwd) server.sendmail(gmail_user, "example@example.com", message) server.close() </code></pre> <p>and that works.. now only miss the attachment.. And i am not able to add the attachment (from <a href="http://snippets.dzone.com/posts/show/757" rel="nofollow" title="attachments">this</a> post)</p> <p>So, why there is not a python class like phpMailer for php? Is it because, for a medium-able python programmer sending a html email with attachment and alt text body is so easy that a class is not needed? Or is because i just didn't find it?</p> <p>If i'll be able to wrote a class like that, when i'll be enough good with python, would that be useful for someone?</p>
3
2009-04-30T14:48:42Z
807,988
<p>If you can excuse some blatant self promotion, I wrote a <a href="http://pypi.python.org/pypi/mailer/0.3" rel="nofollow">mailer module</a> that makes sending email with Python fairly simple. No dependencies other than the Python smtplib and email libraries.</p> <p>Here's a simple example for sending an email with an attachment:</p> <pre><code>from mailer import Mailer from mailer import Message message = Message(From="me@example.com", To=["you@example.com", "him@example.com"]) message.Subject = "Kitty with dynamite" message.Body = """Kitty go boom!""" message.attach("kitty.jpg") sender = Mailer('smtp.example.com') sender.login("username", "password") sender.send(message) </code></pre> <p><strong>Edit</strong>: Here's an example of sending an HTML email with alternate text. :)</p> <pre><code>from mailer import Mailer from mailer import Message message = Message(From="me@example.com", To="you@example.com", charset="utf-8") message.Subject = "An HTML Email" message.Html = """This email uses &lt;strong&gt;HTML&lt;/strong&gt;!""" message.Body = """This is alternate text.""" sender = Mailer('smtp.example.com') sender.send(message) </code></pre> <p><strong>Edit 2</strong>: Thanks to one of the comments, I've added a new version of mailer to pypi that lets you specify the port in the Mailer class.</p>
5
2009-04-30T16:56:26Z
[ "python", "email", "phpmailer" ]
Where is the phpMailer php class equivalent for Python?
807,302
<p>i'm new with python.. Actually, i'm trying to send featured email with python: html body, text alternative body, and attachment.</p> <p>So, i've found this <a href="http://code.activestate.com/recipes/67083/" rel="nofollow" title="tutorial 1">tutorial</a> and adapted it with the gmail authentication (tutorial found <a href="http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html" rel="nofollow" title="tutorial 2">here</a>)</p> <p>The code i have atm, is that:</p> <pre><code>def createhtmlmail (html, text, subject): """Create a mime-message that will render HTML in popular MUAs, text in better ones""" import MimeWriter import mimetools import cStringIO from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders import os out = cStringIO.StringIO() # output buffer for our message htmlin = cStringIO.StringIO(html) txtin = cStringIO.StringIO(text) writer = MimeWriter.MimeWriter(out) # # set up some basic headers... we put subject here # because smtplib.sendmail expects it to be in the # message body # writer.addheader("Subject", subject) writer.addheader("MIME-Version", "1.0") # # start the multipart section of the message # multipart/alternative seems to work better # on some MUAs than multipart/mixed # writer.startmultipartbody("alternative") writer.flushheaders() # # the plain text section # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") pout = subpart.startbody("text/plain", [("charset", 'us-ascii')]) mimetools.encode(txtin, pout, 'quoted-printable') txtin.close() # # start the html subpart of the message # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") # # returns us a file-ish object we can write to # pout = subpart.startbody("text/html", [("charset", 'us-ascii')]) mimetools.encode(htmlin, pout, 'quoted-printable') htmlin.close() # # Now that we're done, close our writer and # return the message body # writer.lastpart() msg = out.getvalue() out.close() return msg import smtplib f = open("/path/to/html/version.html", 'r') html = f.read() f.close() f = open("/path/to/txt/version.txt", 'r') text = f.read() subject = "Prova email html da python, con allegato!" message = createhtmlmail(html, text, subject) gmail_user = "thegmailaccount@gmail.com" gmail_pwd = "thegmailpassword" server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.ehlo() server.login(gmail_user, gmail_pwd) server.sendmail(gmail_user, "example@example.com", message) server.close() </code></pre> <p>and that works.. now only miss the attachment.. And i am not able to add the attachment (from <a href="http://snippets.dzone.com/posts/show/757" rel="nofollow" title="attachments">this</a> post)</p> <p>So, why there is not a python class like phpMailer for php? Is it because, for a medium-able python programmer sending a html email with attachment and alt text body is so easy that a class is not needed? Or is because i just didn't find it?</p> <p>If i'll be able to wrote a class like that, when i'll be enough good with python, would that be useful for someone?</p>
3
2009-04-30T14:48:42Z
895,352
<p>Maybe you can try with <strong>turbomail</strong> python-turbomail.org</p> <p>It's more easy and useful :) </p> <pre><code>import turbomail # ... message = turbomail.Message("from@example.com", "to@example.com", subject) message.plain = "Hello world!" turbomail.enqueue(message) </code></pre>
1
2009-05-21T21:45:25Z
[ "python", "email", "phpmailer" ]
Where is the phpMailer php class equivalent for Python?
807,302
<p>i'm new with python.. Actually, i'm trying to send featured email with python: html body, text alternative body, and attachment.</p> <p>So, i've found this <a href="http://code.activestate.com/recipes/67083/" rel="nofollow" title="tutorial 1">tutorial</a> and adapted it with the gmail authentication (tutorial found <a href="http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html" rel="nofollow" title="tutorial 2">here</a>)</p> <p>The code i have atm, is that:</p> <pre><code>def createhtmlmail (html, text, subject): """Create a mime-message that will render HTML in popular MUAs, text in better ones""" import MimeWriter import mimetools import cStringIO from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders import os out = cStringIO.StringIO() # output buffer for our message htmlin = cStringIO.StringIO(html) txtin = cStringIO.StringIO(text) writer = MimeWriter.MimeWriter(out) # # set up some basic headers... we put subject here # because smtplib.sendmail expects it to be in the # message body # writer.addheader("Subject", subject) writer.addheader("MIME-Version", "1.0") # # start the multipart section of the message # multipart/alternative seems to work better # on some MUAs than multipart/mixed # writer.startmultipartbody("alternative") writer.flushheaders() # # the plain text section # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") pout = subpart.startbody("text/plain", [("charset", 'us-ascii')]) mimetools.encode(txtin, pout, 'quoted-printable') txtin.close() # # start the html subpart of the message # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") # # returns us a file-ish object we can write to # pout = subpart.startbody("text/html", [("charset", 'us-ascii')]) mimetools.encode(htmlin, pout, 'quoted-printable') htmlin.close() # # Now that we're done, close our writer and # return the message body # writer.lastpart() msg = out.getvalue() out.close() return msg import smtplib f = open("/path/to/html/version.html", 'r') html = f.read() f.close() f = open("/path/to/txt/version.txt", 'r') text = f.read() subject = "Prova email html da python, con allegato!" message = createhtmlmail(html, text, subject) gmail_user = "thegmailaccount@gmail.com" gmail_pwd = "thegmailpassword" server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.ehlo() server.login(gmail_user, gmail_pwd) server.sendmail(gmail_user, "example@example.com", message) server.close() </code></pre> <p>and that works.. now only miss the attachment.. And i am not able to add the attachment (from <a href="http://snippets.dzone.com/posts/show/757" rel="nofollow" title="attachments">this</a> post)</p> <p>So, why there is not a python class like phpMailer for php? Is it because, for a medium-able python programmer sending a html email with attachment and alt text body is so easy that a class is not needed? Or is because i just didn't find it?</p> <p>If i'll be able to wrote a class like that, when i'll be enough good with python, would that be useful for someone?</p>
3
2009-04-30T14:48:42Z
2,276,417
<p>Just want to point to <a href="http://lamsonproject.org/" rel="nofollow">Lamson Project</a> which was what I was looking for when I found this thread. I did some more searching and found it. It's:</p> <blockquote> <p>Lamson's goal is to put an end to the hell that is "e-mail application development". Rather than stay stuck in the 1970s, Lamson adopts modern web application framework design and uses a proven scripting language (Python).</p> </blockquote> <p>It integrates nicely with Django. But it's more made for email based applications. It looks like pure love though.</p>
2
2010-02-16T21:18:21Z
[ "python", "email", "phpmailer" ]
Django m2m queries, distinct Users for a m2m relationship of a Model
807,470
<p>I have a model Model with a m2m field : </p> <pre><code>user = .. fk user ... watchers = models.ManyToManyField(User, related_name="boardShot_watchers", null=True) </code></pre> <p>How do i select all distinct Users involved in this watchers relationship for all my entries of type Model ?</p> <p>I dont think there is an ORM way to access to intermediary M2M table.</p> <p>Greg</p>
1
2009-04-30T15:21:37Z
807,562
<p>Not in your current model. If you want to have explicit access to the joining table, you need to make it part of the Django object model. The docs explain how to do this:</p> <p><a href="http://www.djangoproject.com/documentation/models/m2m_intermediary/" rel="nofollow">http://www.djangoproject.com/documentation/models/m2m_intermediary/</a></p> <p>The admin and other django.contrib* components can be configured to treat most fields the same as if they were just model.ManyToMany's. But it will take a little config. </p>
2
2009-04-30T15:37:33Z
[ "python", "django", "orm", "m2m" ]
How to output list of floats to a binary file in Python
807,863
<p>I have a list of floating-point values in Python:</p> <pre><code>floats = [3.14, 2.7, 0.0, -1.0, 1.1] </code></pre> <p>I would like to write these values out to a binary file using IEEE 32-bit encoding. What is the best way to do this in Python? My list actually contains about 200 MB of data, so something "not too slow" would be best.</p> <p>Since there are 5 values, I just want a 20-byte file as output.</p>
17
2009-04-30T16:35:43Z
807,874
<p>have a look at <a href="http://docs.python.org/library/struct.html?highlight=struct#struct.pack%5Finto" rel="nofollow"><code>struct.pack_into</code></a></p>
3
2009-04-30T16:38:02Z
[ "python", "file-io" ]
How to output list of floats to a binary file in Python
807,863
<p>I have a list of floating-point values in Python:</p> <pre><code>floats = [3.14, 2.7, 0.0, -1.0, 1.1] </code></pre> <p>I would like to write these values out to a binary file using IEEE 32-bit encoding. What is the best way to do this in Python? My list actually contains about 200 MB of data, so something "not too slow" would be best.</p> <p>Since there are 5 values, I just want a 20-byte file as output.</p>
17
2009-04-30T16:35:43Z
807,881
<p>See: <a href="http://docs.python.org/library/struct.html">Python's struct module</a></p> <pre><code>import struct s = struct.pack('f'*len(floats), *floats) f = open('file','wb') f.write(s) f.close() </code></pre>
9
2009-04-30T16:39:05Z
[ "python", "file-io" ]
How to output list of floats to a binary file in Python
807,863
<p>I have a list of floating-point values in Python:</p> <pre><code>floats = [3.14, 2.7, 0.0, -1.0, 1.1] </code></pre> <p>I would like to write these values out to a binary file using IEEE 32-bit encoding. What is the best way to do this in Python? My list actually contains about 200 MB of data, so something "not too slow" would be best.</p> <p>Since there are 5 values, I just want a 20-byte file as output.</p>
17
2009-04-30T16:35:43Z
807,890
<p>struct.pack() looks like what you need.</p> <p><a href="http://docs.python.org/library/struct.html" rel="nofollow">http://docs.python.org/library/struct.html</a></p>
3
2009-04-30T16:40:14Z
[ "python", "file-io" ]
How to output list of floats to a binary file in Python
807,863
<p>I have a list of floating-point values in Python:</p> <pre><code>floats = [3.14, 2.7, 0.0, -1.0, 1.1] </code></pre> <p>I would like to write these values out to a binary file using IEEE 32-bit encoding. What is the best way to do this in Python? My list actually contains about 200 MB of data, so something "not too slow" would be best.</p> <p>Since there are 5 values, I just want a 20-byte file as output.</p>
17
2009-04-30T16:35:43Z
808,049
<p>The array module in the standard library may be more suitable for this task than the struct module which everybody is suggesting. Performance with 200 MB of data should be <em>substantially</em> better with array.</p> <p>If you'd like to take at a variety of options, try profiling on your system with <a href="https://gist.github.com/deanmalmgren/fd1714799dc5b5643b87#file-write_profiler-py" rel="nofollow">something like this</a></p>
10
2009-04-30T17:12:01Z
[ "python", "file-io" ]
How to output list of floats to a binary file in Python
807,863
<p>I have a list of floating-point values in Python:</p> <pre><code>floats = [3.14, 2.7, 0.0, -1.0, 1.1] </code></pre> <p>I would like to write these values out to a binary file using IEEE 32-bit encoding. What is the best way to do this in Python? My list actually contains about 200 MB of data, so something "not too slow" would be best.</p> <p>Since there are 5 values, I just want a 20-byte file as output.</p>
17
2009-04-30T16:35:43Z
808,139
<p>Alex is absolutely right, it's more efficient to do it this way:</p> <pre><code>from array import array output_file = open('file', 'wb') float_array = array('d', [3.14, 2.7, 0.0, -1.0, 1.1]) float_array.tofile(output_file) output_file.close() </code></pre> <p>And then read the array like that:</p> <pre><code>input_file = open('file', 'r') float_array = array('d') float_array.fromstring(input_file.read()) </code></pre> <p><code>array.array</code> objects also have a <code>.fromfile</code> method which can be used for reading the file, if you know the count of items in advance (e.g. from the file size, or some other mechanism)</p>
24
2009-04-30T17:32:59Z
[ "python", "file-io" ]
How to output list of floats to a binary file in Python
807,863
<p>I have a list of floating-point values in Python:</p> <pre><code>floats = [3.14, 2.7, 0.0, -1.0, 1.1] </code></pre> <p>I would like to write these values out to a binary file using IEEE 32-bit encoding. What is the best way to do this in Python? My list actually contains about 200 MB of data, so something "not too slow" would be best.</p> <p>Since there are 5 values, I just want a 20-byte file as output.</p>
17
2009-04-30T16:35:43Z
809,216
<p>I'm not sure how <a href="http://numpy.scipy.org/">NumPy</a> will compare performance-wise for your application, but it may be worth investigating.</p> <p>Using <a href="http://numpy.scipy.org/">NumPy</a>:</p> <pre><code>from numpy import array a = array(floats,'float32') output_file = open('file', 'wb') a.tofile(output_file) output_file.close() </code></pre> <p>results in a 20 byte file as well.</p>
7
2009-04-30T21:33:52Z
[ "python", "file-io" ]
How to output list of floats to a binary file in Python
807,863
<p>I have a list of floating-point values in Python:</p> <pre><code>floats = [3.14, 2.7, 0.0, -1.0, 1.1] </code></pre> <p>I would like to write these values out to a binary file using IEEE 32-bit encoding. What is the best way to do this in Python? My list actually contains about 200 MB of data, so something "not too slow" would be best.</p> <p>Since there are 5 values, I just want a 20-byte file as output.</p>
17
2009-04-30T16:35:43Z
34,164,133
<p>I ran into a similar issue while inadvertently writing a 100+ GB csv file. The answers here were extremely helpful but, to get to the bottom of it, <a href="https://gist.github.com/deanmalmgren/fd1714799dc5b5643b87#file-write_profiler-py" rel="nofollow">I profiled all of the solutions mentioned and then some</a>. All profiling runs were done on a 2014 Macbook Pro with a SSD using python 2.7. From what I'm seeing, the <code>struct</code> approach is definitely the fastest from a performance point of view:</p> <pre><code>6.465 seconds print_approach print list of floats 4.621 seconds csv_approach write csv file 4.819 seconds csvgz_approach compress csv output using gzip 0.374 seconds array_approach array.array.tofile 0.238 seconds numpy_approach numpy.array.tofile 0.178 seconds struct_approach struct.pack method </code></pre>
0
2015-12-08T19:15:14Z
[ "python", "file-io" ]
Decoding problems in Django and lxml
808,275
<p>I have a strange problem with lxml when using the deployed version of my Django application. I use lxml to parse another HTML page which I fetch from my server. This works perfectly well on my development server on my own computer, but for some reason it gives me <code>UnicodeDecodeError</code> on the server.</p> <pre><code>('utf8', "\x85why hello there!", 0, 1, 'unexpected code byte') </code></pre> <p>I have made sure that Apache (with mod_python) runs with <code>LANG='en_US.UTF-8'</code>.</p> <p>I've tried googling for this problem and tried different approaches to decoding the string correctly, but I can't figure it out.</p> <p>In your answer, you may assume that my string is called <code>hello</code> or something.</p>
3
2009-04-30T18:02:13Z
808,455
<p>Since modifying site.py is not an ideal solution try this at the start of your program:</p> <pre><code>import sys reload(sys) sys.setdefaultencoding("utf-8") </code></pre>
-2
2009-04-30T18:41:18Z
[ "python", "django", "utf-8", "lxml", "decoding" ]
Decoding problems in Django and lxml
808,275
<p>I have a strange problem with lxml when using the deployed version of my Django application. I use lxml to parse another HTML page which I fetch from my server. This works perfectly well on my development server on my own computer, but for some reason it gives me <code>UnicodeDecodeError</code> on the server.</p> <pre><code>('utf8', "\x85why hello there!", 0, 1, 'unexpected code byte') </code></pre> <p>I have made sure that Apache (with mod_python) runs with <code>LANG='en_US.UTF-8'</code>.</p> <p>I've tried googling for this problem and tried different approaches to decoding the string correctly, but I can't figure it out.</p> <p>In your answer, you may assume that my string is called <code>hello</code> or something.</p>
3
2009-04-30T18:02:13Z
815,780
<p>"\x85why hello there!" is not a utf-8 encoded string. You should try decoding the webpage before passing it to lxml. Check what encoding it uses by looking at the http headers when you fetch the page maybe you find the problem there.</p>
3
2009-05-02T22:32:06Z
[ "python", "django", "utf-8", "lxml", "decoding" ]
Decoding problems in Django and lxml
808,275
<p>I have a strange problem with lxml when using the deployed version of my Django application. I use lxml to parse another HTML page which I fetch from my server. This works perfectly well on my development server on my own computer, but for some reason it gives me <code>UnicodeDecodeError</code> on the server.</p> <pre><code>('utf8', "\x85why hello there!", 0, 1, 'unexpected code byte') </code></pre> <p>I have made sure that Apache (with mod_python) runs with <code>LANG='en_US.UTF-8'</code>.</p> <p>I've tried googling for this problem and tried different approaches to decoding the string correctly, but I can't figure it out.</p> <p>In your answer, you may assume that my string is called <code>hello</code> or something.</p>
3
2009-04-30T18:02:13Z
861,850
<p>Doesn't syntax such as <code>u"\x85why hello there!"</code> help? </p> <p>You may find the following resources from the official Python documentation helpful:</p> <ul> <li><a href="http://docs.python.org/tutorial/introduction.html#unicode-strings" rel="nofollow">Python introduction, Unicode Strings</a></li> <li><a href="http://docs.python.org/library/stdtypes.html#typesseq" rel="nofollow">Sequence Types — str, unicode, list, tuple, buffer, xrange</a></li> </ul>
0
2009-05-14T06:31:39Z
[ "python", "django", "utf-8", "lxml", "decoding" ]
Printing XML into HTML with python
808,529
<p>I have a TextEdit widget in PyQt that I use to print out a log in HTML. I use HTML so I can separate entries into color categories (red for error, yellow for debug, blue for message, etc), but this creates a problem. Most of the debug messages are XML. When I use appendHtml on the widget, it strips out all the tags.</p> <p>How can I pretty print XML in an HTML document?</p>
0
2009-04-30T19:01:10Z
808,577
<p>A cdata section might help.</p> <p><a href="http://reference.sitepoint.com/javascript/CDATASection" rel="nofollow">http://reference.sitepoint.com/javascript/CDATASection</a></p> <p><a href="http://en.wikipedia.org/wiki/CDATA" rel="nofollow">http://en.wikipedia.org/wiki/CDATA</a></p>
0
2009-04-30T19:12:48Z
[ "python", "html", "xml" ]
Printing XML into HTML with python
808,529
<p>I have a TextEdit widget in PyQt that I use to print out a log in HTML. I use HTML so I can separate entries into color categories (red for error, yellow for debug, blue for message, etc), but this creates a problem. Most of the debug messages are XML. When I use appendHtml on the widget, it strips out all the tags.</p> <p>How can I pretty print XML in an HTML document?</p>
0
2009-04-30T19:01:10Z
808,603
<p><a href="http://docs.python.org/library/cgi.html#cgi.escape" rel="nofollow"><code>cgi.escape</code></a> can help you. It will convert the characters <code>'&amp;'</code>, <code>'&lt;'</code> and <code>'&gt;'</code> in the string to HTML-safe sequences. That is enough to prevent interpretation of xml tags.</p> <pre><code>&gt;&gt;&gt; cgi.escape('&lt;tag&gt;') '&amp;lt;tag&amp;gt; </code></pre>
4
2009-04-30T19:18:04Z
[ "python", "html", "xml" ]
Parsing files with Python
808,621
<p>What type of Python objects should I use to parse files with a specific syntax? Also what sort of loop should be followed to make it through the file. Should one pass be sufficient? Two, three?</p>
-3
2009-04-30T19:21:28Z
808,641
<p>how complex the syntax is? are you inventing a new one or not?</p> <p>for a complex language, consider bison bindings like lex + pybison.</p> <p>if you can decide what syntax to use, try YAML.</p>
1
2009-04-30T19:25:32Z
[ "python", "parsing", "object" ]
Parsing files with Python
808,621
<p>What type of Python objects should I use to parse files with a specific syntax? Also what sort of loop should be followed to make it through the file. Should one pass be sufficient? Two, three?</p>
-3
2009-04-30T19:21:28Z
808,650
<p>You should offer more information about your aims ...</p> <ul> <li>What kind of file</li> <li>What structure? Tab separated? XML - like?</li> <li>What kind of encoding?</li> <li>Whats the target structure?</li> <li>Do you need to reparse the file in a regular time period (like an interpreter)?</li> </ul>
2
2009-04-30T19:27:09Z
[ "python", "parsing", "object" ]
Parsing files with Python
808,621
<p>What type of Python objects should I use to parse files with a specific syntax? Also what sort of loop should be followed to make it through the file. Should one pass be sufficient? Two, three?</p>
-3
2009-04-30T19:21:28Z
808,652
<p>It does not depend on your programming language (python) if your parser will have one, two, three or n passes. It depends on the grammar of the syntax you are trying to parse.</p> <p>If the syntax is complex enough I would recommend LEX/YACC combo as Francis said.</p>
0
2009-04-30T19:27:21Z
[ "python", "parsing", "object" ]
Parsing files with Python
808,621
<p>What type of Python objects should I use to parse files with a specific syntax? Also what sort of loop should be followed to make it through the file. Should one pass be sufficient? Two, three?</p>
-3
2009-04-30T19:21:28Z
808,713
<p>It depends on the grammar. You can use <a href="http://pyparsing.wikispaces.com/" rel="nofollow">pyparsing</a> instead of implementing your own parser. It is very easy to use. </p>
3
2009-04-30T19:49:04Z
[ "python", "parsing", "object" ]
Creating an interactive shell for .NET apps and embed scripting languages like python/iron python into it
808,692
<p>I was learning python using the tutorial that comes with the standard python installation. One of the benefits that the author states about python is "maybe you’ve written a program that could use an extension language, and you don’t want to design and implement a whole new language for your application" - My question is how would i go about designing a program (using c#) that can be extended using Python interactively(for this to be possible, i would imagine that i would need to create some sort of a "shell" or "interactive" mode for the .net program) ?</p> <p>Are there any pointers on how to design .NET programs that have an interactive shell. I would then like to use python script in the shell to "extend" or interact with the program.</p> <p><strong>EDIT:</strong> This question partly stems from the demo give by Miguel de Icaza during PDC 2008 where he showed the interactive csharp command prompt, C# 4.0 i think also has this "compiler as a service" feature. I looked at that and thought how cool would it be to design a windows or web program in .NET that had a interactive shell.. and a scripting language like python could be used to extend the features provided by the program.</p> <p>Also, i started thinking about this kind of functionality after reading one of Steve Yegge's essays where he talks about systems that live forever.</p>
13
2009-04-30T19:43:36Z
808,701
<p>This sounds like a great use of <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython">IronPython</a>.</p> <p>It's fairly easy to set up a simple scripting host from C# to allow calls into IronPython scripts, as well as allowing IronPython to call into your C# code. There are samples and examples on the CodePlex site that show how to do this very thing.</p> <p>Another good site for examples and samples is <a href="http://www.ironpython.info/index.php/Main%5FPage">ironpython.info</a></p> <p>And <a href="http://www.voidspace.org.uk/ironpython/embedding.shtml">here is a page</a> dedicated to an example answering your very question, albeit in a generic DLR-centric way -- this would allow you to host IronPython, IronRuby, or whatever DLR languages you want to support.</p> <p>I've used these examples in the past to create an IronPython environment inside a private installation of <a href="http://www.screwturn.eu/">ScrewTurn Wiki</a> - it allowed me to create very expressive Wiki templates and proved to be very useful in general.</p>
11
2009-04-30T19:45:40Z
[ "c#", "python", ".net", "ironpython", "python.net" ]
Creating an interactive shell for .NET apps and embed scripting languages like python/iron python into it
808,692
<p>I was learning python using the tutorial that comes with the standard python installation. One of the benefits that the author states about python is "maybe you’ve written a program that could use an extension language, and you don’t want to design and implement a whole new language for your application" - My question is how would i go about designing a program (using c#) that can be extended using Python interactively(for this to be possible, i would imagine that i would need to create some sort of a "shell" or "interactive" mode for the .net program) ?</p> <p>Are there any pointers on how to design .NET programs that have an interactive shell. I would then like to use python script in the shell to "extend" or interact with the program.</p> <p><strong>EDIT:</strong> This question partly stems from the demo give by Miguel de Icaza during PDC 2008 where he showed the interactive csharp command prompt, C# 4.0 i think also has this "compiler as a service" feature. I looked at that and thought how cool would it be to design a windows or web program in .NET that had a interactive shell.. and a scripting language like python could be used to extend the features provided by the program.</p> <p>Also, i started thinking about this kind of functionality after reading one of Steve Yegge's essays where he talks about systems that live forever.</p>
13
2009-04-30T19:43:36Z
808,730
<p>I don't know what you mean with </p> <blockquote> <p>"extend" or interact with the program</p> </blockquote> <p>so I can't answer your question. Can you give an example?</p> <p>There is an open source interactive C# shell in mono: <a href="http://www.mono-project.com/CsharpRepl" rel="nofollow">http://www.mono-project.com/CsharpRepl</a></p> <p>When you like python, .Net and language extension, you will probably like <a href="http://boo.codehaus.org/" rel="nofollow">Boo</a> over Iron python. Boo comes with an open source interactive shell too.</p> <p>I disagree with </p> <blockquote> <p>"you don’t want to design and implement a whole new language for your application"</p> </blockquote> <p>It's not as hard as it used to be to create a simple DSL. It won't take you days to implement, just hours. It might be an interesting option.</p>
0
2009-04-30T19:52:54Z
[ "c#", "python", ".net", "ironpython", "python.net" ]
Creating an interactive shell for .NET apps and embed scripting languages like python/iron python into it
808,692
<p>I was learning python using the tutorial that comes with the standard python installation. One of the benefits that the author states about python is "maybe you’ve written a program that could use an extension language, and you don’t want to design and implement a whole new language for your application" - My question is how would i go about designing a program (using c#) that can be extended using Python interactively(for this to be possible, i would imagine that i would need to create some sort of a "shell" or "interactive" mode for the .net program) ?</p> <p>Are there any pointers on how to design .NET programs that have an interactive shell. I would then like to use python script in the shell to "extend" or interact with the program.</p> <p><strong>EDIT:</strong> This question partly stems from the demo give by Miguel de Icaza during PDC 2008 where he showed the interactive csharp command prompt, C# 4.0 i think also has this "compiler as a service" feature. I looked at that and thought how cool would it be to design a windows or web program in .NET that had a interactive shell.. and a scripting language like python could be used to extend the features provided by the program.</p> <p>Also, i started thinking about this kind of functionality after reading one of Steve Yegge's essays where he talks about systems that live forever.</p>
13
2009-04-30T19:43:36Z
808,786
<p>Python as an extension language is called "Embedding Python".</p> <p>you can call a python module from c++ by bascially calling the python intepreter and have it execute the python source. This is called <a href="http://www.python.org/doc/2.5.2/ext/embedding.html" rel="nofollow">embedding</a>.</p> <p>It works from C and C++, and will probably work just as well from C#.</p> <p>And no, you do not need any kind of "shell". While Python can be interactive, that's not a requirement at all.</p>
1
2009-04-30T20:05:49Z
[ "c#", "python", ".net", "ironpython", "python.net" ]
Creating an interactive shell for .NET apps and embed scripting languages like python/iron python into it
808,692
<p>I was learning python using the tutorial that comes with the standard python installation. One of the benefits that the author states about python is "maybe you’ve written a program that could use an extension language, and you don’t want to design and implement a whole new language for your application" - My question is how would i go about designing a program (using c#) that can be extended using Python interactively(for this to be possible, i would imagine that i would need to create some sort of a "shell" or "interactive" mode for the .net program) ?</p> <p>Are there any pointers on how to design .NET programs that have an interactive shell. I would then like to use python script in the shell to "extend" or interact with the program.</p> <p><strong>EDIT:</strong> This question partly stems from the demo give by Miguel de Icaza during PDC 2008 where he showed the interactive csharp command prompt, C# 4.0 i think also has this "compiler as a service" feature. I looked at that and thought how cool would it be to design a windows or web program in .NET that had a interactive shell.. and a scripting language like python could be used to extend the features provided by the program.</p> <p>Also, i started thinking about this kind of functionality after reading one of Steve Yegge's essays where he talks about systems that live forever.</p>
13
2009-04-30T19:43:36Z
808,812
<p>Here is a link to a blog post about adding IronRuby to script a C# application.</p> <p><a href="http://blog.jimmy.schementi.com/2008/11/adding-scripting-to-c-silverlight-app.html" rel="nofollow">http://blog.jimmy.schementi.com/2008/11/adding-scripting-to-c-silverlight-app.html</a></p> <p>The principles would also work well for using IronPython.</p>
1
2009-04-30T20:15:16Z
[ "c#", "python", ".net", "ironpython", "python.net" ]
Creating an interactive shell for .NET apps and embed scripting languages like python/iron python into it
808,692
<p>I was learning python using the tutorial that comes with the standard python installation. One of the benefits that the author states about python is "maybe you’ve written a program that could use an extension language, and you don’t want to design and implement a whole new language for your application" - My question is how would i go about designing a program (using c#) that can be extended using Python interactively(for this to be possible, i would imagine that i would need to create some sort of a "shell" or "interactive" mode for the .net program) ?</p> <p>Are there any pointers on how to design .NET programs that have an interactive shell. I would then like to use python script in the shell to "extend" or interact with the program.</p> <p><strong>EDIT:</strong> This question partly stems from the demo give by Miguel de Icaza during PDC 2008 where he showed the interactive csharp command prompt, C# 4.0 i think also has this "compiler as a service" feature. I looked at that and thought how cool would it be to design a windows or web program in .NET that had a interactive shell.. and a scripting language like python could be used to extend the features provided by the program.</p> <p>Also, i started thinking about this kind of functionality after reading one of Steve Yegge's essays where he talks about systems that live forever.</p>
13
2009-04-30T19:43:36Z
809,017
<p>I was looking solution for the same problem, and found IronTextBox: <a href="http://www.codeproject.com/KB/edit/irontextbox2.aspx" rel="nofollow">http://www.codeproject.com/KB/edit/irontextbox2.aspx</a></p> <p>It needs a little tuning for current versions, but seems to be everything I needed. First made it compile, and then added variables I wanted to access from shell to the scope.</p>
3
2009-04-30T20:53:52Z
[ "c#", "python", ".net", "ironpython", "python.net" ]
Creating an interactive shell for .NET apps and embed scripting languages like python/iron python into it
808,692
<p>I was learning python using the tutorial that comes with the standard python installation. One of the benefits that the author states about python is "maybe you’ve written a program that could use an extension language, and you don’t want to design and implement a whole new language for your application" - My question is how would i go about designing a program (using c#) that can be extended using Python interactively(for this to be possible, i would imagine that i would need to create some sort of a "shell" or "interactive" mode for the .net program) ?</p> <p>Are there any pointers on how to design .NET programs that have an interactive shell. I would then like to use python script in the shell to "extend" or interact with the program.</p> <p><strong>EDIT:</strong> This question partly stems from the demo give by Miguel de Icaza during PDC 2008 where he showed the interactive csharp command prompt, C# 4.0 i think also has this "compiler as a service" feature. I looked at that and thought how cool would it be to design a windows or web program in .NET that had a interactive shell.. and a scripting language like python could be used to extend the features provided by the program.</p> <p>Also, i started thinking about this kind of functionality after reading one of Steve Yegge's essays where he talks about systems that live forever.</p>
13
2009-04-30T19:43:36Z
1,052,679
<p>If your goal is to avoid learning a new language you can use <a href="http://www.csscript.net" rel="nofollow">CSScript.Net</a> and embedded scripts written in C# or VB into you application. With CSScript you get full access to the CLR. Three different models of script execution are supported so that you can execute script that refers to objects in your current app domain, execute using remoting, or execute as a shell.</p> <p>Currently I am using CCScript as "glue" code for configuring application objects somewhat similar to using Boo.</p> <p>This <a href="http://www.codeproject.com/KB/cs/cs-script%5Ffor%5Fcp.aspx" rel="nofollow">link</a> tasks you to a code project article that provides a good overview. </p>
1
2009-06-27T11:33:14Z
[ "c#", "python", ".net", "ironpython", "python.net" ]
Python - Threading and a While True Loop
808,746
<p>I have a thread that appends rows to self.output and a loop that runs until self.done is True (or the max execution time is reached).</p> <p>Is there a more efficient way to do this other than using a while loop that constantly checks to see if it's done. The while loop causes the CPU to spike to 100% while it's running.. </p> <pre><code>time.clock() while True: if len(self.output): yield self.output.pop(0) elif self.done or 15 &lt; time.clock(): if 15 &lt; time.clock(): yield "Maximum Execution Time Exceeded %s seconds" % time.clock() break </code></pre>
9
2009-04-30T19:57:07Z
808,764
<p>Use time.sleep(seconds) to create a brief pause after each iteration of the while loop to relinquish the cpu. You will have to set the time you sleep during each iteration based on how important it is that you catch the job quickly after it's complete.</p> <p>Example:</p> <pre><code>time.clock() while True: if len(self.output): yield self.output.pop(0) elif self.done or 15 &lt; time.clock(): if 15 &lt; time.clock(): yield "Maximum Execution Time Exceeded %s seconds" % time.clock() break time.sleep(0.01) # sleep for 10 milliseconds </code></pre>
0
2009-04-30T20:01:13Z
[ "python", "multithreading", "loops" ]
Python - Threading and a While True Loop
808,746
<p>I have a thread that appends rows to self.output and a loop that runs until self.done is True (or the max execution time is reached).</p> <p>Is there a more efficient way to do this other than using a while loop that constantly checks to see if it's done. The while loop causes the CPU to spike to 100% while it's running.. </p> <pre><code>time.clock() while True: if len(self.output): yield self.output.pop(0) elif self.done or 15 &lt; time.clock(): if 15 &lt; time.clock(): yield "Maximum Execution Time Exceeded %s seconds" % time.clock() break </code></pre>
9
2009-04-30T19:57:07Z
808,775
<p>You have to use a synchronization primitive here. Look here: <a href="http://docs.python.org/library/threading.html" rel="nofollow">http://docs.python.org/library/threading.html</a>.</p> <p>Event objects seem very simple and should solve your problem. You can also use a condition object or a semaphore.</p> <p>I don't post an example because I've never used Event objects, and the alternatives are probably less simple.</p> <p><hr /></p> <p><strong>Edit:</strong> I'm not really sure I understood your problem. If a thread can wait until some condition is statisfied, use synchronization. Otherwise the <code>sleep()</code> solution that someone posted will about taking too much CPU time.</p>
0
2009-04-30T20:02:55Z
[ "python", "multithreading", "loops" ]
Python - Threading and a While True Loop
808,746
<p>I have a thread that appends rows to self.output and a loop that runs until self.done is True (or the max execution time is reached).</p> <p>Is there a more efficient way to do this other than using a while loop that constantly checks to see if it's done. The while loop causes the CPU to spike to 100% while it's running.. </p> <pre><code>time.clock() while True: if len(self.output): yield self.output.pop(0) elif self.done or 15 &lt; time.clock(): if 15 &lt; time.clock(): yield "Maximum Execution Time Exceeded %s seconds" % time.clock() break </code></pre>
9
2009-04-30T19:57:07Z
808,778
<p>use mutex module or event/semaphore</p>
0
2009-04-30T20:03:57Z
[ "python", "multithreading", "loops" ]
Python - Threading and a While True Loop
808,746
<p>I have a thread that appends rows to self.output and a loop that runs until self.done is True (or the max execution time is reached).</p> <p>Is there a more efficient way to do this other than using a while loop that constantly checks to see if it's done. The while loop causes the CPU to spike to 100% while it's running.. </p> <pre><code>time.clock() while True: if len(self.output): yield self.output.pop(0) elif self.done or 15 &lt; time.clock(): if 15 &lt; time.clock(): yield "Maximum Execution Time Exceeded %s seconds" % time.clock() break </code></pre>
9
2009-04-30T19:57:07Z
808,780
<p>Use a semaphore; have the working thread release it when it's finished, and block your appending thread until the worker is finished with the semaphore.</p> <p>ie. in the worker, do something like <code>self.done = threading.Semaphore()</code> at the beginning of work, and <code>self.done.release()</code> when finished. In the code you noted above, instead of the busy loop, simply do <code>self.done.acquire()</code>; when the worker thread is finished, control will return.</p> <p>Edit: I'm afraid I don't address your needed timeout value, though; this <a href="http://bugs.python.org/issue850728" rel="nofollow">issue</a> describes the need for a semaphore timeout in the standard library.</p>
1
2009-04-30T20:04:28Z
[ "python", "multithreading", "loops" ]
Python - Threading and a While True Loop
808,746
<p>I have a thread that appends rows to self.output and a loop that runs until self.done is True (or the max execution time is reached).</p> <p>Is there a more efficient way to do this other than using a while loop that constantly checks to see if it's done. The while loop causes the CPU to spike to 100% while it's running.. </p> <pre><code>time.clock() while True: if len(self.output): yield self.output.pop(0) elif self.done or 15 &lt; time.clock(): if 15 &lt; time.clock(): yield "Maximum Execution Time Exceeded %s seconds" % time.clock() break </code></pre>
9
2009-04-30T19:57:07Z
808,820
<p>Are your threads appending to self.output here, with your main task consuming them? If so, this is a tailor-made job for <a href="http://docs.python.org/library/queue.html">Queue.Queue</a>. Your code should become something like:</p> <pre><code>import Queue # Initialise queue as: queue = Queue.Queue() Finished = object() # Unique marker the producer will put in the queue when finished # Consumer: try: while True: next_item = self.queue.get(timeout=15) if next_item is Finished: break yield next_item except Queue.Empty: print "Timeout exceeded" </code></pre> <p>Your producer threads add items to the queue with <code>queue.put(item)</code></p> <p><strong>[Edit]</strong> The original code has a race issue when checking self.done (for example multiple items may be appended to the queue before the flag is set, causing the code to bail out at the first one). Updated with a suggestion from ΤΖΩΤΖΙΟΥ - the producer thread should instead append a special token (Finished) to the queue to indicate it is complete.</p> <p>Note: If you have multiple producer threads, you'll need a more general approach to detecting when they're all finished. You could accomplish this with the same strategy - each thread a Finished marker and the consumer terminates when it sees num_threads markers.</p>
11
2009-04-30T20:16:46Z
[ "python", "multithreading", "loops" ]
Find all IPs on an HTML Page
809,037
<p>I want to get an HTML page with python and then print out all the IPs from it. I will define an IP as the following:</p> <p><strong>x</strong>.<strong>x</strong>.<strong>x</strong>.<strong>x</strong>:<strong>y</strong></p> <p>Where: x = a number between 0 and 256. y = a number with &lt; 7 digits.</p> <p>Thanks.</p>
0
2009-04-30T20:57:12Z
809,061
<p>The basic approach would be:</p> <ul> <li>Use <a href="http://docs.python.org/library/urllib2.html" rel="nofollow"><code>urllib2</code></a> to download the contents of the page</li> <li>Use a <a href="http://docs.python.org/library/re.html" rel="nofollow">regular expression</a> to extract IPv4-like addresses</li> <li>Validate each match according to the numeric constraints on each octet</li> <li>Print out the list of matches</li> </ul> <p>Please provide a clearer indication of what specific part you are having trouble with, along with evidence to show what it is you've tried thus far.</p>
1
2009-04-30T21:01:45Z
[ "python", "regex", "screen-scraping", "extract" ]
Find all IPs on an HTML Page
809,037
<p>I want to get an HTML page with python and then print out all the IPs from it. I will define an IP as the following:</p> <p><strong>x</strong>.<strong>x</strong>.<strong>x</strong>.<strong>x</strong>:<strong>y</strong></p> <p>Where: x = a number between 0 and 256. y = a number with &lt; 7 digits.</p> <p>Thanks.</p>
0
2009-04-30T20:57:12Z
809,109
<p>Try:</p> <pre><code>re.compile("\d?\d?\d.\d?\d?\d.\d?\d?\d.\d?\d?\d:\d+").findall(urllib2.urlopen(url).read()) </code></pre>
0
2009-04-30T21:12:25Z
[ "python", "regex", "screen-scraping", "extract" ]
Find all IPs on an HTML Page
809,037
<p>I want to get an HTML page with python and then print out all the IPs from it. I will define an IP as the following:</p> <p><strong>x</strong>.<strong>x</strong>.<strong>x</strong>.<strong>x</strong>:<strong>y</strong></p> <p>Where: x = a number between 0 and 256. y = a number with &lt; 7 digits.</p> <p>Thanks.</p>
0
2009-04-30T20:57:12Z
809,123
<blockquote> <p>Right. The only part I cant do is the regular expression one. – das 9 mins ago If someone shows me that, I will be fine. – das 8 mins ago</p> </blockquote> <pre><code>import re ip = re.compile(r"\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?):\d{1,6}\b") junk = " 1.1.1.1:123 2.2.2.2:321 312.123.1.12:123 " print ip.findall(junk) # outputs ['1.1.1.1:123', '2.2.2.2:321'] </code></pre> <p>Here is a complete example:</p> <pre><code>import re, urllib2 f = urllib2.urlopen("http://www.samair.ru/proxy/ip-address-01.htm") junk = f.read() ip = re.compile(r"\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?):\d{1,6}\b") print ip.findall(junk) # ['114.30.47.10:80', '118.228.148.83:80', '119.70.40.101:8080', '12.47.164.114:8888', '121. # 17.161.114:3128', '122.152.183.103:80', '122.224.171.91:3128', '123.234.32.27:8080', '124. # 107.85.115:80', '124.247.222.66:6588', '125.76.228.201:808', '128.112.139.75:3128', '128.2 # 08.004.197:3128', '128.233.252.11:3124', '128.233.252.12:3124'] </code></pre>
3
2009-04-30T21:14:43Z
[ "python", "regex", "screen-scraping", "extract" ]
Find all IPs on an HTML Page
809,037
<p>I want to get an HTML page with python and then print out all the IPs from it. I will define an IP as the following:</p> <p><strong>x</strong>.<strong>x</strong>.<strong>x</strong>.<strong>x</strong>:<strong>y</strong></p> <p>Where: x = a number between 0 and 256. y = a number with &lt; 7 digits.</p> <p>Thanks.</p>
0
2009-04-30T20:57:12Z
809,129
<p>Not to turn this into a who's-a-better-regex-author-war but...</p> <pre><code>(\d{1,3}\.){3}\d{1,3}\:\d{1,6} </code></pre>
0
2009-04-30T21:15:45Z
[ "python", "regex", "screen-scraping", "extract" ]
Find all IPs on an HTML Page
809,037
<p>I want to get an HTML page with python and then print out all the IPs from it. I will define an IP as the following:</p> <p><strong>x</strong>.<strong>x</strong>.<strong>x</strong>.<strong>x</strong>:<strong>y</strong></p> <p>Where: x = a number between 0 and 256. y = a number with &lt; 7 digits.</p> <p>Thanks.</p>
0
2009-04-30T20:57:12Z
12,188,252
<p><strong><a href="http://regexr.com?3202m" rel="nofollow">In action</a></strong>:</p> <pre><code>\b(?: # A.B.C in A.B.C.D:port (?: 25[0-5] | 2[0-4][0-9] | 1[0-9][0-9] | [1-9]?[0-9] )\. ){3} (?: # D in A.B.C.D:port 25[0-5] | 2[0-4][0-9] | 1[0-9][0-9] | [1-9]?[0-9] ) :[1-9]\d{0,5} # port number any number in (0,999999] \b </code></pre>
0
2012-08-30T00:17:38Z
[ "python", "regex", "screen-scraping", "extract" ]
Django Manager Chaining
809,210
<p>I was wondering if it was possible (and, if so, how) to chain together multiple managers to produce a query set that is affected by both of the individual managers. I'll explain the specific example that I'm working on:</p> <p>I have multiple abstract model classes that I use to provide small, specific functionality to other models. Two of these models are a DeleteMixin and a GlobalMixin.</p> <p>The DeleteMixin is defined as such:</p> <pre><code>class DeleteMixin(models.Model): deleted = models.BooleanField(default=False) objects = DeleteManager() class Meta: abstract = True def delete(self): self.deleted = True self.save() </code></pre> <p>Basically it provides a pseudo-delete (the deleted flag) instead of actually deleting the object.</p> <p>The GlobalMixin is defined as such:</p> <pre><code>class GlobalMixin(models.Model): is_global = models.BooleanField(default=True) objects = GlobalManager() class Meta: abstract = True </code></pre> <p>It allows any object to be defined as either a global object or a private object (such as a public/private blog post).</p> <p>Both of these have their own managers that affect the queryset that is returned. My DeleteManager filters the queryset to only return results that have the deleted flag set to False, while the GlobalManager filters the queryset to only return results that are marked as global. Here is the declaration for both:</p> <pre><code>class DeleteManager(models.Manager): def get_query_set(self): return super(DeleteManager, self).get_query_set().filter(deleted=False) class GlobalManager(models.Manager): def globals(self): return self.get_query_set().filter(is_global=1) </code></pre> <p>The desired functionality would be to have a model extend both of these abstract models and grant the ability to only return the results that are both non-deleted and global. I ran a test case on a model with 4 instances: one was global and non-deleted, one was global and deleted, one was non-global and non-deleted, and one was non-global and deleted. If I try to get result sets as such: SomeModel.objects.all(), I get instance 1 and 3 (the two non-deleted ones - great!). If I try SomeModel.objects.globals(), I get an error that DeleteManager doesn't have a globals (this is assuming my model declaration is as such: SomeModel(DeleteMixin, GlobalMixin). If I reverse the order, I don't get the error, but it doesn't filter out the deleted ones). If I change GlobalMixin to attach GlobalManager to globals instead of objects (so the new command would be SomeModel.globals.globals()), I get instances 1 and 2 (the two globals), while my intended result would be to only get instance 1 (the global, non-deleted one).</p> <p>I wasn't sure if anyone had run into any situation similar to this and had come to a result. Either a way to make it work in my current thinking or a re-work that provides the functionality I'm after would be very much appreciated. I know this post has been a little long-winded. If any more explanation is needed, I would be glad to provide it.</p> <p><strong>Edit:</strong></p> <p>I have posted the eventual solution I used to this specific problem below. It is based on the link to Simon's custom QuerySetManager.</p>
28
2009-04-30T21:33:29Z
813,277
<p>See this snippet on Djangosnippets: <a href="http://djangosnippets.org/snippets/734/">http://djangosnippets.org/snippets/734/</a></p> <p>Instead of putting your custom methods in a manager, you subclass the queryset itself. It's very easy and works perfectly. The only issue I've had is with model inheritance, you always have to define the manager in model subclasses (just: "objects = QuerySetManager()" in the subclass), even though they will inherit the queryset. This will make more sense once you are using QuerySetManager.</p>
20
2009-05-01T21:04:31Z
[ "python", "django", "django-models", "django-managers" ]
Django Manager Chaining
809,210
<p>I was wondering if it was possible (and, if so, how) to chain together multiple managers to produce a query set that is affected by both of the individual managers. I'll explain the specific example that I'm working on:</p> <p>I have multiple abstract model classes that I use to provide small, specific functionality to other models. Two of these models are a DeleteMixin and a GlobalMixin.</p> <p>The DeleteMixin is defined as such:</p> <pre><code>class DeleteMixin(models.Model): deleted = models.BooleanField(default=False) objects = DeleteManager() class Meta: abstract = True def delete(self): self.deleted = True self.save() </code></pre> <p>Basically it provides a pseudo-delete (the deleted flag) instead of actually deleting the object.</p> <p>The GlobalMixin is defined as such:</p> <pre><code>class GlobalMixin(models.Model): is_global = models.BooleanField(default=True) objects = GlobalManager() class Meta: abstract = True </code></pre> <p>It allows any object to be defined as either a global object or a private object (such as a public/private blog post).</p> <p>Both of these have their own managers that affect the queryset that is returned. My DeleteManager filters the queryset to only return results that have the deleted flag set to False, while the GlobalManager filters the queryset to only return results that are marked as global. Here is the declaration for both:</p> <pre><code>class DeleteManager(models.Manager): def get_query_set(self): return super(DeleteManager, self).get_query_set().filter(deleted=False) class GlobalManager(models.Manager): def globals(self): return self.get_query_set().filter(is_global=1) </code></pre> <p>The desired functionality would be to have a model extend both of these abstract models and grant the ability to only return the results that are both non-deleted and global. I ran a test case on a model with 4 instances: one was global and non-deleted, one was global and deleted, one was non-global and non-deleted, and one was non-global and deleted. If I try to get result sets as such: SomeModel.objects.all(), I get instance 1 and 3 (the two non-deleted ones - great!). If I try SomeModel.objects.globals(), I get an error that DeleteManager doesn't have a globals (this is assuming my model declaration is as such: SomeModel(DeleteMixin, GlobalMixin). If I reverse the order, I don't get the error, but it doesn't filter out the deleted ones). If I change GlobalMixin to attach GlobalManager to globals instead of objects (so the new command would be SomeModel.globals.globals()), I get instances 1 and 2 (the two globals), while my intended result would be to only get instance 1 (the global, non-deleted one).</p> <p>I wasn't sure if anyone had run into any situation similar to this and had come to a result. Either a way to make it work in my current thinking or a re-work that provides the functionality I'm after would be very much appreciated. I know this post has been a little long-winded. If any more explanation is needed, I would be glad to provide it.</p> <p><strong>Edit:</strong></p> <p>I have posted the eventual solution I used to this specific problem below. It is based on the link to Simon's custom QuerySetManager.</p>
28
2009-04-30T21:33:29Z
813,550
<p>I spent a while trying to come up with a way to build a nice factory to do this, but I'm running into a lot of problems with that.</p> <p>The best I can suggest to you is to chain your inheritance. It's not very generic, so I'm not sure how useful it is, but all you would have to do is:</p> <pre><code>class GlobalMixin(DeleteMixin): is_global = models.BooleanField(default=True) objects = GlobalManager() class Meta: abstract = True class GlobalManager(DeleteManager): def globals(self): return self.get_query_set().filter(is_global=1) </code></pre> <p>If you want something more generic, the best I can come up with is to define a base <code>Mixin</code> and <code>Manager</code> that redefines <code>get_query_set()</code> (I'm assuming you only want to do this once; things get pretty complicated otherwise) and then pass a list of fields you'd want added via <code>Mixin</code>s.</p> <p>It would look something like this (not tested at all):</p> <pre><code>class DeleteMixin(models.Model): deleted = models.BooleanField(default=False) class Meta: abstract = True def create_mixin(base_mixin, **kwargs): class wrapper(base_mixin): class Meta: abstract = True for k in kwargs.keys(): setattr(wrapper, k, kwargs[k]) return wrapper class DeleteManager(models.Manager): def get_query_set(self): return super(DeleteManager, self).get_query_set().filter(deleted=False) def create_manager(base_manager, **kwargs): class wrapper(base_manager): pass for k in kwargs.keys(): setattr(wrapper, k, kwargs[k]) return wrapper </code></pre> <p>Ok, so this is ugly, but what does it get you? Essentially, it's the same solution, but much more dynamic, and a little more DRY, though more complex to read.</p> <p>First you create your manager dynamically:</p> <pre><code>def globals(inst): return inst.get_query_set().filter(is_global=1) GlobalDeleteManager = create_manager(DeleteManager, globals=globals) </code></pre> <p>This creates a new manager which is a subclass of <code>DeleteManager</code> and has a method called <code>globals</code>.</p> <p>Next, you create your mixin model:</p> <pre><code>GlobalDeleteMixin = create_mixin(DeleteMixin, is_global=models.BooleanField(default=False), objects = GlobalDeleteManager()) </code></pre> <p>Like I said, it's ugly. But it means you don't have to redefine <code>globals()</code>. If you want a different type of manager to have <code>globals()</code>, you just call <code>create_manager</code> again with a different base. And you can add as many new methods as you like. Same for the manager, you just keep adding new functions that will return different querysets.</p> <p>So, is this really practical? Maybe not. This answer is more an exercise in (ab)using Python's flexibility. I haven't tried using this, though I do use some of the underlying principals of dynamically extending classes to make things easier to access.</p> <p>Let me know if anything is unclear and I'll update the answer.</p>
2
2009-05-01T22:26:05Z
[ "python", "django", "django-models", "django-managers" ]
Django Manager Chaining
809,210
<p>I was wondering if it was possible (and, if so, how) to chain together multiple managers to produce a query set that is affected by both of the individual managers. I'll explain the specific example that I'm working on:</p> <p>I have multiple abstract model classes that I use to provide small, specific functionality to other models. Two of these models are a DeleteMixin and a GlobalMixin.</p> <p>The DeleteMixin is defined as such:</p> <pre><code>class DeleteMixin(models.Model): deleted = models.BooleanField(default=False) objects = DeleteManager() class Meta: abstract = True def delete(self): self.deleted = True self.save() </code></pre> <p>Basically it provides a pseudo-delete (the deleted flag) instead of actually deleting the object.</p> <p>The GlobalMixin is defined as such:</p> <pre><code>class GlobalMixin(models.Model): is_global = models.BooleanField(default=True) objects = GlobalManager() class Meta: abstract = True </code></pre> <p>It allows any object to be defined as either a global object or a private object (such as a public/private blog post).</p> <p>Both of these have their own managers that affect the queryset that is returned. My DeleteManager filters the queryset to only return results that have the deleted flag set to False, while the GlobalManager filters the queryset to only return results that are marked as global. Here is the declaration for both:</p> <pre><code>class DeleteManager(models.Manager): def get_query_set(self): return super(DeleteManager, self).get_query_set().filter(deleted=False) class GlobalManager(models.Manager): def globals(self): return self.get_query_set().filter(is_global=1) </code></pre> <p>The desired functionality would be to have a model extend both of these abstract models and grant the ability to only return the results that are both non-deleted and global. I ran a test case on a model with 4 instances: one was global and non-deleted, one was global and deleted, one was non-global and non-deleted, and one was non-global and deleted. If I try to get result sets as such: SomeModel.objects.all(), I get instance 1 and 3 (the two non-deleted ones - great!). If I try SomeModel.objects.globals(), I get an error that DeleteManager doesn't have a globals (this is assuming my model declaration is as such: SomeModel(DeleteMixin, GlobalMixin). If I reverse the order, I don't get the error, but it doesn't filter out the deleted ones). If I change GlobalMixin to attach GlobalManager to globals instead of objects (so the new command would be SomeModel.globals.globals()), I get instances 1 and 2 (the two globals), while my intended result would be to only get instance 1 (the global, non-deleted one).</p> <p>I wasn't sure if anyone had run into any situation similar to this and had come to a result. Either a way to make it work in my current thinking or a re-work that provides the functionality I'm after would be very much appreciated. I know this post has been a little long-winded. If any more explanation is needed, I would be glad to provide it.</p> <p><strong>Edit:</strong></p> <p>I have posted the eventual solution I used to this specific problem below. It is based on the link to Simon's custom QuerySetManager.</p>
28
2009-04-30T21:33:29Z
814,254
<p>Here is the specific solution to my problem using the custom QuerySetManager by Simon that Scott linked to.</p> <pre><code>from django.db import models from django.contrib import admin from django.db.models.query import QuerySet from django.core.exceptions import FieldError class MixinManager(models.Manager): def get_query_set(self): try: return self.model.MixinQuerySet(self.model).filter(deleted=False) except FieldError: return self.model.MixinQuerySet(self.model) class BaseMixin(models.Model): admin = models.Manager() objects = MixinManager() class MixinQuerySet(QuerySet): def globals(self): try: return self.filter(is_global=True) except FieldError: return self.all() class Meta: abstract = True class DeleteMixin(BaseMixin): deleted = models.BooleanField(default=False) class Meta: abstract = True def delete(self): self.deleted = True self.save() class GlobalMixin(BaseMixin): is_global = models.BooleanField(default=True) class Meta: abstract = True </code></pre> <p>Any mixin in the future that wants to add extra functionality to the query set simply needs to extend BaseMixin (or have it somewhere in its heirarchy). Any time I try to filter the query set down, I wrapped it in a try-catch in case that field doesn't actually exist (ie, it doesn't extend that mixin). The global filter is invoked using globals(), while the delete filter is automatically invoked (if something is deleted, I never want it to show). Using this system allows for the following types of commands:</p> <pre><code>TemporaryModel.objects.all() # If extending DeleteMixin, no deleted instances are returned TemporaryModel.objects.all().globals() # Filter out the private instances (non-global) TemporaryModel.objects.filter(...) # Ditto about excluding deleteds </code></pre> <p>One thing to note is that the delete filter won't affect admin interfaces, because the default Manager is declared first (making it the default). I don't remember when they changed the admin to use Model._default_manager instead of Model.objects, but any deleted instances will still appear in the admin (in case you need to un-delete them).</p>
6
2009-05-02T06:00:37Z
[ "python", "django", "django-models", "django-managers" ]
Django Manager Chaining
809,210
<p>I was wondering if it was possible (and, if so, how) to chain together multiple managers to produce a query set that is affected by both of the individual managers. I'll explain the specific example that I'm working on:</p> <p>I have multiple abstract model classes that I use to provide small, specific functionality to other models. Two of these models are a DeleteMixin and a GlobalMixin.</p> <p>The DeleteMixin is defined as such:</p> <pre><code>class DeleteMixin(models.Model): deleted = models.BooleanField(default=False) objects = DeleteManager() class Meta: abstract = True def delete(self): self.deleted = True self.save() </code></pre> <p>Basically it provides a pseudo-delete (the deleted flag) instead of actually deleting the object.</p> <p>The GlobalMixin is defined as such:</p> <pre><code>class GlobalMixin(models.Model): is_global = models.BooleanField(default=True) objects = GlobalManager() class Meta: abstract = True </code></pre> <p>It allows any object to be defined as either a global object or a private object (such as a public/private blog post).</p> <p>Both of these have their own managers that affect the queryset that is returned. My DeleteManager filters the queryset to only return results that have the deleted flag set to False, while the GlobalManager filters the queryset to only return results that are marked as global. Here is the declaration for both:</p> <pre><code>class DeleteManager(models.Manager): def get_query_set(self): return super(DeleteManager, self).get_query_set().filter(deleted=False) class GlobalManager(models.Manager): def globals(self): return self.get_query_set().filter(is_global=1) </code></pre> <p>The desired functionality would be to have a model extend both of these abstract models and grant the ability to only return the results that are both non-deleted and global. I ran a test case on a model with 4 instances: one was global and non-deleted, one was global and deleted, one was non-global and non-deleted, and one was non-global and deleted. If I try to get result sets as such: SomeModel.objects.all(), I get instance 1 and 3 (the two non-deleted ones - great!). If I try SomeModel.objects.globals(), I get an error that DeleteManager doesn't have a globals (this is assuming my model declaration is as such: SomeModel(DeleteMixin, GlobalMixin). If I reverse the order, I don't get the error, but it doesn't filter out the deleted ones). If I change GlobalMixin to attach GlobalManager to globals instead of objects (so the new command would be SomeModel.globals.globals()), I get instances 1 and 2 (the two globals), while my intended result would be to only get instance 1 (the global, non-deleted one).</p> <p>I wasn't sure if anyone had run into any situation similar to this and had come to a result. Either a way to make it work in my current thinking or a re-work that provides the functionality I'm after would be very much appreciated. I know this post has been a little long-winded. If any more explanation is needed, I would be glad to provide it.</p> <p><strong>Edit:</strong></p> <p>I have posted the eventual solution I used to this specific problem below. It is based on the link to Simon's custom QuerySetManager.</p>
28
2009-04-30T21:33:29Z
12,682,136
<p>Another option worth considering is the PassThroughManager:</p> <p><a href="https://django-model-utils.readthedocs.org/en/latest/managers.html#passthroughmanager" rel="nofollow">https://django-model-utils.readthedocs.org/en/latest/managers.html#passthroughmanager</a></p>
2
2012-10-01T22:41:21Z
[ "python", "django", "django-models", "django-managers" ]
How to calculate cumulative normal distribution in Python
809,362
<p>I am looking for a function in Numpy or Scipy (or any rigorous Python library) that will give me the cumulative normal distribution function in Python.</p>
48
2009-04-30T22:13:11Z
809,402
<p>Adapted from here <a href="http://mail.python.org/pipermail/python-list/2000-June/039873.html">http://mail.python.org/pipermail/python-list/2000-June/039873.html</a></p> <pre><code>from math import * def erfcc(x): """Complementary error function.""" z = abs(x) t = 1. / (1. + 0.5*z) r = t * exp(-z*z-1.26551223+t*(1.00002368+t*(.37409196+ t*(.09678418+t*(-.18628806+t*(.27886807+ t*(-1.13520398+t*(1.48851587+t*(-.82215223+ t*.17087277))))))))) if (x &gt;= 0.): return r else: return 2. - r def ncdf(x): return 1. - 0.5*erfcc(x/(2**0.5)) </code></pre>
15
2009-04-30T22:23:28Z
[ "python", "statistics" ]
How to calculate cumulative normal distribution in Python
809,362
<p>I am looking for a function in Numpy or Scipy (or any rigorous Python library) that will give me the cumulative normal distribution function in Python.</p>
48
2009-04-30T22:13:11Z
809,406
<p>Here's an example:</p> <pre><code>&gt;&gt;&gt; from scipy.stats import norm &gt;&gt;&gt; norm.cdf(1.96) array(0.97500210485177952) </code></pre> <p>If you need the inverse CDF:</p> <pre><code>&gt;&gt;&gt; norm.ppf(norm.cdf(1.96)) array(1.9599999999999991) </code></pre>
63
2009-04-30T22:24:02Z
[ "python", "statistics" ]
How to calculate cumulative normal distribution in Python
809,362
<p>I am looking for a function in Numpy or Scipy (or any rigorous Python library) that will give me the cumulative normal distribution function in Python.</p>
48
2009-04-30T22:13:11Z
3,525,548
<p>To build upon Unknown's example, the Python equivalent of the function normdist() implemented in a lot of libraries would be:</p> <pre><code>def normcdf(x, mu, sigma): t = x-mu; y = 0.5*erfcc(-t/(sigma*sqrt(2.0))); if y&gt;1.0: y = 1.0; return y def normpdf(x, mu, sigma): u = (x-mu)/abs(sigma) y = (1/(sqrt(2*pi)*abs(sigma)))*exp(-u*u/2) return y def normdist(x, mu, sigma, f): if f: y = normcdf(x,mu,sigma) else: y = normpdf(x,mu,sigma) return y </code></pre>
11
2010-08-19T19:35:08Z
[ "python", "statistics" ]
How to calculate cumulative normal distribution in Python
809,362
<p>I am looking for a function in Numpy or Scipy (or any rigorous Python library) that will give me the cumulative normal distribution function in Python.</p>
48
2009-04-30T22:13:11Z
12,955,360
<p>As Google gives this answer for the search <strong>netlogo pdf</strong>, here's the netlogo version of the above python code</p> <pre> ;; Normal distribution cumulative density function to-report normcdf [x mu sigma] let t x - mu let y 0.5 * erfcc [ - t / ( sigma * sqrt 2.0)] if ( y > 1.0 ) [ set y 1.0 ] report y end ;; Normal distribution probability density function to-report normpdf [x mu sigma] let u = (x - mu) / abs sigma let y = 1 / ( sqrt [2 * pi] * abs sigma ) * exp ( - u * u / 2.0) report y end ;; Complementary error function to-report erfcc [x] let z abs x let t 1.0 / (1.0 + 0.5 * z) let r t * exp ( - z * z -1.26551223 + t * (1.00002368 + t * (0.37409196 + t * (0.09678418 + t * (-0.18628806 + t * (.27886807 + t * (-1.13520398 +t * (1.48851587 +t * (-0.82215223 + t * .17087277 ))))))))) ifelse (x >= 0) [ report r ] [report 2.0 - r] end </pre>
-4
2012-10-18T13:02:40Z
[ "python", "statistics" ]
How to calculate cumulative normal distribution in Python
809,362
<p>I am looking for a function in Numpy or Scipy (or any rigorous Python library) that will give me the cumulative normal distribution function in Python.</p>
48
2009-04-30T22:13:11Z
29,273,201
<p>It may be too late to answer the question but since Google still leads people here, I decide to write my solution here.</p> <p>That is, since Python 2.7, the <strong>math</strong> library has integrated the error function <strong>math.erf(x)</strong></p> <p>The erf() function can be used to compute traditional statistical functions such as the cumulative standard normal distribution:</p> <pre><code>from math import * def phi(x): #'Cumulative distribution function for the standard normal distribution' return (1.0 + erf(x / sqrt(2.0))) / 2.0 </code></pre> <p>Ref:</p> <p><a href="https://docs.python.org/2/library/math.html">https://docs.python.org/2/library/math.html</a></p> <p><a href="https://docs.python.org/3/library/math.html">https://docs.python.org/3/library/math.html</a></p>
8
2015-03-26T07:40:44Z
[ "python", "statistics" ]
How to calculate cumulative normal distribution in Python
809,362
<p>I am looking for a function in Numpy or Scipy (or any rigorous Python library) that will give me the cumulative normal distribution function in Python.</p>
48
2009-04-30T22:13:11Z
33,824,283
<p>Alex's answer shows you a solution for standard normal distribution (mean = 0, standard deviation = 1). If you have normal distribution with <code>mean</code> and <code>std</code> (which is <code>sqr(var)</code>) and you want to calculate:</p> <pre><code>from scipy.stats import norm # cdf(x &lt; val) print norm.cdf(val, m, s) # cdf(x &gt; val) print 1 - norm.cdf(val, m, s) # cdf(v1 &lt; x &lt; v2) print norm.cdf(v2, m, s) - norm.cdf(v1, m, s) </code></pre> <p>Read more about <a href="https://en.wikipedia.org/wiki/Cumulative_distribution_function" rel="nofollow">cdf here</a> and scipy implementation of normal distribution with many formulas <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.stats.norm.html" rel="nofollow">here</a>.</p>
1
2015-11-20T10:24:57Z
[ "python", "statistics" ]
distributed/faster python unit tests
809,564
<p>I have a lot of python unit tests for a project and it's getting to the point where it takes a long time to run them. I don't want to add more because I know they're going to make things slower. How do people solve this problem? Is there any easy way to distribute the test execution over a cluster?</p>
4
2009-04-30T23:25:02Z
809,629
<p>Profile them to see what really is slow. You may be able to solve this problem with out distribution. If the tests are truly unit tests then I see not many problems with running the tests across multiple execution engines.</p>
2
2009-04-30T23:49:30Z
[ "python", "unit-testing" ]
distributed/faster python unit tests
809,564
<p>I have a lot of python unit tests for a project and it's getting to the point where it takes a long time to run them. I don't want to add more because I know they're going to make things slower. How do people solve this problem? Is there any easy way to distribute the test execution over a cluster?</p>
4
2009-04-30T23:25:02Z
809,937
<p>The first part of the solution to this problem is to only run the tests one needs to run. Between commits to a shared branch, one runs only those tests that one's new work interacts with; that should take all of five seconds. If one adopts this model, it becomes vital to make a point of running the entire test suite before committing to a shared resource.</p> <p>The problem of running the full test suite for regression purposes remains, of course, though it's already partially addressed by simply running the full suite less often. To avoid having to wait around while that job runs, one can offload the task of testing to another machine. That quickly turns into a task for a continuous integration system; <a href="http://pypi.python.org/pypi/buildbot/0.7.6" rel="nofollow">buildbot</a> seem fairly appropriate to your use case.</p> <p>You should also be able to distribute tests across hosts using buildbot, firing off two jobs with different entry points to the test suite. But I am not convinced that this will gain you much over the first two steps I've mentioned here; it should be reserved for cases when tests take much longer to run than the interval between commits to shared resources.</p> <p>D'A</p> <p>[Caveat lector: My understanding of buildbot is largely theoretical at this point, and it is probably harder than it looks.]</p>
1
2009-05-01T02:14:55Z
[ "python", "unit-testing" ]
distributed/faster python unit tests
809,564
<p>I have a lot of python unit tests for a project and it's getting to the point where it takes a long time to run them. I don't want to add more because I know they're going to make things slower. How do people solve this problem? Is there any easy way to distribute the test execution over a cluster?</p>
4
2009-04-30T23:25:02Z
810,002
<p>While coding, only run the tests of the class that You have just changed, not all the tests in the whole project.</p> <p>Still, it is a good practice to run all tests before You commit Your code (but the Continuous Integration server can do it for You).</p>
1
2009-05-01T02:45:58Z
[ "python", "unit-testing" ]
distributed/faster python unit tests
809,564
<p>I have a lot of python unit tests for a project and it's getting to the point where it takes a long time to run them. I don't want to add more because I know they're going to make things slower. How do people solve this problem? Is there any easy way to distribute the test execution over a cluster?</p>
4
2009-04-30T23:25:02Z
811,222
<p>See py.test, which has the ability to pass unit tests off to a group of machines, or Nose, which (as of trunk, not the currently released version) supports running tests in parallel with the multiprocessing module.</p>
3
2009-05-01T12:52:28Z
[ "python", "unit-testing" ]
distributed/faster python unit tests
809,564
<p>I have a lot of python unit tests for a project and it's getting to the point where it takes a long time to run them. I don't want to add more because I know they're going to make things slower. How do people solve this problem? Is there any easy way to distribute the test execution over a cluster?</p>
4
2009-04-30T23:25:02Z
814,552
<p>You can't frequently run all your tests, because they're too slow. This is an inevitable consequence of your project getting bigger, and won't go away. Sure, you may be able to run the tests in parallel and get a nice speedup, but the problem will just come back later, and it'll never be as it was when your project was small.</p> <p>For productivity, you need to be able to code, and run relevant unit tests and get results within a few seconds. If you have a hierarchy of tests, you can do this effectively: run the tests for the module you're working on frequently, the tests for the component you're working on occasionally, and the project-wide tests infrequently (perhaps before you're thinking of checking it in). You may have integration tests, or full system tests which you may run overnight: this strategy is an extension of that idea.</p> <p>All you need to do to set this up is to organize your code and tests to support the hierarchy.</p>
4
2009-05-02T09:46:16Z
[ "python", "unit-testing" ]
Any gotchas using unicode_literals in Python 2.6?
809,796
<p>We've already gotten our code base running under Python 2.6. In order to prepare for Python 3.0, we've started adding:</p> <pre> from __future__ import unicode_literals </pre> <p>into our <code>.py</code> files (as we modify them). I'm wondering if anyone else has been doing this and has run into any non-obvious gotchas (perhaps after spending a lot of time debugging).</p>
91
2009-05-01T00:56:37Z
826,710
<p>I did find that if you add the <code>unicode_literals</code> directive you should also add something like:</p> <pre><code> # -*- coding: utf-8 </code></pre> <p>to the first or second line your .py file. Otherwise lines such as:</p> <pre><code> foo = "barré" </code></pre> <p>result in an an error such as:</p> <pre> SyntaxError: Non-ASCII character '\xc3' in file mumble.py on line 198, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details </pre>
11
2009-05-05T20:09:56Z
[ "python", "unicode", "python-2.6", "unicode-literals" ]
Any gotchas using unicode_literals in Python 2.6?
809,796
<p>We've already gotten our code base running under Python 2.6. In order to prepare for Python 3.0, we've started adding:</p> <pre> from __future__ import unicode_literals </pre> <p>into our <code>.py</code> files (as we modify them). I'm wondering if anyone else has been doing this and has run into any non-obvious gotchas (perhaps after spending a lot of time debugging).</p>
91
2009-05-01T00:56:37Z
827,449
<p>The main source of problems I've had working with unicode strings is when you mix utf-8 encoded strings with unicode ones.</p> <p>For example, consider the following scripts.</p> <p>two.py</p> <pre><code># encoding: utf-8 name = 'helló wörld from two' </code></pre> <p>one.py</p> <pre><code># encoding: utf-8 from __future__ import unicode_literals import two name = 'helló wörld from one' print name + two.name </code></pre> <p>The output of running <code>python one.py</code> is:</p> <pre><code>Traceback (most recent call last): File "one.py", line 5, in &lt;module&gt; print name + two.name UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128) </code></pre> <p>In this example, <code>two.name</code> is an utf-8 encoded string (not unicode) since it did not import <code>unicode_literals</code>, and <code>one.name</code> is an unicode string. When you mix both, python tries to decode the encoded string (assuming it's ascii) and convert it to unicode and fails. It would work if you did <code>print name + two.name.decode('utf-8')</code>.</p> <p>The same thing can happen if you encode a string and try to mix them later. For example, this works:</p> <pre><code># encoding: utf-8 html = '&lt;html&gt;&lt;body&gt;helló wörld&lt;/body&gt;&lt;/html&gt;' if isinstance(html, unicode): html = html.encode('utf-8') print 'DEBUG: %s' % html </code></pre> <p>Output:</p> <pre><code>DEBUG: &lt;html&gt;&lt;body&gt;helló wörld&lt;/body&gt;&lt;/html&gt; </code></pre> <p>But after adding the <code>import unicode_literals</code> it does NOT:</p> <pre><code># encoding: utf-8 from __future__ import unicode_literals html = '&lt;html&gt;&lt;body&gt;helló wörld&lt;/body&gt;&lt;/html&gt;' if isinstance(html, unicode): html = html.encode('utf-8') print 'DEBUG: %s' % html </code></pre> <p>Output:</p> <pre><code>Traceback (most recent call last): File "test.py", line 6, in &lt;module&gt; print 'DEBUG: %s' % html UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 16: ordinal not in range(128) </code></pre> <p>It fails because <code>'DEBUG: %s'</code> is an unicode string and therefore python tries to decode <code>html</code>. A couple of ways to fix the print are either doing <code>print str('DEBUG: %s') % html</code> or <code>print 'DEBUG: %s' % html.decode('utf-8')</code>.</p> <p>I hope this helps you understand the potential gotchas when using unicode strings.</p>
94
2009-05-05T23:52:06Z
[ "python", "unicode", "python-2.6", "unicode-literals" ]
Any gotchas using unicode_literals in Python 2.6?
809,796
<p>We've already gotten our code base running under Python 2.6. In order to prepare for Python 3.0, we've started adding:</p> <pre> from __future__ import unicode_literals </pre> <p>into our <code>.py</code> files (as we modify them). I'm wondering if anyone else has been doing this and has run into any non-obvious gotchas (perhaps after spending a lot of time debugging).</p>
91
2009-05-01T00:56:37Z
1,789,107
<p>Also in 2.6 (before python 2.6.5 RC1+) unicode literals doesn't play nice with keyword arguments (<a href="http://bugs.python.org/issue4978">issue4978</a>):</p> <p>The following code for example works without unicode_literals, but fails with TypeError: <code>keywords must be string</code> if unicode_literals is used.</p> <pre><code> &gt;&gt;&gt; def foo(a=None): pass ... &gt;&gt;&gt; foo(**{'a':1}) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: foo() keywords must be strings </code></pre>
16
2009-11-24T10:10:01Z
[ "python", "unicode", "python-2.6", "unicode-literals" ]