<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python Blog - All about python &#187; orm</title>
	<atom:link href="http://www.python-blog.com/tag/orm/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.python-blog.com</link>
	<description>and technologies around</description>
	<lastBuildDate>Tue, 27 Jul 2010 19:58:17 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>pylons translating custom error messages.</title>
		<link>http://www.python-blog.com/2010/02/08/pylons-translating-custom-error-messages/</link>
		<comments>http://www.python-blog.com/2010/02/08/pylons-translating-custom-error-messages/#comments</comments>
		<pubDate>Mon, 08 Feb 2010 09:02:53 +0000</pubDate>
		<dc:creator>Marcin Kuźmiński</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[lazy translations]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[problem]]></category>
		<category><![CDATA[Pylons]]></category>
		<category><![CDATA[pylons translation issues]]></category>
		<category><![CDATA[python blog]]></category>
		<category><![CDATA[translation problems]]></category>

		<guid isPermaLink="false">http://www.python-blog.com/?p=148</guid>
		<description><![CDATA[I&#8217;d created another simple application in pylons, final step was to translate it from English to Polish.
I used the babel extractor recommended by pylons and that went really smooth.
My application have a language selector available anytime from menu.
I saw that even this switch worked very well for mako templates and string inside controllers,
 it did [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;d created another simple application in pylons, final step was to translate it from English to Polish.</p>
<p>I used the babel extractor recommended by pylons and that went really smooth.</p>
<p>My application have a language selector available anytime from menu.<br />
I saw that even this switch worked very well for mako templates and string inside controllers,<br />
 it did not work when displaying my custom messages that i over rid in validators<br />
and also did not work in my own custom validators that inherit from FancyValidator.<br />
So i started to investigate this.</p>
<p>The first problem of not translating custom error messages in the regular formencode validators was easily being fixed by using lazy_ugettex method.</p>
<pre class="brush:python">
def _(s):
    #fix for translation error messages
    return lazy_ugettext(s)
</pre>
<p>This method allowed me to use lazy_ugettext to translate.<br />
So now when in the validators your translating a string using _(&#8216;this string is for translate&#8217;) method it&#8217;s actually wrapper for lazy_ugettext function.<br />
Lazy translation is when you translate a string when it is accessed, not when the _() or other functions are called.</p>
<p>The second problem of translating custom error messages in your own validator was a bigger problem</p>
<p>I was looking for a solution for some time, and found a nice trick. You have to use your own<br />
state_obj with static _() function. As example below for custom validation function.</p>
<pre class="brush:python">
class ValidLoginNames(formencode.validators.FancyValidator):

    messages = {'invalid_name':_('you cannot use %(username)s as login')}

    def validate_python(self, value, state):
        banned_names = ['admin', 'administrator', 'root']
        if value in banned_names:
            raise formencode.Invalid(self.message('invalid_name', state = State_obj, username = value), value, state)

#this is needed to translate the messages using _()
class State_obj(object):
    _ = staticmethod(_)
</pre>
<p>Those two trick now let&#8217;s you translate custom validators without a problem.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.python-blog.com/2010/02/08/pylons-translating-custom-error-messages/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pydev 1.5.1 &#8211; still getting better.</title>
		<link>http://www.python-blog.com/2009/11/20/pydev-1-5-1-still-getting-better/</link>
		<comments>http://www.python-blog.com/2009/11/20/pydev-1-5-1-still-getting-better/#comments</comments>
		<pubDate>Thu, 19 Nov 2009 23:02:41 +0000</pubDate>
		<dc:creator>Marcin Kuźmiński</dc:creator>
				<category><![CDATA[Editors]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[1.5.1]]></category>
		<category><![CDATA[decorators]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[eclipse plugin]]></category>
		<category><![CDATA[IDE]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[problem]]></category>
		<category><![CDATA[PyDev]]></category>
		<category><![CDATA[pydev 1.5]]></category>

		<guid isPermaLink="false">http://www.python-blog.com/?p=214</guid>
		<description><![CDATA[Few days ago there was again a major update on pydev eclipse plugin.
The version 1.5.1. Comes with new refactoring engine PEPTIC, it&#8217;s way better than any one before.
Complete list below: visit http://pydev.org for download.

Release 1.5.1

Improvements in the AST rewriter
Improvements on the refactoring engine:

No longer using BRM
Merged with the latest PEPTIC
Inline local available
Extract method bug-fixes
Extract local [...]]]></description>
			<content:encoded><![CDATA[<p>Few days ago there was again a major update on pydev eclipse plugin.<br />
The version 1.5.1. Comes with new refactoring engine PEPTIC, it&#8217;s way better than any one before.<br />
Complete list below: visit <a href="http://pydev.org" target="_blank">http://pydev.org</a> for download.</p>
<div id="release-1-5-1">
<h1>Release 1.5.1</h1>
<ul>
<li>Improvements in the AST rewriter</li>
<li>Improvements on the refactoring engine:
<ul>
<li>No longer using BRM</li>
<li>Merged with the latest PEPTIC</li>
<li>Inline local available</li>
<li>Extract method bug-fixes</li>
<li>Extract local on multi-line</li>
<li>Generating properties using coding style defined in preferences</li>
<li>Add after current method option added to extract method</li>
<li>A bunch of other corner-case situations were fixed</li>
</ul>
</li>
<li>Bug-fixes:
<ul>
<li>Minor editor improvements</li>
<li>Adding default forced builtins on all platforms (e.g.: time, math, etc) which wouldn&#8217;t be on sys.builtin_module_names on some python installations</li>
<li>Adding &#8216;numpy&#8217; and &#8216;Image&#8217; to the forced builtins always</li>
<li>Ctrl+1: Generate docstring minor fixes</li>
<li>Ctrl+1: Assign to local now follows coding style preferences properly</li>
<li>Exponential with uppercase E working on code-formatting</li>
<li>When a set/get method is found in code-completion for a java class an NPE is no longer thrown</li>
<li>Backspace properly treated in block mode</li>
<li>Setting IRONPYTHONPATH when dealing with Iron Python (projects could not be referenced)</li>
<li>No longer giving spurious &#8217;statement has no effect&#8217; inside of lambda and decorators</li>
<li>Fixed new exec in python 3k</li>
<li>Fixed NPE when breakpoint is related to a resource in a removed project</li>
<li>Fixed import problem on regexp that could lead to a recursion.</li>
<li>No longer giving NPE when debugging with the register view open</li>
<li>List access be treated as __getitem__() in the list &#8212; patch from Tassilo Barth</li>
<li>Fix for invalid auto-self added when typing</li>
</ul>
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.python-blog.com/2009/11/20/pydev-1-5-1-still-getting-better/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Mercurial on nginx with authentication and SSL</title>
		<link>http://www.python-blog.com/2009/11/15/mercurial-on-nginx-with-authentication-and-ssl/</link>
		<comments>http://www.python-blog.com/2009/11/15/mercurial-on-nginx-with-authentication-and-ssl/#comments</comments>
		<pubDate>Sun, 15 Nov 2009 19:59:08 +0000</pubDate>
		<dc:creator>Marcin Kuźmiński</dc:creator>
				<category><![CDATA[Mercurial]]></category>
		<category><![CDATA[Nginx]]></category>
		<category><![CDATA[certificate generation]]></category>
		<category><![CDATA[crypt]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[generator]]></category>
		<category><![CDATA[IDE]]></category>
		<category><![CDATA[mercurial ssl]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[passwd]]></category>
		<category><![CDATA[push pull]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[python blog]]></category>
		<category><![CDATA[ssl]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.python-blog.com/?p=205</guid>
		<description><![CDATA[Today is a great day ;) i switched my repos from svn to mercurial.
I was still thinking about GIT but there where three key points that made me choose mercurial

 hg serve ( out of the box http server)
 it&#8217;s written in python
 has a very good eclipse plug-in (http://www.vectrace.com/mercurialeclipse/)

Cons: it&#8217;s slower than GIT ( [...]]]></description>
			<content:encoded><![CDATA[<p>Today is a great day ;) i switched my repos from svn to mercurial.<br />
I was still thinking about GIT but there where three key points that made me choose mercurial</p>
<ul>
<li> hg serve ( out of the box http server)</li>
<li> it&#8217;s written in python</li>
<li> has a very good eclipse plug-in (<a href="http://www.vectrace.com/mercurialeclipse/">http://www.vectrace.com/mercurialeclipse/</a>)</li>
</ul>
<p>Cons: it&#8217;s slower than GIT ( but who cares :D )</p>
<p>So after installing mercurial and moving my svn repos with history with <a title="HGSVN home page" href="http://pypi.python.org/pypi/hgsvn" target="_blank">hgsvn</a> ( which can also do push to svn )<br />
I started to setup easy access to the repository using nginx. I&#8217;ll show you how to setup an SSL http based repository to do PUSH/PULL/CLONE what ever.</p>
<p>Firstly we have to make self signed ssl certificates.<br />
I found on of the easiest tutorials available you can find it here: <a href="http://www.akadia.com/services/ssh_test_certificate.html" target="_blank">http://www.akadia.com/services/ssh_test_certificate.html</a></p>
<p>OK when we have the ssl certificates for our server. Put it somewhere on the server so nginx can access it.<br />
We have to setup a new virtual host for nginx that will only do ssl connections<br />
and have basic auth additionally.</p>
<p>Here&#8217;s the example config:</p>
<pre class="brush:plain">server {
    listen          443;
    server_name     hg.yourserver.com;
    ssl    on;
    ssl_certificate    /home/ssl_certs/hg_cert.crt;
    ssl_certificate_key     /home/ssl_certs/hg_cert.key;
    access_log      /var/log/nginx/hg.log;
    auth_basic      "mercurial server";
    auth_basic_user_file    /etc/nginx/.htpasswd;

    location / {
        proxy_pass      http://127.0.0.1:8001;
        #here's where the hg server runs
        include         /etc/nginx/proxy.conf;
    }
}</pre>
<p>Few thing to notice.<br />
.htpasswd file has to be in a format &lt;username&gt;:&lt;cryptPassword&gt; if you don&#8217;t have apache<br />
installed you can use <a href="http://www.python-blog.com/2009/06/23/python-random-password-generator/" target="_blank">my password generator</a> for generating crypt password. This username<br />
and password will be used to do pull/push from console and eclipse.<br />
Another important thing is that when you run hg serve you must specify the -a 127.0.0.1 option which is<br />
for the address the mercurial server runs. Hg serve default is to start at all interfaces<br />
so you have this port open outside and your ssl/passwd protection is for nothing&#8230;</p>
<p>I run my using hg serve &#8211;webdir-conf=/etc/hg/hgweb.conf -d -p 8001 -a 127.0.0.1</p>
<p>The hgweb.conf should be with</p>
<pre class="brush:plain">push_ssl = false
#since nginx is doing the SSL
allow_push = * #NGINX  is doing the auth
style = gitweb</pre>
<p>O and one more thing remember that your repo should be accessible to hg serv.<br />
I made a mistake and run hg serve as www-data and my repo was to my home user,<br />
and i had internal server error when trying to do push to server.</p>
<p>So now you can have your repo via http with SSL and nginx authentication.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.python-blog.com/2009/11/15/mercurial-on-nginx-with-authentication-and-ssl/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python logging &#8211; simpler than ever</title>
		<link>http://www.python-blog.com/2009/11/09/python-logging-simpler-than-ever/</link>
		<comments>http://www.python-blog.com/2009/11/09/python-logging-simpler-than-ever/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 10:07:04 +0000</pubDate>
		<dc:creator>Łukasz Balcerzak</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[python blog]]></category>

		<guid isPermaLink="false">http://www.python-blog.com/?p=202</guid>
		<description><![CDATA[During the weekend I&#8217;ve created Djalog project hosted at the http://code.google.com/p/djalog/. It is simplest possible logging app aimed to work within Django context (or for prototyping as it is also logging-ready out of the box after import in any scripts). 
I&#8217;ve also put it on the PyPi (http://pypi.python.org/pypi/Djalog) so in order to install it you [...]]]></description>
			<content:encoded><![CDATA[<p>During the weekend I&#8217;ve created Djalog project hosted at the http://code.google.com/p/djalog/. It is simplest possible logging app aimed to work within Django context (or for prototyping as it is also logging-ready out of the box after import in any scripts). </p>
<p>I&#8217;ve also put it on the PyPi (http://pypi.python.org/pypi/Djalog) so in order to install it you would execute:</p>
<pre class="brush:python">
easy_install Djalog
</pre>
<p>and you are ready. If you want to quickly check how it works just type:</p>
<pre class="brush:python">
import djalog
import logging

logging.debug("Log some debug information.")
logging.info("Log some information.")
logging.warn("Log some warning.")
logging.error("Log some error.")
logging.critical("Log some critical information.")

from djalog import configure
configure(LOG_USE_COLORS=True, LOG_SQL=True, LOG_LEVEL=5)

logging.debug("Log some debug information.")
logging.info("Log some information.")
logging.warn("Log some warning.")
logging.error("Log some error.")
logging.critical("Log some critical information.")

# Log sql query
logging.sql("SELECT * FROM users WHERE username = 'admin'")
</pre>
<p>This is beta but it should be changed to &#8220;final&#8221; in two weeks. Remember that you may update projects from CheeseShop using &#8220;-U&#8221; option:</p>
<pre class="brush:python">
easy_install -U Djalog
</pre>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.python-blog.com/2009/11/09/python-logging-simpler-than-ever/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>SQLAlchemy: give me my Session object!</title>
		<link>http://www.python-blog.com/2009/10/21/sqlalchemy-give-me-my-session-object/</link>
		<comments>http://www.python-blog.com/2009/10/21/sqlalchemy-give-me-my-session-object/#comments</comments>
		<pubDate>Wed, 21 Oct 2009 09:34:44 +0000</pubDate>
		<dc:creator>Łukasz Balcerzak</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[integer]]></category>
		<category><![CDATA[model]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[problem]]></category>
		<category><![CDATA[python blog]]></category>
		<category><![CDATA[SqlAlchemy]]></category>

		<guid isPermaLink="false">http://www.python-blog.com/?p=197</guid>
		<description><![CDATA[While I love many things about SQLAlchemy this was something I just missed sooooo much &#8211; defining model&#8217;s methods without having to pass session object.
While using Django ORM for such action it is extra easy as there is no session objects at all (well, there is connection object but it&#8217;s much simpler and less sophisticated).
Assume [...]]]></description>
			<content:encoded><![CDATA[<p>While I love many things about SQLAlchemy this was something I just missed sooooo much &#8211; defining model&#8217;s methods without having to pass session object.<br />
While using Django ORM for such action it is extra easy as there is no session objects at all (well, there is connection object but it&#8217;s much simpler and less sophisticated).<br />
Assume you have BlogEntry and BlogComment mappers and you want to define function at entry model which returns related comments &#8211; I know, it is as simple as it could be, but it&#8217;s only an example.</p>
<pre class="brush:python">
class BlogEntry(Base):
    __tablename__ = 'blog_entry'

    title = Column(String)
    content = Column(Text)
    created_at = Column(DateTime, default=datetime.datetime.now)

    def __repr__(self):
        return self.title

class BlogComment(Base):
    __tablename__ = 'blog_comment'

    content = Column(Text)
    created_at = Column(DateTime, default=datetime.datetime.now)
    entry_id = Column(Integer, ForeignKey('blog_entry.id'))
    entry = relation('BlogEntry',
        primaryjoin='BlogEntry.id==BlogComment.entry_id',
        backref='comment_set')
</pre>
<p>You now can of course get comments using comment_set attribute on blog entry. But sometimes we want start querying for other objects, for some reasons.<br />
With Django ORM, no problem, just define method on the model and start querying &#8211; it just works. With SQLAlchemy on the other hand we need to create query<br />
using Session object. But how does mapper use proper session if you call &#8216;comment_set&#8217;? Well, I&#8217;ve found the answer here: http://www.sqlalchemy.org/docs/05/reference/orm/sessions.html . There is &#8216;Session.object_session&#8217; class method which returns session object binded to an model object.</p>
<p>So now we can simply define method for BlogComment:</p>
<pre class="brush:python">
    def get_related_comments(self):
        session = Session.object_session(self)
        comment_list = session.query(BlogComment)\
            .filter(BlogComment.entry_id==BlogEntry.id)\
            .all()
        return comment_list
</pre>
<p>Just remember that object which is passed to &#8216;Session.object_session&#8217; method has to be binded with some session first.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.python-blog.com/2009/10/21/sqlalchemy-give-me-my-session-object/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Hosting change to hosteurope.de</title>
		<link>http://www.python-blog.com/2009/09/13/hosting-change-to-hosteurope-de/</link>
		<comments>http://www.python-blog.com/2009/09/13/hosting-change-to-hosteurope-de/#comments</comments>
		<pubDate>Sun, 13 Sep 2009 18:50:00 +0000</pubDate>
		<dc:creator>Marcin Kuźmiński</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[python blog]]></category>

		<guid isPermaLink="false">http://www.python-blog.com/?p=170</guid>
		<description><![CDATA[I moved the blog to a new server. I think I’m going to move permanently from slicehost to hosteurope.de for the same price i have 1gb ram compared to 256 and 25 50 times the traffic. Also i compiled php 5.3 with php-fpm for this server, and updated mysql to newest available. I hope I’ll [...]]]></description>
			<content:encoded><![CDATA[<p>I moved the blog to a new server. I think I’m going to move permanently from slicehost to hosteurope.de for the same price i have 1gb ram compared to 256 and <span style="text-decoration: line-through;">25</span> 50 times the traffic. Also i compiled php 5.3 with php-fpm for this server, and updated mysql to newest available. I hope I’ll gain some performance with this as well. So enjoy a new theme and the server whitch i hope will be faster.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.python-blog.com/2009/09/13/hosting-change-to-hosteurope-de/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>django and sqlachemy integration</title>
		<link>http://www.python-blog.com/2009/09/05/django-and-sqlachemy-integration/</link>
		<comments>http://www.python-blog.com/2009/09/05/django-and-sqlachemy-integration/#comments</comments>
		<pubDate>Sat, 05 Sep 2009 16:45:44 +0000</pubDate>
		<dc:creator>Marcin Kuźmiński</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[SqlAlchemy]]></category>
		<category><![CDATA[django-alchemy]]></category>
		<category><![CDATA[IDE]]></category>
		<category><![CDATA[integration]]></category>
		<category><![CDATA[multiple database]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[python blog]]></category>

		<guid isPermaLink="false">http://www.python-blog.com/?p=158</guid>
		<description><![CDATA[One of my friends started an interesting project to integrate sqlalchemy into Django. Project name is django-alchemy.
You can visit it on Google code under http://code.google.com/p/django-alchemy/.
You may ask why to use sqlalchemy under Django if it already have an ORM ?
It&#8217;s very easy the django orm is not always the best choice. When using multiple schemas, [...]]]></description>
			<content:encoded><![CDATA[<p>One of my friends started an interesting project to integrate sqlalchemy into Django. Project name is django-alchemy.<br />
You can visit it on Google code under <a href="http://code.google.com/p/django-alchemy/">http://code.google.com/p/django-alchemy/</a>.</p>
<p>You may ask why to use sqlalchemy under Django if it already have an ORM ?<br />
It&#8217;s very easy the django orm is not always the best choice. When using multiple schemas, or multiple database connection the Django ORM just does not provide such functionality.<br />
SqlAlchemy have this built in so when you&#8217;re thinking of using multiple schemas or databases in your django project check out his project. Highly recommended</p>
]]></content:encoded>
			<wfw:commentRss>http://www.python-blog.com/2009/09/05/django-and-sqlachemy-integration/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Django 1.1 finally released!</title>
		<link>http://www.python-blog.com/2009/07/29/django-1-1-finally-released/</link>
		<comments>http://www.python-blog.com/2009/07/29/django-1-1-finally-released/#comments</comments>
		<pubDate>Wed, 29 Jul 2009 19:53:51 +0000</pubDate>
		<dc:creator>Łukasz Balcerzak</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[python blog]]></category>
		<category><![CDATA[SqlAlchemy]]></category>

		<guid isPermaLink="false">http://www.python-blog.com/?p=131</guid>
		<description><![CDATA[With almost 4 months late here it comes, Django 1.1. I&#8217;ve been waiting to see this at the final stage, as we use Django in our company, and I was sometimes forced to code down things that are already boundled now, like sql aggregation functionality for instance (well, in fact I just wrote a little [...]]]></description>
			<content:encoded><![CDATA[<p>With almost 4 months late here it comes, Django 1.1. I&#8217;ve been waiting to see this at the final stage, as we use Django in our company, and I was sometimes forced to code down things that are already boundled now, like sql aggregation functionality for instance (well, in fact I just wrote a little django app using full force of SQLAlchemy instead of Django ORM). Additionally, some security patch was released yesterday, which is included with 1.1 too.</p>
<p>You may read more at <a href="http://docs.djangoproject.com/en/dev/releases/1.1/">release notes</a> page . Stay tuned with Django and minor swing ;-) </p>
]]></content:encoded>
			<wfw:commentRss>http://www.python-blog.com/2009/07/29/django-1-1-finally-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>multiprocessing port scanner</title>
		<link>http://www.python-blog.com/2009/07/17/multiprocessing-port-scanner/</link>
		<comments>http://www.python-blog.com/2009/07/17/multiprocessing-port-scanner/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 14:55:04 +0000</pubDate>
		<dc:creator>Marcin Kuźmiński</dc:creator>
				<category><![CDATA[Multiprocessing]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[cores]]></category>
		<category><![CDATA[GIL]]></category>
		<category><![CDATA[global interpreter lock]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[pararell calculations]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[port scan]]></category>
		<category><![CDATA[port scanner]]></category>
		<category><![CDATA[python blog]]></category>
		<category><![CDATA[socket]]></category>
		<category><![CDATA[Threads]]></category>

		<guid isPermaLink="false">http://www.python-blog.com/?p=125</guid>
		<description><![CDATA[I&#8217;d started to play with multiprocessing module that came up with python 2.6. Multiprocessing module is very similar to threading (it has almost the same functions/classes that threading).
Here are by my opinion three advantages over threading.

Multiprocessing runs on processes not threads.
Overcomes the GIL (global interpreter lock) that threading is using by using sub processes.
Processes can [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;d started to play with multiprocessing module that came up with python 2.6. Multiprocessing module is very similar to threading (it has almost the same functions/classes that threading).</p>
<p>Here are by my opinion three advantages over threading.</p>
<ul>
<li>Multiprocessing runs on processes not threads.</li>
<li>Overcomes the GIL (global interpreter lock) that threading is using by using sub processes.</li>
<li>Processes can be synchronized even remotely so we could write a concurrent calculations over the network</li>
</ul>
<p>I made a simple example class that uses multiprocessing module to scan ports, just for testing i made the same thing that Lukasz made using threading. This example however is not more efficient than the one presented in <a href="http://www.python-blog.com/2009/07/01/python-threaded/" target="_blank">http://www.python-blog.com/2009/07/01/python-threaded/</a> but when we could replace the function check_port with more CPU consuming function we could end up with performance grater by the number of cpus/cores we have. For example in one of my projects recently i made a calculations for popular gambling game in Poland, MultiMulti. I&#8217;d made up a calculations of most repeating number in last 50 games. To calculate combination of 9&#8217;s over 20&#8217;s 50 times with threading i&#8217;d got around 1200s with multiprocessing i was able to calculate it in around 700 s with my Core2Duo CPU. I wish i had core2 quad to check the performance :) So i&#8217;f you need to make some heavy calculations multiprocessing can give you that performance.</p>
<p>Here&#8217;s the code and you can download the port descriptions file <a href="http://www.python-blog.com/wp-content/uploads/2009/07/port_list.data">port_list</a> to match port with description.</p>
<pre class="brush:python">from multiprocessing import Process, Queue, cpu_count, Lock
import socket, sys

class PortScanner(object):
    ''' multiprocessing port scanner with port description'''

    def __init__(self, host = '' , port_range = (1, 100), nr_processes = cpu_count(), port_list_file = ''):
        '''
        port_range=(start,stop) default 1,100
        nr_processes = int default cpu_count() '''
        q = Queue()
        l = Lock()
        port_list = []

        try:
            for i in open(port_list_file).readlines():
                port_list.append([x.strip() for x in i.split('\t')])

        except IOError:
            print 'no port list file specified'
            pass

        for _ in xrange(port_range[0], port_range[1]):
            q.put((host, _))

        #to stop all processes we have to put STOP to queue and break the loop for each process
        for _ in xrange(nr_processes):
            q.put('STOP')

        for _ in xrange(nr_processes):
            p = Process(target = self.check_port, args = (q, l, port_list))
            p.start()

    def check_port(self, q, l, port_list):
        ''' worker class invoked by process '''
        while True:
            queue_ret = q.get()

            if queue_ret == 'STOP':
                break

            s = socket.socket()

            try:

                s.connect((queue_ret))

                #lock for uncorrupted printing to console
                l.acquire()
                print "[INFO] %s on port %s is open" % (queue_ret)

                if len(port_list) &gt; 1:
                    for i in port_list:
                        if int(i[0]) == int(queue_ret[1]):
                            for _ in i:sys.stdout.write(_ + " ")
                            print "\n\n"

                l.release()
            except socket.error:
                #print "[WARNING] %s on port %s is closed" % (queue_ret)
                pass
            s.close()

if __name__ == "__main__":

    PortScanner(host = 'example.com', port_range = (1, 60), nr_processes = 40, port_list_file = 'port_list.data')</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.python-blog.com/2009/07/17/multiprocessing-port-scanner/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python threads tutorial</title>
		<link>http://www.python-blog.com/2009/07/07/python-threads-tutorial/</link>
		<comments>http://www.python-blog.com/2009/07/07/python-threads-tutorial/#comments</comments>
		<pubDate>Tue, 07 Jul 2009 08:29:59 +0000</pubDate>
		<dc:creator>Marcin Kuźmiński</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Threads]]></category>
		<category><![CDATA[GIL]]></category>
		<category><![CDATA[learning python]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[pdf]]></category>
		<category><![CDATA[python blog]]></category>
		<category><![CDATA[thread queue]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.python-blog.com/?p=113</guid>
		<description><![CDATA[If you&#8217;re looking how to start with threads in python i found a great pdf to start with.
Download the Python-Threads pdf. Whitch includes the basic, and some more advanced information and tutorials about the threads in python.
In the pdf you can useful find info about:

thread and threading modules
queue
locks
gil
events
debugging threads

]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re looking how to start with threads in python i found a great pdf to start with.</p>
<p>Download the <strong><a href="http://www.python-blog.com/wp-content/uploads/2009/07/Python-Threads.pdf">Python-Threads</a></strong> pdf. Whitch includes the basic, and some more advanced information and tutorials about the threads in python.</p>
<p>In the pdf you can useful find info about:</p>
<ul>
<li>thread and threading modules</li>
<li>queue</li>
<li>locks</li>
<li>gil</li>
<li>events</li>
<li>debugging threads</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.python-blog.com/2009/07/07/python-threads-tutorial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
