免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3130 | 回复: 0
打印 上一主题 下一主题

[翻译]Django at a glance--Django初窥 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-11-20 19:39 |只看该作者 |倒序浏览

                                                                                                                由于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”,它里面定义了一堆语句块...
               
               
               
               
               
               
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/72694/showart_2099641.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP