Thursday, June 30, 2011

Yesterday date

$yesterday = date('Y-m-d', mktime(0, 0, 0, date("m") , date("d") - 1, date("Y")))

UPD: (thanks to stamm)
$yesterday = date('Y-m-d', strtotime('- 1 day')); 

Tuesday, June 28, 2011

Kwargs in Python

Recently I noticed that function cannot accept unicode strings as parameter names given in kwargs. They must be converted to strings.

I made a sample script
import sys

print "Version: %d.%d.%d\n" % sys.version_info[:3]

string_params = {'a':1, 'b': 2}
unicode_params = {u'a':1, u'b': 2}

def f(a,b):
 print "params: ", a, b

print "Run with string params:"

print "\nRun with unicode params:"

As output I got
Version: 2.5.1

Run with string params:
params:  1 2

Run with unicode params:
Traceback (most recent call last):
  Line 15, in 
TypeError: f() keywords must be strings

To check out it online.

Disable Firefox cache for developing

To disable caches while you're developing and testing in Firefox:
  1. Type about:config in FF address bar;
  2. Set to false the following params:
    • network.http.use-cache
    • browser.cache.offline.enable
    • browser.cache.disk.enable
    • browser.cache.disk_cache_ssl
    • browser.cache.memory.enable
Beware, it totally disables cache in FF!

Monday, June 27, 2011

Make string html-safe

To make a string HTML-safe (convert & to &, > to > and so forth):

>>> import cgi
>>> test_string = "This is <unsafe> string & it contains wrong symbols"
>>> print cgi.escape(test_string)
This is &lt;unsafe&gt; string &amp; it contains wrong symbols

Wednesday, June 22, 2011

Run Django via WSGI without web server

Recently I faced a problem - I needed to test updated Django WSGI-runner script. But I didn't have a web server on my computer. And I didn't want to install it. So, how to deal with that?

I found out about Werkzeug. It was supposed to solve my issue. To install it run system-wide
sudo pip install werkzeug
I made a runner script that makes a dev server with Werkzeug and voila:
from werkzeug.serving import run_simple
from wsgi import application

run_simple('', 4000, application)

where is former django.wsgi file.