Python

Checking that JPEG in PIL works from shell

With a JPG image file_name.jpg in the same directory

from PIL import Image
trial_image = Image.open('file_name.jpg')
trial_image.save('file_name_test.jpg')

Installing PIL with virtualenv

If PIL is required it is better to install it correctly once in the system and then use virtualenv with --site-packages.

Problems with JPEG

http://three99.com/posts/how-to-install-pil-on-ubuntu-with-jpeg-support

sudo apt-get install libjpeg62-dev
/myEnv/bin/pip install --no-install PIL
cd /myEnv/build/PIL

Change in setup.py

JPEG_ROOT = None 
JPEG_ROOT = libinclude("/usr/lib")
  /myEnv/bin/pip install PIL

Another possibility

http://stackoverflow.com/questions/4435016/install-pil-on-virtualenv-with-libjpeg

For Ubuntu 11.04, what finally worked for me is:

pip uninstall PIL
sudo apt-get install libjpeg8-dev
pip install PIL

And yet another approach:

http://ubuntuforums.org/showthread.php?t=1751455

Rather than mess with the setup.py in PIL, you can also simply create symlinks to the libraries in /usr/lib (assuming you have sudo access).

I did this with the following commands:

sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib/
sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib/
sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib/

And one more good link for Ubuntu 11.10 - http://obroll.com/install-python-pil-python-image-library-on-ubuntu-11-10-oneiric/

Zen of Python

http://www.python.org/dev/peps/pep-0020/

http://stackoverflow.com/questions/228181/the-zen-of-python

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complex is better than complicated.
  • Flat is better than nested.
  • Sparse is better than dense.
  • Readability counts.
  • Special cases aren't special enough to break the rules.
  • Although practicality beats purity.
  • Errors should never pass silently.
  • Unless explicitly silenced.
  • In the face of ambiguity, refuse the temptation to guess.
  • There should be one-- and preferably only one --obvious way to do it.
  • Although that way may not be obvious at first unless you're Dutch.
  • Now is better than never.
  • Although never is often better than right now.
  • If the implementation is hard to explain, it's a bad idea.
  • If the implementation is easy to explain, it may be a good idea.
  • Namespaces are one honking great idea -- let's do more of those!

Nohup and Python

http://stackoverflow.com/questions/3515757/python-print-statements-being-buffered-with-output-redirection

See Python output buffering for ways to do the latter:

  1. Use the -u command line switch
  2. Wrap sys.stdout in an object that flushes after every write
  3. Set PYTHONUNBUFFERED env var
  4. sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

Move from --no-site-packages

http://ericholscher.com/blog/2010/nov/1/virtualenv-tips/

Frank Wiles ran into this problem on IRC, where he wanted to add in the site-packages after creating a virtualenv with --no-site-packages. It turns out to be really simple, in that you only have to remove the no-global-site-packages.txt in the lib/python2.x directory inside the virtualenv. After that virtualenv will go ahead and fallback to the global site packages happily.

Test coverage in Python

Coverage utility: http://nedbatchelder.com/code/coverage/

Testing AJAX request with Django

http://thingsilearned.com/2009/05/08/testing-ajax-requests-in-django/

request.is_ajax()
from django.test.client import Client
client = Client()
client.post('http://example.com', {'foo': 'bar'}, **{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'})

Conditional expression idiom

https://trac.khavr.com/agiloprojects/42-test-dudarev/ticket/13

Starting with python 2.5, you can use:

x if c else y

In Django 1.4 it will be possible to redefine (override) settings while testing

https://docs.djangoproject.com/en/dev/topics/testing/#overriding-settings

DEBUG=False in test server in Django

https://docs.djangoproject.com/en/dev/topics/testing/#other-test-conditions

Regardless of the value of the DEBUG setting in your configuration file, all Django tests run with DEBUG=False. This is to ensure that the observed output of your code matches what will be seen in a production setting.

Binding uploaded files to forms

https://docs.djangoproject.com/en/dev/ref/forms/api/#binding-uploaded-files

Installing PIP in virtualenv

http://ubuntuforums.org/showthread.php?t=1751455

http://www.eddiewelker.com/2010/03/31/installing-pil-virtualenv-ubuntu/

Template inheritance in Django templates

Using blocks in Django templates

https://docs.djangoproject.com/en/dev/topics/templates/#template-inheritance

The most powerful -- and thus the most complex -- part of Django's template engine is template inheritance. Template inheritance allows you to build a base "skeleton" template that contains all the common elements of your site and defines blocks that child templates can override.

Step-by-step tutorials for testing in Django

http://toastdriven.com/blog/2011/apr/10/guide-to-testing-in-django/

http://toastdriven.com/blog/2011/apr/17/guide-to-testing-in-django-2/

Testing that user logged in and using reverse for URLs

http://stackoverflow.com/questions/2705235/django-test-failing-on-a-view-with-login-required

from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test.client import Client
import unittest

class LoginTestCase(unittest.TestCase):
    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')

    def testLogin(self):
        self.client.login(username='john', password='johnpassword')
response = self.client.get(reverse('testlogin-view'))
        self.assertEqual(response.status_code, 200)

I suggest you (if you don't use them already) to use the reverse() function and name your URLs. This way you are sure that you get always the right URL.

Common issue with redirect when testing Django apps

http://www.slideshare.net/freakboy3742/djangocon09-the-test-client

r = self.client.get('/foo')
self.assertEquals(r.status_code, 200)

FAIL Assertion Error: 301 != 200

r = self.client.get('/foo', follow=True)
self.assertEquals(r.status_code, 200)

response.redirect_chain - links visited before a non-redirect was found.

Simple Login Form

http://www.djangobook.com/en/2.0/chapter14/

By default, the login view renders a template at registration/login.html (you can change this template name by passing an extra view argument ,template_name). This form needs to contain a username and a password field. A simple template might look like this:

{% extends "base.html" %}

{% block content %}

  {% if form.errors %}
    <p class="error">Sorry, that's not a valid username or password</p>
  {% endif %}

  <form action="" method="post">
    <label for="username">User name:</label>
    <input type="text" name="username" value="" id="username">
    <label for="password">Password:</label>
    <input type="password" name="password" value="" id="password">

    <input type="submit" value="login" />
    <input type="hidden" name="next" value="{{ next|escape }}" />
  </form>

{% endblock %}

When to use django-admin and when manage.py

http://stackoverflow.com/questions/3220303/when-should-you-use-django-admin-py-verus-manage-py

Why do the Django documentation code examples using django-admin.py instead of manage.py when demonstrating subcommands such as loaddata and dumpdata?

Well, because these scripts are the same in priciple, with the differences, you already mentioned. The Django docs also mention

django-admin.py <subcommand> [options]
manage.py <subcommand> [options]

side by side. Usually you use django-admin.py to start a new project or application and manage.py to do the rest.

Or if really want to use django-admin:

Use virtualenv, and have DJANGO_SETTINGS_MODULE set by bin/activate, and then you can use django-admin.py

Otherwise an error ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

Django full text search

django-fts on Google code can not be ran right after cloning. I forked and fixed it:

https://github.com/dudarev/django-fts

To include with pip in virtualenv add the following line to requirements.txt

-e git+https://github.com/dudarev/django-fts#egg=fts

If you tried Google Code version. Drop fts_ tables. Sync database with manage.py. Restart the server.

How to determine from which class a method was inherited from?

Use the inspect module.

http://stackoverflow.com/questions/4733220/how-to-determine-from-which-class-a-method-was-inherited-from

Multiple Inheritance

http://docs.python.org/tutorial/classes.html#multiple-inheritance

Python supports a limited form of multiple inheritance as well. A class definition with multiple base classes looks like this:

class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    .
    <statement-N>

For old-style classes, the only rule is depth-first, left-to-right. Thus, if an attribute is not found in DerivedClassName, it is searched in Base1, then (recursively) in the base classes of Base1, and only if it is not found there, it is searched in Base2, and so on.

With new-style classes, dynamic ordering is necessary because all cases of multiple inheritance exhibit one or more diamond relationships (where at least one of the parent classes can be accessed through multiple paths from the bottommost class). For example, all new-style classes inherit from object, so any case of multiple inheritance provides more than one path to reach object. To keep the base classes from being accessed more than once, the dynamic algorithm linearizes the search order in a way that preserves the left-to-right ordering specified in each class, that calls each parent only once, and that is monotonic (meaning that a class can be subclassed without affecting the precedence order of its parents). Taken together, these properties make it possible to design reliable and extensible classes with multiple inheritance. For more detail, see http://www.python.org/download/releases/2.3/mro/.

New-style and classic classes

http://docs.python.org/reference/datamodel.html#newstyle

Classes and instances come in two flavors: old-style (or classic) and new-style.

Up to Python 2.1, old-style classes were the only flavour available to the user. The concept of (old-style) class is unrelated to the concept of type: if x is an instance of an old-style class, then x.__class__ designates the class of x, but type(x) is always . This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance.

New-style classes were introduced in Python 2.2 to unify classes and types. A new-style class is neither more nor less than a user-defined type. If x is an instance of a new-style class, then type(x) is typically the same as x.__class__ (although this is not guaranteed - a new-style class instance is permitted to override the value returned for x.__class__).

The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model. It also has a number of practical benefits, like the ability to subclass most built-in types, or the introduction of “descriptors”, which enable computed properties.

For compatibility reasons, classes are still old-style by default. New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the “top-level type” object if no other parent is needed. The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type() returns. Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are “fixes” that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance.

While this manual aims to provide comprehensive coverage of Python’s class mechanics, it may still be lacking in some areas when it comes to its coverage of new-style classes. Please see http://www.python.org/doc/newstyle/ for sources of additional information.

Old-style classes are removed in Python 3.0, leaving only the semantics of new-style classes.

User Registartion

https://github.com/lig/django-registration-me - user registration app for Django using Mongoengine.

Exporting data to Excel in Django

http://djangosnippets.org/snippets/2233/

Testing Django from terminal

When testing with Python from terminal

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'

Python SMTP server for testing sending emails

http://ubuntuforums.org/showthread.php?t=1572903

import smtpd, asyncore
server = smtpd.DebuggingServer(('localhost', 8000), None)
asyncore.loop()
Last edited by dudarev, 2012-05-17 08:27:59. Edit