Filed Under (Editors, Python) by Marcin Kuźmiński on February-10-2010

makers of a great ruby on rails IDE rubymine, and ever greater Java IDE intelliJ, released
another (probably) great idea product named pycham, a python IDE, written from scratch in Java.

Since IntelliJ is a really the best Java IDE out there, i presume their next product
dedicated to python will be worth switching.

It’s still in preview but as for now it provides:

  • Coding Assistance
  • Project Code Navigation
  • Google App Engine Support
  • Code Analysis
  • Python Refactoring
  • Web Development with Django (some really nice ones)
  • debugger
  • Integrated unit tests
  • Version control integration



I’d tested under linux, seems to be a littler slower than my eclipse home brew version, but I’d expect the final version faster. It has few nice features, easy configuration, code completion are doing fine.
You can grab a free 45 day copy from here.

I’ll for sure fallow this product development. Stay posted for more !



Filed Under (Editors, Python) by Marcin Kuźmiński on November-20-2009

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’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 on multi-line
    • Generating properties using coding style defined in preferences
    • Add after current method option added to extract method
    • A bunch of other corner-case situations were fixed
  • Bug-fixes:
    • Minor editor improvements
    • Adding default forced builtins on all platforms (e.g.: time, math, etc) which wouldn’t be on sys.builtin_module_names on some python installations
    • Adding ‘numpy’ and ‘Image’ to the forced builtins always
    • Ctrl+1: Generate docstring minor fixes
    • Ctrl+1: Assign to local now follows coding style preferences properly
    • Exponential with uppercase E working on code-formatting
    • When a set/get method is found in code-completion for a java class an NPE is no longer thrown
    • Backspace properly treated in block mode
    • Setting IRONPYTHONPATH when dealing with Iron Python (projects could not be referenced)
    • No longer giving spurious ’statement has no effect’ inside of lambda and decorators
    • Fixed new exec in python 3k
    • Fixed NPE when breakpoint is related to a resource in a removed project
    • Fixed import problem on regexp that could lead to a recursion.
    • No longer giving NPE when debugging with the register view open
    • List access be treated as __getitem__() in the list — patch from Tassilo Barth
    • Fix for invalid auto-self added when typing


Filed Under (Mercurial, Nginx) by Marcin Kuźmiński on November-15-2009

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

Cons: it’s slower than GIT ( but who cares :D )

So after installing mercurial and moving my svn repos with history with hgsvn ( which can also do push to svn )
I started to setup easy access to the repository using nginx. I’ll show you how to setup an SSL http based repository to do PUSH/PULL/CLONE what ever.

Firstly we have to make self signed ssl certificates.
I found on of the easiest tutorials available you can find it here: http://www.akadia.com/services/ssh_test_certificate.html

OK when we have the ssl certificates for our server. Put it somewhere on the server so nginx can access it.
We have to setup a new virtual host for nginx that will only do ssl connections
and have basic auth additionally.

Here’s the example config:

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;
    }
}

Few thing to notice.
.htpasswd file has to be in a format <username>:<cryptPassword> if you don’t have apache
installed you can use my password generator for generating crypt password. This username
and password will be used to do pull/push from console and eclipse.
Another important thing is that when you run hg serve you must specify the -a 127.0.0.1 option which is
for the address the mercurial server runs. Hg serve default is to start at all interfaces
so you have this port open outside and your ssl/passwd protection is for nothing…

I run my using hg serve –webdir-conf=/etc/hg/hgweb.conf -d -p 8001 -a 127.0.0.1

The hgweb.conf should be with

push_ssl = false
#since nginx is doing the SSL
allow_push = * #NGINX  is doing the auth
style = gitweb

O and one more thing remember that your repo should be accessible to hg serv.
I made a mistake and run hg serve as www-data and my repo was to my home user,
and i had internal server error when trying to do push to server.

So now you can have your repo via http with SSL and nginx authentication.



Filed Under (Django, Pylons, SqlAlchemy) by Marcin Kuźmiński on September-26-2009

Recently i had to create a lot of models using declarative mode with sqlalchemy 0.5.5 It was very time consuming especially for large databases. I started to think about an automated solution.

Sqlalchemy have this auto load feature which fetches info about tables by itself. I wanted to use this somehow to generate a string which can be easily  copy/paste to database model definition script. So i started a little project to write auto  model generator for sql alchemy based on auto load feature in sqlalchemy.

The script  is not perfect but it works and save a huge amount of time just codding the models. In fact is was able to setup a 186 table database model in 15minutes with this script.

Well the script helped me a lot and now on when i have to load some new existing database or changes i use it all the time.

The documentation is inside the script i tried to write it so anybody could use it out of the box.

I tested it on 4 schema 200+ tables database and i worked quite good. This script still have to be polished but current functionality is enough for most users.

My script is going to be also a part of django-alchemy project started by my friend Lukasz Balcerzak. You can visit the project site @ http://code.google.com/p/django-alchemy/

I used it with Pylons application and Django with modded sqlalchemy. but it can be basically used in any app which uses sqlalchemy. I did not test it with mysql though,but it should work, just specify mysql as dialect.

You can download this script from sqlalchemy model generator



Filed Under (Editors) by Marcin Kuźmiński on September-6-2009

The creator of PyDev together with aptana released the version 1.5 of PyDev.This major release contains PyDev along with previously commercial non free PyDev extensions.
This is from now a Open Source project you could find on sourceforge
Pydev Extensions is a plugin that adds many other features to Pydev such as…

* code-analysis
* code completion with auto-import
* better implementation of go to definition
* remote debugging
* ‘quick-fixes’
* mark-occurrences <- this one is great :)

Before the PyDev extension was a paid plugin for aptana or eclipse.Now you could download it as PyDev 1.5 which is pyDev + pyDev extension merged together as a free open source project.
Great to here that :)

In order to install the pyDev 1.5 just update your eclipse repository to new update address which is http://pydev.org/updates

I think the nightly builds are yet not in 1.5 so I’ll use this repo for now.

Also i found a great link for PyDev functionality.

http://pydev.org/manual_adv_features.html

i did not know eclipse provide the ctrl+/ functionality (text auto completion emacs style…) This one is very handy !!

Enjoy new even better pyDev



Filed Under (Django, SqlAlchemy) by Marcin Kuźmiński on September-5-2009

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’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.
SqlAlchemy have this built in so when you’re thinking of using multiple schemas or databases in your django project check out his project. Highly recommended



Filed Under (Python) by Marcin Kuźmiński on July-7-2009

I found a really great beginners tutorial for Python i need to share with others. It’s python by examples.

Found at http://www.lightbird.net/py-by-example/

I read many tutorials and sites dedicated to python, but this one is absolutely a must if you’re a python beginner. It’s loaded with simple examples, and descriptions. It briefly shows you the basics of python , each function is nicely explained with few examples. If you’re interested in learning Python this is the place to start. I personally found few things i did not use and know in python like shelve or inspect.

Here is the huge list of what’s on the page:

Regards M.



Filed Under (Python, Threads) by Łukasz Balcerzak on July-1-2009

Recently I’ve run into some optimizations problem which I once hoped I wouldn’t had to face. After some research on the subject I decided to split some process using threads. I hadn’t have much experience in that area except some classes at PJIIT (Polish-Japanese Institute of Information Technology) so start was painful… but not for long (as with everything in Python).

So I decided to share my thoughts with everyone who would ever try to use threads in Python programming.

Let’s imagine simple case: you want to check some host if it has opened any port from range 1-1000. We create simple script (use whatever host you like)

import socket
import time

def is_port_open(host, port):
    """
    Takes host param as string and port param as int.
    Returns true if port is open and false otherwise.
    """
    #print "[DEBUG] Checking host %s:%s" % (host, port)
    s = socket.socket()
    is_open = True
    try:
        s.connect( (host, port) )
    except socket.error:
        is_open = False
    s.close()
    return is_open

def main():
    start = time.time()

    host = 'some.host'
    ports = range(1,1000) 

    print "[INFO] Will now check host %s for ports between %s and %s" % \
        (host, ports[0], ports[-1]) 

    for port in ports:
        if is_port_open(host, port):
            print "[INFO] Port %s on host %s is open." % (port, host)

    print "Elapsed Time: %s" % (time.time() - start)

if __name__ == '__main__':
    main()

How long was it? Well, try this then:

import threading
import socket
import time
import Queue

THREAD_NUMBER = 20

def is_port_open(host, port):
    """
    Takes host param as string and port param as int.
    Returns true if port is open and false otherwise.
    """
    #print "[DEBUG] Checking host %s:%s" % (host, port)
    s = socket.socket()
    is_open = True
    try:
        s.connect( (host, port) )
    except socket.error:
        is_open = False
    s.close()
    return is_open

class PortChecker(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue

    def run(self):
        while True:
            host, port = self.queue.get()
            if is_port_open(host, port):
                print "[INFO] Port %s on host %s is open." % (port, host)
            self.queue.task_done()

def main():
    start = time.time()

    host = 'some.host'
    ports = range(1,1000)
    queue = Queue.Queue()

    for i in xrange(THREAD_NUMBER):
        pc = PortChecker(queue)
        pc.setDaemon(True)
        pc.start()

    print "[INFO] Will now check host %s for ports between %s and %s" % \
        (host, ports[0], ports[-1]) 

    for port in ports:
        queue.put( (host, port) )

    queue.join()
    print "Elapsed Time: %s" % (time.time() - start)

if __name__ == '__main__':
    main()

Try with different port range/thread number. Ok, this is just an example. But it should give you an idea how to handle with some process that is done inside a loop. You have to define your “handler” (thread that will process on some object(s)), create empy queue and fill it with objects. Try to use only 1 thread (set THREAD_NUMBER to 1) and look at the time it took to finish whole process.

I know that programmer’s time is much more expensive than processor’s time and I try not to break this rule. But sometimes (i.e. when your script runs for over 12 hours) it is very nice if you can cut the time you can generate results. Just remember to catch exceptions inside threads – it is very important as if exception is risen by thread, it will just die without any notification.

Well, thats it. I will proceed tomorrow with some example with SQLAlchemy. Good night folks.



Filed Under (Python) by Marcin Kuźmiński on July-1-2009

Here an example how to send a mail with attachement using built in smtp lib to multiple recipients. It’s really very simple in python.

Just take a look at the code bellow.

'simple smtp mailer with multiple recipients and file attachments'

from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders
import os
from smtplib import SMTP

class Mailer(object):
    ''' simple mailer  '''

    def __init__(self):

        self.mail_to = ['rec3@example.com', 'rec2@example.com', 'rec3@example.com']

        self.mail_from = 'mailer@python-blog.com'
        msg_en = "This is an automated message from python-blog.com\r\n"

        #path to file we want to attach
        msg_file_attachment = '/home/marcink/Desktop/pydev_icons.zip'
        #get the filename we need it for adding to mail header
        msg_file_name = os.path.basename(msg_file_attachment)

        smtp_serv = SMTP('mail.python-blog.com')

        smtp_serv.ehlo("simpleMailerHello.python-blog.com")

        #if server requires authorization you must provide login and password
        smtp_serv.login('mylogin', 'mypassword')
        date_ = formatdate(localtime = True)

        msg = MIMEMultipart()
        msg['From'] = self.mail_from
        msg['To'] = COMMASPACE.join(self.mail_to)
        msg['Date'] = date_
        msg['Subject'] = "example subject"

        #attach string message
        msg.attach(MIMEText(msg_en))

        #attach open encode the filename
        file_part = MIMEBase('application', "octet-stream")
        file_part.set_payload(open(msg_file_attachment, "rb").read())
        encoders.encode_base64(file_part)
        file_part.add_header('Content-Disposition', 'attachment; filename="%s"'
                       % msg_file_name)
        msg.attach(file_part)

        #sendmail and exit server
        smtp_serv.sendmail(self.mail_from, self.mail_to, msg.as_string())
        smtp_serv.quit()

if __name__ == "__main__":
    Mailer()
    print 'mail sent'


Filed Under (Editors, Python) by Marcin Kuźmiński on June-25-2009

Today is Eclipse Galileo release day. So i made my new PyDev + eclipse compilation with some customizations.

I remove all the unnecessary stuff for java IDE since we program in python we don’t need java stuff in there( and it loads faster to :D )
replaced splash screen with the one from pyDev site, and throw some nice (Python) window icons.

Here’s the main window:
Screenshot-Pydev - Eclipse

Here’s what you have to do to have my setup:

  • Get the newest version of eclipse for java IDE (not the EE) use this direct link if you want download eclipse
  • extract folder eclipse to you hard drive and rename it to let’s say PyDev ;]
  • DON’T RUN ECLIPSE !! please
  • Ok here’s what you have to remove to get rid of all the java stuff
    (i have nothing against java, but we’re talking python here)
  • from folder features remove org.eclipse.jdt_3.5.0.v20090527-2000-7r88FEeFJePyvYeA33DjZ_c1
  • from folder plugins remove
    org.eclipse.jdt.debug_3.5.0.v20090526
    org.eclipse.jdt.apt.core_3.3.200.v20090528-1135.jar
    org.eclipse.jdt.apt.pluggable.core_1.0.200.v20090526-2130.jar
    org.eclipse.jdt.apt.ui_3.3.200.v20090528-1135.jar
    org.eclipse.jdt.compiler.apt_1.0.200.v20090528-1135.jar
    org.eclipse.jdt.compiler.tool_1.0.100.v_963.jar
    org.eclipse.jdt.core.manipulation_1.3.0.v20090603.jar
    org.eclipse.jdt.core_3.5.0.v_963.jar
    org.eclipse.jdt.debug.ui_3.4.0.v20090527.jar
    org.eclipse.jdt.doc.user_3.5.0.v20090603-1530.jar
    org.eclipse.jdt.junit.runtime_3.4.100.v20090513-2000.jar
    org.eclipse.jdt.junit4.runtime_1.1.0.v20090513-2000.jar
    org.eclipse.jdt.junit_3.5.0.v20090526-2000.jar
    org.eclipse.jdt.launching_3.5.0.v20090527.jar
    org.eclipse.jdt.ui_3.5.0.v20090604.jar
    org.eclipse.jdt_3.5.0.v200906111540.jar
  • Firstly i decided to remove epp.package.java but this really screws up eclipse and the icons so don’t do it
  • Now download this pydev icons  package pydev_icons and extract it somewhere
    if you don’t need the eclipse icon replacement you can skip this.
  • Copy and replace splash.bmp to folder plugins/org.eclipse.platform_3.3.200.v200906111540
    and paste rest of images to folder in plugins/org.eclipse.epp.package.java_1.2.0.20090619-0620
  • In case of newer eclipse builds (3.5.2) just copy everything to plugins/org.eclipse.platform_*.*(version number) and remove the gifs, so eclipse will load png
  • Your done !

Now run eclipse save you workspace and setup pydev as in this post:

http://www.python-blog.com/index.php/2009/06/20/python-ide-pydev-best-choice/

Enjoy lighter version of newest eclipse galileo with Pydev and some nice icons :)

UPDATE: I changed the splash screen in pydev icons to be the same size as original one.