2008年7月29日 星期二

python imaging library

If model in Django wants to use ImageField,  we must install python imaging library

2008年7月25日 星期五

template

 template object & context object:
ex:
from django.template import Template, Context
a=Template("<p>hello {{name}} </p>")
b=Context({ 'name': 'Peter' } )
a.render(b)
{{ }} in template define the variable
context is a dictionary that map variable to value
render function replace the value with value

call method in {{ }}:
no () & no arguments
ex:
{{ dog.bark }}

list in {{}}:
ex:
{{items.2}}

dictionary in {{}}:
ex:
{{ Person.name }}

define a method that can not be executed by template
ex:
def  test(self):
       hello
test.alters_data=true

template tag:
if & else:
ex:
{% if isHot %}
     {{isHot}}
{% else %}
     not Hot
{% endif %}

and ,  or, not,  can be used in if 

for:
ex:
{% for  name in nameList %}
       {{ name}}
{% endfor %}

for & reverse:
ex:
{% for name in nameList reversed %}
     {{name}}
{% endfor %}

forloop.counter:
the number of times the loop has been entered

forloop.first:
forloop.revcounter:
forloop.last:

forloop.parentloop:
reference to the forloop object for the parent loop

ifequal / ifnotequal:
ex:
{%  ifequal a b %}
     test
{%  endifequal %}

comment:
ex:
{#  this is a comment #}

filter:
change variable,  use | with filter name
ex:
date filter:
{{ tempDate | date: "F j, Y" }}




2008年7月18日 星期五

exception

ex:
ckass Bad(Exception):
          pass

def test():
      raise  Bad(), "test bad"

try:
    test()
except  Bad, info:
     print "bad", info
else:
    print "else"
finally:
     print "finally"

assert:
raise AssertionError when test evaluates to false
ex:
assert  x<=3, 'x must be larger than 3'

raise:
ex1: raise object
class A:
     pass
def  test():
     raise A()

ex2:  raise string
message="Error"
def test():
      raise  message

2008年7月14日 星期一

debug in django

use assert False:
trigger debug page

change type

int:
string to int

str:
int to string

view function

first parameter must be HttpRequest
the other parameters are the string matched by ( ) of urlpatterns

ex:
def hours_ahead(request, offset):
offset=int(offset)
dt= datetime.datetime.now()+ datetime.timedelta(hours=offset)
html="<html><body>In %s hours(s), it will be %s.</body></html>"% (offset,dt)
return HttpResponse(html)

2008年7月13日 星期日

class method & static method

class method:
ex:
def  test(cls):
       print('class method')
test=classmethod(test)

static method:
ex:
def  test()
      print('static method')
test=staticmethod(test)



url mapping

settings.py has a variable  ROOT_URLCONF

ROOT_URLCONF  decides the python file for routing

ROOT_URLCONF is urls.py by default

when a request comes in, Django loads ROOT_URLCONF and find the match between request url & urlpatterns 

when pattern found, the associated view function is called( the function is passed HttpRequest object as first parameter) 

the view function will return an HttpResponse object

define urlpatterns
ex:
urlpatterns = patterns( '', ( r'^test/$',  testFunction) )
match  /test/ ,  if request is /test/,  testFunction is called

define view function:
ex:
def test(request):
now=datetime.datetime.now()
html= "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)

raw string

using r:
turn off escpate
ex:
tempStr=  r'C:\test'

python path

print python path:
import sys
print  sys.path

create a project, create an app, run the server, path, timezone

create a projct
django-admin.py  startproject  newSite

create an app in the project:
python manage.py   startapp books
create  __init__.py, models.py,  views.py in books directory 

run the server:
python manage.py   runserver
running at 127.0.0.0.1:8000

python manage.py  runserver  0.0.0.0  8888
listen on any network interface,  on port 8888

set path for django project
add django_site.pth  under /Library/Python/2.5/site-packages
ex:
django_site.pth:
/Volumes/Data/django_project/

time zone
in settings.py
TIME_ZONE = 'Asia/Taipei'

install django

sudo python setup.py install

__name__ & __main__

when the file is run as a top-level program,  __name__ is set as __main__

when the file is imported,  __name__ is set to the module's name

Hence, we can use __name__ to do unit test.
If  __name__ == __main__,   we execute unit test
if __name__ != __main__,  unit test is not executed