django 1.3 STATICFILES_DIRS

after trying many thing and going thru django (1.3) files, here is how we set

static files on django dev server

in settings.py add absolute path of your static files dirs to STATICFILES_DIRS

STATICFILES_DIRS = (

# Put strings here, like "/home/html/static" or "C:/www/django/static".

# Always use forward slashes, even on Windows.

# Don't forget to use absolute paths, not relative paths.

'C:/tools/python/examples/ecomstore-site/estore/static',

)

dont forget trailing comma

Advertisements

post blog remotely with wordpress-library

wordpress-library

# http://code.google.com/p/wordpress-library/source/checkout
import wordpresslib
import getopt
import sys
import re
import random

TITLE_RE = re.compile(r'title=(.*)',re.IGNORECASE)
TAGS_RE = re.compile(r'tags=(.*)',re.IGNORECASE)

def usage():
	print "Usage: python " + sys.argv[0] + " -w wordpress_url -u user -p password [-t title] -f file"

def main():
	try:
		opts, args = getopt.getopt(sys.argv[1:], "w:u:p:t:f:")
	except getopt.GetoptError, err:
		# print help information and exit:
		print str(err) # will print something like "option -a not recognized"
		usage()
		sys.exit(2)

	user = passwd = title = file = url = tags = None

	for o,a in opts:
		if o == "-u":
			user = a
		elif o == "-p":
			passwd = a
		elif o == "-t":
			title = a
		elif o == "-f":
			file = a
		elif o == "-w":
			url = a
		else:
			assert False, ("unhandled option '%s'" % o)

	if not user or not passwd or not url or not file:
		usage()
		sys.exit(3)

	fh = open(file)
	flines = fh.readlines()
	fh.close()

	if not flines:
		print 'error: nothing to post'
		sys.exit(4)

	match = TITLE_RE.search(flines[0])
	if match:
		title = match.group(1)
		flines = flines[1:] # skip line
	
	match = TAGS_RE.search(flines[0])
	if match:
		tags = match.group(1)
		flines = flines[1:]
	
	if not flines:
		print 'error: nothing post body found'
		sys.exit(5)

	body = ''.join(flines)

	wp = wordpresslib.WordPressClient(url, user, passwd)

	# select blog id
	wp.selectBlog(0)

	post = wordpresslib.WordPressPost()
	post.title = title or ('untitled-' + str(random.randint(500, 50001)))
	post.tags = tags or ''
	post.description = body 
	#post.categories = (wp.getCategoryIdFromName('Python'),)

	# pubblish post
	idNewPost = wp.newPost(post, True) # False

	print 'posting successful', idNewPost

if __name__ == '__main__':
  main()

sample blog post


title=Test1
tags=testing,xmlrpc,wordpresslib

<span style="background-color:yellow">testing 123</span>
<div style="margin-left:10%;margin-right:10%">hello again</div>
<ol>
<li>one</li>
<li>two</li>
</ol>
<ui>
<li>a point</li>
<li>another point</li>
</ui>
<strong>very bold</strong>
<span style=’color:red’>and this is red</span>
and a table
<table border="1" style="margin:2%">
<tr>
<td>col1</td>
<td>col2</td>
<td>col3</td>
</tr>
</table>

<div>new line</div>


editplus cliptext file for writing wordpress blog
wordpress.ctl

happey blogging with editplus

wordnet 2.1 lexnames missing

download PyWordNet

>>> from wordnet import *

Traceback (most recent call last):
  File "<pyshell #8>", line 1, in <module>
    from wordnet import *
  File "C:\tools\python\2.6.2\lib\site-packages\wordnet.py", line 767, in </module><module>
    setupLexnames()
  File "C:\tools\python\2.6.2\lib\site-packages\wordnet.py", line 763, in setupLexnames
    for l in open(WNSEARCHDIR+'/lexnames').readlines():
IOError: [Errno 2] No such file or directory: 'C:\\tools\\wordnet\\2.1\\dict/lexnames'

download WordNet-2.0.tar.gz

C:\tools\python>gzip -d WordNet-2.0.tar.gz
C:\tools\python>mkdir x
C:\tools\python>cd x
C:\tools\python\x>mv ..\WordNet-2.0.tar .
C:\tools\python\x>tar xf WordNet-2.0.tar
C:\tools\python\x\WordNet-2.0\dict>cp lexnames C:\tools\wordnet\2.1\dict

now it works

>>> from wordnet import *
>>> N['dog']
dog(n.)
>>> V['dog']
dog(v.)
>>> ADJ['clear']
clear(adj.)
>>> ADV['clearly']
clearly(adv.)

Why lexnames is missing from wordnet 2.1 ?

python dict sort by value

many ways

http://blog.client9.com/2007/11/sorting-python-dict-by-value.html

alist = sorted(adict.iteritems(), key=lambda (k,v): (v,k))

http://coreygoldberg.blogspot.com/2008/06/python-sort-dictionary-by-values.html

sorted(foo.items(), key=lambda(k,v):(v,k))

http://writeonly.wordpress.com/2008/08/30/sorting-dictionaries-by-value-in-python-improved/

def sbv0(adict,reverse=False):
    ''' proposed at Digital Sanitation Engineering
    http://blog.modp.com/2007/11/sorting-python-dict-by-value.html '''
    return sorted(adict.iteritems(), key=lambda (k,v): (v,k), reverse=reverse)

def sbv1(d,reverse=False):
    '''  explicit list expansion '''
    L = [(k,v) for (k,v) in d.iteritems()]
    return sorted(L, key=lambda x: x[1] , reverse=reverse)

def sbv2(d,reverse=False):
    '''  generator '''
    L = ((k,v) for (k,v) in d.iteritems())
    return sorted(L, key=lambda x: x[1] , reverse=reverse)

def sbv3(d,reverse=False):
    ''' using a lambda to get the key, rather than "double-assignment" '''

    return sorted(d.iteritems(), key=lambda x: x[1] , reverse=reverse)

def sbv4(d,reverse=False):
    ''' using a formal function to get the sorting key, rather than a lambda'''
    def sk(x):  return x[1]
    return sorted(d.iteritems(), key=sk , reverse=reverse)

def sk(x):  return x[1]

def sbv5(d,reverse=False):
    ''' using a formal function, defined in outer scope
    to get the sorting key, rather than a lambda
    '''
    return sorted(d.iteritems(), key=sk , reverse=reverse)

from operator import itemgetter
def sbv6(d,reverse=False):
    ''' proposed in PEP 265, using  the itemgetter '''
    return sorted(d.iteritems(), key=itemgetter(1), reverse=True)

D = dict(zip(range(100),range(100)))

from profile import run

run("for ii in xrange(10000):  sbv0(D, reverse=True)")
run("for ii in xrange(10000):  sbv1(D, reverse=True)")
run("for ii in xrange(10000):  sbv2(D, reverse=True)")
run("for ii in xrange(10000):  sbv3(D, reverse=True)")
run("for ii in xrange(10000):  sbv4(D, reverse=True)")
run("for ii in xrange(10000):  sbv5(D, reverse=True)")
run("for ii in xrange(10000):  sbv6(D, reverse=True)")

python reading table into list of dicts

Task:
create a list of dict from a table. First row of the table is header and rest is data. Each row should be converted to a dict where keys are header value and values are data.

Example:

header1 header2 header3
x1 x2 x3
y1 y2 y3
z1 z2 z3

Code:

table=[
['header1','header2','header3'],
['x1','x2','x3'],
['y1','y2','y3'],
['z1','z2','z3'],
]

header=table[0]
print [dict(zip(header,table[rowx])) for rowx in range(1,len(table))]

Output:

[{'header2': 'x2', 'header3': 'x3', 'header1': 'x1'}, {'header2': 'y2', 'header3': 'y3', 'header1': 'y1'}, {'header2': 'z2', 'header3': 'z3', 'header1': 'z1'}]

The Zen of Python

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

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!

getting started google app engine using python

download and install python 2.5
http://www.python.org/ftp/python/2.5.4/python-2.5.4.msi

download and install app engine sdk for pyton
http://googleappengine.googlecode.com/files/GoogleAppEngine_1.2.3.msi

2 scripts of interest in C:/tools/google/appengine
* dev_appserver.py, the development web server
* appcfg.py, for uploading your app to App Engine

C:/tools/google/appengine>mkdir helloworld
C:/tools/google/appengine>cd helloworld
C:/tools/google/appengine/helloworld>
C:/tools/google/appengine/helloworld>vi helloworld.py

copy this and paste in helloworld.py

print 'Content-Type: text/plain'
print ''
print 'Hello, world!'

C:/tools/google/appengine/helloworld>vi app.yaml

copy this and paste in app.yaml

application: helloworld
version: 1
runtime: python
api_version: 1

handlers:
- url: /.*
  script: helloworld.py

start the webserver with following cmd

    google_appengine/dev_appserver.py helloworld/

QUESTION: how does dev_appserver.py knows where is helloworld/
on file system ?
ANSWER: dev_appserver.py calls dev_appserver_main.py

run dev_appserver.py with --debug argument

C:/tools/google/appengine>python dev_appserver.py --debug helloworld/
INFO     2009-06-21 13:05:43,641 appengine_rpc.py:157] Server: appengine.google.com
Allow dev_appserver to check for updates on startup? (Y/n): n
dev_appserver will not check for updates on startup.  To change this setting, edit C:/Documents and Settings/Administrator/.appcfg_nag
WARNING  2009-06-21 13:05:53,095 datastore_file_stub.py:404] Could not read datastore data from c:/temp/user/dev_appserver.datastore
WARNING  2009-06-21 13:05:53,095 datastore_file_stub.py:404] Could not read datastore data from c:/temp/user/dev_appserver.datastore.history
WARNING  2009-06-21 13:05:53,296 dev_appserver.py:3296] Could not initialize images API; you are likely missing the Python "PIL" module. ImportError: No module named _imaging
INFO     2009-06-21 13:05:53,426 dev_appserver_main.py:465] Running application helloworld on port 8080: http://localhost:8080
=====================================================
I've added following line
    print ("=========path=%s" % path);
on line# 393 (in main method)
seems like path is relative to the dir from where we are running script

if I run from c:/

C:/>python C:/tools/google/appengine/dev_appserver.py helloworld/
=========path=helloworld/app.yaml
=========path=helloworld/app.yml
ERROR:root:Application configuration file not found in helloworld/

It cant find it.

It works with absolute path

C:/>python C:/tools/google/appengine/dev_appserver.py C:/tools/google/appengine/helloworld/
=======path=C:/tools/google/appengine/helloworld/app.yaml
INFO     2009-06-21 13:13:06,308 appengine_rpc.py:157] Server: appengine.google.com
WARNING  2009-06-21 13:13:06,328 datastore_file_stub.py:404] Could not read datastore data from c:/temp/user/dev_appserver.datastore
WARNING  2009-06-21 13:13:06,328 datastore_file_stub.py:404] Could not read datastore data from c:/temp/user/dev_appserver.datastore.history
WARNING  2009-06-21 13:13:06,348 dev_appserver.py:3296] Could not initialize images API; you are likely missing the Python "PIL" module. ImportError: No module named _imaging
INFO     2009-06-21 13:13:06,378 dev_appserver_main.py:466] Running application helloworld on port 8080: http://localhost:8080

C:/tools/google/appengine>python dev_appserver.py --debug helloworld/
=========path=helloworld/app.yaml
============================
C:/tools/google/appengine>python dev_appserver.py --help
Runs a development application server for an application.

dev_appserver.py [options] 

Application root must be the path to the application to run in this server.
Must contain a valid app.yaml or app.yml file.

Options:
  --help, -h                 View this helpful message.
  --debug, -d                Use debug logging. (Default false)
  --clear_datastore, -c      Clear the Datastore on startup. (Default false)
  --address=ADDRESS, -a ADDRESS
                             Address to which this server should bind. (Default
                             localhost).
  --port=PORT, -p PORT       Port for the server to run on. (Default 8080)
  --datastore_path=PATH      Path to use for storing Datastore file stub data.
                             (Default c:/temp/user/dev_appserver.datastore)
  --history_path=PATH        Path to use for storing Datastore history.
                             (Default c:/temp/user/dev_appserver.datastore.history)
  --require_indexes          Disallows queries that require composite indexes
                             not defined in index.yaml.
  --smtp_host=HOSTNAME       SMTP host to send test mail to.  Leaving this
                             unset will disable SMTP mail sending.
                             (Default '')
  --smtp_port=PORT           SMTP port to send test mail to.
                             (Default 25)
  --smtp_user=USER           SMTP user to connect as.  Stub will only attempt
                             to login if this field is non-empty.
                             (Default '').
  --smtp_password=PASSWORD   Password for SMTP server.
                             (Default '')
  --enable_sendmail          Enable sendmail when SMTP not configured.
                             (Default false)
  --show_mail_body           Log the body of emails in mail stub.
                             (Default false)
  --auth_domain              Authorization domain that this app runs in.
                             (Default gmail.com)
  --debug_imports            Enables debug logging for module imports, showing
                             search paths used for finding modules and any
                             errors encountered during the import process.
  --allow_skipped_files      Allow access to files matched by app.yaml's
                             skipped_files (default False)
  --disable_static_caching   Never allow the browser to cache static files.
                             (Default enable if expiration set in app.yaml)


=====================================================
The web server is now running, listening for requests on port 8080.
Test the application by visiting the following URL in your web browser:

    * http://localhost:8080/

You can leave the web server running while you develop your application.
The web server knows to watch for changes in your source files and reload
them if necessary.

To shut down the web server, make sure the terminal window is active,
then press Control-C (or the appropriate "break" key for your console).

NOTE: if you get error
application configuration file not found

say you have an C:\MyDemo\HelloWorld dir which include 2 files:
helloworld.py and app.yaml

then you should go to C:\MyDemo rather than C:\MyDemo\HelloWorld to
perform the 
cmd("dev_appserver.py helloworld/").