Django at a glance–Django初窥

由于Django发展于快节奏的newsroom环境中,它被设计用来使通常的web开发更加快捷简单。以下是一个非正式的介绍:使用Django来写一个数据库驱动(database-driven)的web app。
本文意在给你足够的技术细节来懂得Django是如何工作的,而不是作为一个tutorial或reference–这些东西我们都有。当你准备开始一个项目时,你可以start with the tutorial或者dive right into more detailed documentation.
Design your model虽然可以使用Django without a database, Django有一个对象关系映射器(object-relational mapper),通过它你得以在Python代码中描述你的数据库模型(database layout)这种数据-模型机制(data-model syntax)为表示你的数据模型提供了众多的方式—-so far, 它正用来解决会耗时两年(two years’ worth)的数据库模式(database-schema)问题。

下面是一个小例子:

class Reporter(models.Model):
    full_name = models.CharField(max_length=70)

    def __unicode__(self):
        return self.full_name

class Article(models.Model):
    pub_date = models.DateTimeField()
    headline = models.CharField(max_length=200)
    content = models.TextField()
    reporter = models.ForeignKey(Reporter)

    def __unicode__(self):
        return self.headline

Install it 生成数据库Next, 运行Django命令行工具(command-line utility)来自动生成database tables.

manage.py syncdb

syncdb命令会查找你已有的models, 并创建任何不存在的database table.
Enjoy the free API使用django(或者说是对象关系映射器), 你将获得一个free,丰富的Python API来访问你的数据。这些API是全局的(on the fly),不需要生成任何代码

>>> from mysite.models import Reporter, Article

# No reporters are in the system yet.
>>> Reporter.objects.all()
[]

# Create a new Reporter.
>>> r = Reporter(full_name=’John Smith’)

# Save the object into the database. You have to call save() explicitly.
>>> r.save()

# Now it has an ID.
>>> r.id
1

# Now the new reporter is in the database.
>>> Reporter.objects.all()
[<Reporter: John Smith>]

# Fields are represented as attributes on the Python object.
>>> r.full_name
‘John Smith’

# Django provides a rich database lookup API.
>>> Reporter.objects.get(id=1)
<Reporter: John Smith>
>>> Reporter.objects.get(full_name__startswith=’John’)
<Reporter: John Smith>
>>> Reporter.objects.get(full_name__contains=’mith’)
<Reporter: John Smith>
>>> Reporter.objects.get(id=2)
Traceback (most recent call last):
    …
DoesNotExist: Reporter matching query does not exist.

# Create an article.
>>> from datetime import datetime
>>> a = Article(pub_date=datetime.now(), headline=’Django is cool’,
… content=’Yeah.’, reporter=r)
>>> a.save()

# Now the article is in the database.
>>> Article.objects.all()
[<Article: Django is cool>]

# Article objects get API access to related Reporter objects.
>>> r = a.reporter
>>> r.full_name
‘John Smith’

# And vice versa: Reporter objects get API access to Article objects.
>>> r.article_set.all()
[<Article: Django is cool>]

# The API follows relationships as far as you need, performing efficient
# JOINs for you behind the scenes.
# This finds all articles by a reporter whose name starts with “John”.
>>> Article.objects.filter(reporter__full_name__startswith=”John”)
[<Article: Django is cool>]

# Change an object by altering its attributes and calling save().
>>> r.full_name = ‘Billy Goat’
>>> r.save()

# Delete an object with delete().
>>> r.delete()

dynamic admin interface动态管理界面:不仅仅是脚手架(scaffolding)–it’s the whole house当你的models定义好后,Django能自动生成一个专业的,production ready管理界面(administrative interface),一个web站点,允许授权用户增加,修改和删除objects.方法很简单,即registering your model in the admin site.

# In models.py…

from django.db import models

class Article(models.Model):
    pub_date = models.DateTimeField()
    headline = models.CharField(max_length=200)
    content = models.TextField()
    reporter = models.ForeignKey(Reporter)

# In admin.py in the same directory…

import models
from django.contrib import admin

admin.site.register(models.Article)

此处的哲学思想(philosophy)是,你的站点将被员工,或者客户,或者是你自己编辑—而你,并不愿意去创建仅仅用来管理内容的后台接口。
创建Django apps典型的工作流程(workflow)是,create models,让admin sites跑起来,跑的越快越好。然后你的职员(或客户)可以开始输入数据了。接着,开发数据的显示方式。
Design your URLs一个干净的,优雅的URL机制在高质量的web application中是一个重要的细节部分。Django鼓励优美的URL设计,并且不把任何cruft放在URLs中,like .php or .asp.
给一个app设计URLs,你创建一个叫做URLconf的Python module. 一个你的app目录(contents)的表格,它包含一个简单的URL pattern与Python回调函数之间的映射。URLconfs也用来从Python代码中分离出URLs.
以下是一个URLconf的例子, 与上面的Reporter/Article例子相关:

from django.conf.urls.defaults import *

urlpatterns = patterns(”,
    (r’^articles/(\d{4})/$’, ’mysite.views.year_archive’),
    (r’^articles/(\d{4})/(\d{2})/$’, ’mysite.views.month_archive’),
    (r’^articles/(\d{4})/(\d{2})/(\d+)/$’, ’mysite.views.article_detail’),
)

上述代码,将URLs(一些简单的正则表达式),映射到Python回调函数(Python callback functions)(”views”).正则表达式使用括号来从URLs中得到值。当用户请求一个页面(request a page), Django遍历每个表达式,按顺序,在第一个匹配的位置停下。(如果没有一个匹配,Django调用一个special-case 404 view).上述过程非常快,因为正则表达式在加载的时候已经被编译了(compiled at load time).
一旦匹配,Django引入(import)并调用相应的view,view实际是一个简单的Python函数。每个view将被传递一个request object–其中含有request metadata–其值在正则表达式中e.g. 如果用户请求URL “/articles/2005/05/39323/”, Django会调用函数mysite.views.article_detail(request, ‘2005′, ‘05′, ‘39323′).
Write your views每个view负责做下面的两件事之一:返回一个HttpResponse object,包含请求页需要的内容,或者引发一个异常如Http404.The rest up to you.通常,一个view获得参数数据,loads a template,并且用获得的数据renders the template.以下是一个view的例子,year_archive函数

def year_archive(request, year):
    a_list = Article.objects.filter(pub_date__year=year)
    return render_to_response(’news/year_archive.html’, {’year’: year, ‘article_list’: a_list})

这个例子用的是Django的template system,它有很多强大的特性,但其目的是保持足够的简单来给非程序员使用。
Design your templates上述代码加载了news/year_archive.html这个templateDjango有一个template搜索路径,使你最小化templates之间的冗余。在你的Django设置里,你指定a list of directories来搜索templates.如果某个template在第一个路径不存在,接着寻找第二个,第三个。咱们假定news/article_detail.html已经找到,它看起来可能如下:

{% extends ”base.html” %}

{% block title %}Articles for {{ year }}{% endblock %}

{% block content %}
<h1>Articles for {{ year }}</h1>

{% for article in article_list %}
    <p>{{ article.headline }}</p>
    <p>By {{ article.reporter.full_name }}</p>
    <p>Published {{ article.pub_date|date:”F j, Y” }}</p>
{% endfor %}
{% endblock %}

变量用大括号括起来了。{{ article.headline }}意指“输出文章标题属性的值-output the value of the article’s headline attribute”但是点(dots)不仅仅用于attribute lookup,他们同样用于dictionary-key lookup和函数调用注意{{ article.pub_date|date:”F j, Y” }}使用了Unix-style的管道(pipe)(”|”符号)。这个叫做template filter,它是一种过滤变量值的方式。你可以链接(chain together)尽可能多的filters.你可以定制自己的filters.你可以定制自己的template tags,它能在后台运行定制的Python代码最后,Django使用了”template inheritance”的概念:正如{% extends “base.html” %}所做的。意指“首先加载名字是’base’的template”,它里面定义了一堆语句块…

Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • RSS
  • Slashdot
  • Technorati
  • TwitThis

Related posts:

  1. URL 调度程序
  2. URL 调度程序
  3. 在apache上面部署django应用
  4. Run taobao API using GAE
  5. Python list的排序
  6. django中ModelBase的属性
  7. BlogPump: Blog Post Client with Web Crawler(1) – big picture

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Contact us

Admin: Bryan Wu