2008-9
4
发表于: Python | 作者: admin

Django 1.0终于发布啦!!

看看 Django 的创始人对于 1.0 发布的总结吧:

No, you’re not hallucinating, it’s really here.

Around three years ago, Adrian, Simon, Wilson and I released some code to the world. Our plan was to hack quietly on it for a bit, release a solid 1.0 release, and then really get the ball rolling.

Well.

What happened, of course, was that an amazing community sprung up literally overnight — our IRC channel had over a hundred people in it the day after release, and it’s never been that “empty” since.

I really can’t stress enough how amazing our community of users and developers are. About half of the code that’s gone into Django over the past three years has been contributed by someone other than a core committer. Since our last stable release, we’ve made over 4,000 code commits, fixed more than 2,000 bugs, and edited, added, or removed around 350,000 lines of code. We’ve also added 40,000 lines of new documentation, and greatly improved what was already there.

Django 1.0 represents a the largest milestone in Django’s development to date: a web framework that a group of perfectionists can truly be proud of. Without this amazing community, though, it would have never happened.

You can download Django 1.0 on the Django downloads page, and read the complete release notes.

For distributors and for verification purposes, a file containing the MD5 and SHA1 checksums of the 1.0 package has been placed on the djangoproject.com server. This file is PGP-signed with the Django release manager’s public key. This key has the ID 0×8C8B2AE1 and can be obtained from, e.g., the MIT PGP keyserver.

近来,北京的天气清爽了许多,时不时的在午夜或午后大雨倾盆。

很久没有酣畅淋漓的去做一件事情了,到现在也没有。

大雨如注,很对自己现在的心情。

真想跑进雨里,痛痛快快的任由这雨水肆意地冲刷、拍打,

直至我的体温冷却下来… …

父子情深-意大利-怀旧电影

电影简介

在一个风雨交加的夜晚,罗贝尔托在电唱机上放上一张唱片,立刻,优美的钢琴曲唤起了他对往日的回忆。这张唱片是他的儿子卢卡作为礼物送给他的,而现在卢卡已经永远地、永远地消失了。

十岁的卢卡是罗贝尔托的独生子,孩子的母亲已经去世了,做律师的父亲又公务繁忙,因此卢卡是在缺少亲人关怀的环境中长大。卢卡感到孤独,产生了对于父爱的强烈需要,他渴望能得到父亲更多的关怀。复活节假期到了,卢卡从学校回到了家中,他买了一张唱片预备送给父亲,同时打算和父亲商量一下假期怎么过,一直等到天黑,父亲也没回来。第二天早晨,父亲一早出门走了,卢卡只得到法院去找,总算找到父亲,罗贝尔托答应晚上和他再谈。可是,罗贝尔托晚上并没有回来,孤单无聊的卢卡架起放映机,放映父亲拍摄的家庭影片。在银幕上,卢卡看到了自己的母亲,同时又看到了另一个女人,一个欢乐的、充满朝气的女人。卢卡当然不知道这个名叫韦罗妮卡的女人正在和罗贝尔托相恋,只知道她不是自己的母亲。

又一个晚上,卢卡终于同父亲一起坐在餐馆共进晚餐了。罗贝尔托本来打算让韦罗妮卡同他们一起度假,可是卢卡一说“我就想和你在一起”,罗贝尔托只好把话咽了回去。然而,韦罗妮卡却由于担心同卢卡难以相处,因而在未同卢卡讲清楚之前不同意参与罗贝尔托的家庭生活。这可真使罗贝尔托感到这个爸爸不好当了。

他们三个人终于坐着轿车,踏上了度假的旅途。但是韦罗妮卡从卢卡那双猜疑而又充满不满的眼睛里看出,罗贝尔托并没有把她向卢卡介绍,因此到了度假地,韦罗妮卡不愿意同他们父子俩住在一起,而是单独住进了附近的旅馆。韦罗妮卡努力从心灵上同卢卡这个敏感的孩子接近,他们的关系慢慢地融洽了。

然而,韦罗妮卡的存在却使卢卡同父亲产生了隔阂。卢卡担心会失去父亲的爱,因此从度假地回来后一直闷闷不乐。在别人的劝说下,卢卡同父亲进行了一次严肃的交谈,罗贝尔托告诉他男人的生活里需要有女人作伴,而对韦罗妮卡的爱不会影响对卢卡的爱,父子俩终于和解。为了使卢卡高兴,罗贝尔托决定让卢卡推迟一个星期返校,他要带着卢卡到山上去滑雪。

在山上,父子俩玩得很高兴。不幸的事情发生了,卢卡在滑雪橇时不慎从山坡上滚了下来,住进了医院。这一回虽然并没有摔伤,医生却查出卢卡已经患了致命的白血病,罗贝尔托惊呆了。这时,罗贝尔托才感到自己平时对儿子的关心太少了,他很少到学校去看望卢卡,他总是以工作忙为借口,剥夺了卢卡同他在一起的机会,就连这次滑雪也是韦罗妮卡出的主意,他自问:“我都干了些什么啊!”

卢卡的病情急剧地恶化,在奄奄一息的时候,他提出要父亲带着他到渴望已久的游乐场去玩一次,罗贝尔托痛苦地答应了。也许是出于同情心,已经关门的空无一人的游乐场为卢卡重新开放,罗贝尔托抱着心爱的卢卡在各处玩着。由于父亲不来看望而经常遭到同学们嘲笑的卢卡看到整个游乐场都归他一个人玩时,苍白的脸上泛起了笑容并告诉父亲从学校回来时曾买过一张唱片,本来打算送给父亲,后来由于老是见不着父亲,自己生了气,把唱片藏了起来。现在他希望父亲找到唱片并且能喜欢它。卢卡深情地望着父亲,轻轻地说:“可惜我再也见不着你了,请你不要难过。”卢卡垂下了头,他在父亲的怀抱中,怀着对父亲的无限留恋离开了人世。
《父子情深》主题音乐聆听地址:http://www.likenote.com/listener/article/2575

#coding=utf-8
from django.db import models
import datetime

class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()

def __unicode__(self):
return self.headline

# 自定义方法
def was_published_today(self):
return self.pub_date == datetime.date.today()

# 使用 Django 的 Model API 进行数据筛选
def articles_from_same_day_1(self):
return Article.objects.filter(pub_date=self.pub_date).exclude(id=self.id)

# 使用自定义 SQL 语句进行相同操作的数据筛选
def articles_from_same_day_2(self):
“”"
自定义方法 get_articles_from_same_day_1 的详细版本,出于演示的缘故这里做了一个自定义数据库查询。
“”"
from django.db import connection # 导入数据库链接 connection
cursor = connection.cursor() # 返回一个数据库链接的游标

# 执行自定义数据库查询语句,并使用格式化参数进行替换
cursor.execute(”"”
SELECT id, headline, pub_date
FROM custom_methods_article
WHERE pub_date = %s
AND id != %s”"”, [str(self.pub_date), self.id])

# 使用游标获取所有符合条件的数据
# 而 “(*row)” 中的星号则告诉 Python 将动态长度列表参数 row 扩充为 Article 列表
return [self.__class__(*row) for row in cursor.fetchall()]

2008-7
5

版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://kimva.blogbus.com/logs/18646089.html

1.  下载字体,可到我的Mofile空间下载:Fonts.zip
或到以下地址下载:http://www.box.net/shared/lvh50qodvn
2.  将字体cp到~/.fonts 或者 /usr/local/share/fonts/ 或者 /usr/share/fonts/
其实放在~/.fonts是最简单的方法,也就是在主目录下新建一个文件夹命名为“.fonts”,然后把解压后的两个字体文件复制到其下面。命令如下:
sudo cp Fonts/*.ttf ~/.fonts
或者打开首选项-外观-字体-细节-转到字体文件夹,把雅黑字体复制进去就行了。
然后终端执行:
sudo fc-cache -f
3.  下载配置文件,可到我的Mofile空间下载:ubuntu-font-optimize.zip
或到以下地址下载:http://www.zflier.com/upload/ubuntu-font-optimize.zip

下载完毕后,解压,将其中的文件都复制到/etc/fonts/下

命令如下:
sudo cp ubuntu-font-optimize/*.conf /etc/fonts/
4.  调整字体选项。
系统–》首选项–》字体:
除了等宽字体外全部选择“微软雅黑”,等宽字体选雅黑的话终端字体不好看,还是选自己喜欢的吧。
字体渲染选择次像素平滑!(这一步是设置英文字体)
5.  按Ctrl+Alt+Backspace重启x server,并登录。

ASCII 是一种字符集,包括大小写的英文字母、数字、控制字符等,它用一个字节表示,范围是 0-127

Unicode分为UTF-8和UTF-16。UTF-8变长度的,最多 6 个字节,小于 127 的字符用一个字节表示,与 ASCII 字符集的结果一样,ASCII 编码下的英语文本不需要修改就可以当作 UTF-8 编码进行处理。

Python 从 2.2 开始支持 Unicode ,函数 decode( char_set )可以实现 其它编码到 Unicode 的转换函数 encode( char_set )实现 Unicode 到其它编码方式的转换

比如 (”你好”).decode( “GB2312″) 将得到 u’\u4f60\u597d’,即 “你”和“好”的 Unicode 码分别是 0×4f60 和 0×597d
再用 (u’\u4f60\u597d’).encode(”UTF-8″) 将得到 ‘\xe4\xbd\xa0\xe5\xa5\xbd’,它是  “你好”的UTF-8编码结果。

python中使用 unicode的关键:unicode是一个类,函数unicode(str,”utf8″)从utf8编码(当然也可以是别的编码)的字符串str生成 unicode类的对象,而函数unc.encode(”utf8″)将unicode类的对象unc转换为(编码为)utf8编码(当然也可以是别的编码)的字符串。于是,编写unicode相关程序,需要做的事情是

* 获取数据(字符串)时,用unicode(str, “utf8″)生成unicode对象
* 在程序中仅使用unicode对象,对程序中出现的字符串常量都以u”字符串”的形式书写
* 输出时,可将unicode对象转换为任意编码输出,使用str.encode(”some_encoding”)

>>> unicode(”你好”, “utf8″)
u’\u4f60\u597d’
>>> x = _
>>> type(x)

>>> type(”你好”)

>>> x.encode(”utf8″)
‘\xe4\xbd\xa0\xe5\xa5\xbd’
>>> x.encode(”gbk”)
‘\xc4\xe3\xba\xc3′
>>> x.encode(”gb2312″)
‘\xc4\xe3\xba\xc3′
>>> print x
你好
>>> print x.encode(”utf8″)
你好
>>> print x.encode(”gbk”)
???

以 上是测试结果(Ubuntu 6.06,locale为utf8),注意type(x)和type(”你好”)的区别。从编码上可以看出utf8编码与gbk不同。在utf8的 locale设置下,打印x按该环境变量编码(我猜我猜我猜猜猜),而打印x.encode(”gbk”)则是乱码

2008-7
1
发表于: WebServer, nginx | 作者: admin
标签: ,

建议:FreeBSD RELENG_6
使用心得:nginx处理大并发比较稳定,特别省内存,配置简单.
1.安装python

cd /usr/ports/lang/python
make install clean

2.安装flup

cd /usr/ports/www/py-flup
make install clean

3.安装django 1)

cd /usr/ports/www/py-django
make install clean

4.安装nginx

cd /usr/ports/www/nginx
make install clean

5.启动和管理flup的脚本 参考http://www.djangoproject.com/documentation/fastcgi/

#!/bin/sh
# Replace these three settings.
PROJDIR="/home/user/myproject"
PIDFILE="$PROJDIR/mysite.pid"
SOCKET="$PROJDIR/mysite.sock"
cd $PROJDIR
if [ -f $PIDFILE ]; then
kill `cat -- $PIDFILE`
rm -f -- $PIDFILE
fi
exec /usr/local/bin/python manage.py runfcgi method=prefork socket=${SOCKET} pidfile=${PIDFILE} minspare=5 maxspare=10 maxchildren=40

6.配置nginx 参考http://wiki.codemongers.com/Main
nginx.conf

user  www www;
worker_processes  5;
pid /var/run/nginx.pid;
error_log  /var/log/httpd/error.log warn;
events {
worker_connections  10240;
use kqueue;
}
http {
include       mime.types;
default_type  application/octet-stream;
log_format  main  '$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$gzip_ratio"';
client_header_timeout  3m;
client_body_timeout    3m;
send_timeout           3m;
connection_pool_size        256;
client_header_buffer_size    1k;
large_client_header_buffers    4 2k;
request_pool_size        4k;
output_buffers   4 32k;
postpone_output  1460;
sendfile        on;
tcp_nopush             on;
keepalive_timeout      75 20;
tcp_nodelay            on;
client_max_body_size       10m;
client_body_buffer_size    256k;
proxy_connect_timeout      90;
proxy_send_timeout         90;
proxy_read_timeout         90;
client_body_temp_path      /var/log/nginx/client_body_temp;
proxy_temp_path            /var/log/nginx/proxy_temp;
fastcgi_temp_path          /var/log/nginx/fastcgi_temp;
gzip on;
gzip_min_length  1100;
gzip_buffers     4 32k;
gzip_types       text/plain text/html application/x-javascript text/xml text/css;
ignore_invalid_headers    on;
include    website.conf;
}

website.conf

server {
listen 80;
server_name test.tmdxy.org;
access_log    /var/log/httpd/access.log main;
location / {
# host and port to fastcgi server
fastcgi_pass unix:/tmp/test_tmdxy.sock;
fastcgi_param PATH_INFO $fastcgi_script_name;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_pass_header Authorization;
fastcgi_param REMOTE_ADDR           $remote_addr;
fastcgi_param SERVER_PROTOCOL       $server_protocol;
fastcgi_param SERVER_PORT           $server_port;
fastcgi_param SERVER_NAME           $server_name;
fastcgi_intercept_errors off;
}
location ^~ /media/ {
alias    /home/www/django/test_tmdxy_org/meida/;
}
location ~* ^.+\.(gif|png|jpg|jpeg|css|swf|htm|html|asp|php|jsp|js|doc|txt)$ {
root    /home/www/django/test_tmdxy_org/media/;
access_log   off;
}
}

7.配置反向代理服务器
只需在server {}里加入

location /go/ {
proxy_pass http://192.168.1.5:8088/;
proxy_redirect http://192.168.1.5:8088/ /;

}
1) 我使用svn版
[原文地址]http://wiki.freebsdchina.org/doc/n/nginx_django

据说某股票明年三月至少会翻番,最近身边的人都在忙着准备买港股。因为中国金融被打了鸡血针,所以大家谈论的都是投资的问题。

前天和同事讨论到了男女的问题,然后也扯到了投资上,两件事情的模式是一样的:付出,然后期望回报。

上回拿公式来算男女的价值,结果让男人自卑,女人也嫌看不懂。于是今天给大家看看米国人的问答

这篇文章最初是来自美国的一个大型网站的金融版上。文章起因是一个年轻漂亮的美国女孩在网上论坛版发表了这样一个问题帖:我怎样才能嫁给有钱人?她的话说得真诚坦率,原文如下:

I am 25 years old, is one of those people Spectacular, beautiful, how can I marry the rich?

I would like to say the following are the truth. I am 25 years old, very pretty, is the kind of nice people and colorful, conversation elegant and good taste, would like to marry an annual salary of 500,000 US dollars. Maybe you would say that I am greedy, but 1 million annual salaries in New York to be the middle, I actually do not request high.

This version has no annual salary of more than 500,000 people? You married? I would like to ask you a question - how to marry you to the rich? I have people around, the richest annual salary of 250,000; it seems to be my limit. Admitted to the New York Central Park west of luxury residential, the annual salary of 250,000 is far from enough. I sincerely ask for the. There are several specific issues: First, the wealthy bachelor generally spend time where? (Please list of bars, restaurants, the gym’s name and full address.) Second, I should have set the target at which age? Third, why is it that it looks rich wife mediocre? I have seen some girls, looks like water, there are no attractive places, but they managed to marry Homer. Single bars, and the beautiful women who listen but poor luck. Fourth, determine who you how the wife, who can only do a girlfriend? (I now aim is to get married.)

– Ms. Bowers

我下面要说的都是心里话。本人25岁,非常漂亮,是那种让人惊艳的漂亮,谈吐文雅,有品位,想嫁给年薪 50万美元的人。你也许会说我贪心,但在纽约年薪100万才算是中产,本人的要求其实不高。

这个版上有没有年薪超过 50万的人?你们都结婚了吗?我想请教各位一个问题——怎样才能嫁给你们这样的有钱人?我约会过的人中,最有钱的年薪 25万,这似乎是我的上限。要住进纽约中心公园以西的高尚住宅区,年薪25万远远不够。我是来诚心诚意请教的。有几个具体的问题:一、有钱的单身汉一般都 在哪里消磨时光? (请列出酒吧、饭店、健身房的名字和详细地址。)二、我应该把目标定在哪个年龄段?三、为什么有些富豪的妻子看起来相貌平平?我见过有 些女孩,长相如同白开水,毫无吸引人的地方,但她们却能嫁入豪门。而单身酒吧里那些迷死人的美女却运气不佳。四、你们怎么决定谁能做妻子,谁只能做女朋 友?(我现在的目标是结婚。)

——波尔斯女士

下面是一个华尔街金融投资顾问的回帖,最有趣的是他对投资美女的投资增值空间所做的分析:

Your beauty will fade away, but my money is not reduced; So I value assets, accelerated depreciation of assets you .

Dear Powles I read with great interest your note; I believe that many of you also have the similar questions. Let me take as an investment expert to analyze this situation. My annual salary more than 500,000,in line with your spouse, so please believe that I am not a waste of everyone’s time.

For a businessman’s view, with your marriage is a bad business decision-making, reasoning clear enough, please listen to me explain. Set aside marginal, in fact you have said is a simple “wealth”, “Outlook” transactions: Party A person’s appearance provided references, B million expense, fair trade, everybody. However, here there is a fatal problem, your beauty will fade away, but my money is not for no reason at all reduced. In fact, my income is likely to increase year-by-year T, year by year and you cannot pretty.

Therefore, from the economics perspective, I value assets, the depreciation of assets you are not only devalued, but also accelerated depreciation! You are now 25, in the next five years, you can still maintain the posture slim, pretty appearance, although a slight decline each year. But the beauty of speed will increasingly vanish fast if it is your only asset, the value of ten years after you very worried.

With Wall Street terminology, each transaction has positions, the contacts are with you “trading position”, if the value fell to sell immediately, but not long-term holders - that is, you want the marriage. This sounds cruel, but it will accelerate a depreciation of the material, a wise choice is leasing, rather than buying. The annual salary to more than 500,000 people, of course, are not idiots, we will contact with you, but not with your marriage. Therefore, I advise you not to marry the rich hard to find the secret formula. Incidentally, you want to approach but can be turned into the annual salary of 500,000 own people, than get a rich fool’s chance of winning is bigger.

I hope this replies can help you. If your “rent” interested, please contact with me.

– Bo Luo. Campbell (J P Morgan variety of investment advisers)

亲爱的波尔斯:我怀着极大的兴趣看完了贵帖,相信不少女士也有跟你类似的疑问。让我以一个投资专家的身份,对你的处境做一分析。我年薪超过50万,符合你的择偶标准,所以请相信我并不是在浪费大家的时间。

从生意人的角度来看,跟你结婚是个糟糕的经营决策,道理再明白不过,请听我解释。抛开细枝末节,你所说的其实是一笔简单的“财貌”交易:甲方提供述 人的外表,乙万出钱,公平交易,童叟无欺。但是,这里有个致命的问题,你的美貌会消逝,但我的钱却不会无缘无故减少。事实上,我的收入很可能会逐年涕增。 而你不可能一年比一年漂亮。

因此从经济学的角度讲,我是增值资产,你是贬值资产,不但贬值,而且是加速贬值!你现在25,在未来的5年里,你仍可以保持窈窕的身段,俏丽的容貌,虽然每年略有退步。但美貌消逝的速度会越来越快,如果它是你仅有的资产,十年以后你的价值甚忧。

用华尔街术语说,每笔交易都有一个仓位,跟你交往属于“交易仓位”(tradingl position),一旦价值下跌就要立即抛售,而不宜长期持有——也就是你想要的婚姻。听起来很残忍,但对一件会加速贬值的物资,明智的选择是租赁,而 不是购入。年薪能超过50万的人,当然都不是傻瓜,因此我们只会跟你交往,但不会跟你结婚。所以我劝你不要苦苦寻找嫁给有钱人的秘方。顺便说一句,你倒可 以想办法把自己变成年薪50万的人,这比碰到一个有钱的傻瓜的胜算要大。

希望我的回帖能对你有帮助。如果你对”租赁”感兴趣,请跟我联系。

——罗波.坎贝尔(J·P·摩根银行多种产业投资顾问)

从女性的角度反过来想想如何做这个投资,有点儿意思吧?

2008-7
1
发表于: CSS, UI | 作者: admin
标签:

原文作者:Brett
原文链接:14 CSS Tools to Save you Time
译者:Chada

作为一个网站设计/开发人员,你必须不断寻找方法来减少设计/开发过程中所花费的时间。这对于提高你的工作效率并最大化你的利润是非常重要的。下面介绍的按功能分类的CSS工具可以有效地节省你设计网站的时间。Chada在这基础上增加了三个自己曾经介绍过的工具。

优化/格式化类

1、CSSTidy - CSS Tidy是一个开源的CSS分析和优化工具;
2、CleanCSS - CleanCSS是一个基于CSS Tidy的强大的CSS优化和格式化工具。Chada曾经介绍过这个在线工具,在这里
3、CSS Optimizer - CSS Optimizer可以通过优化压缩CSS样式文件大小。
4、CSS Analyzer - CSS Analyzer可以帮助你检查你的CSS样式是否符合W3C的认证。

字体类

1、Em Calculator - EM Calculator可以帮助你计算px与em之间的转换。
2、CSS Font and Text Style Wizard - 这个小工具可以很方便地将你的CSS样式呈现出来。

表格类

1、CSS Form Code Maker - 很方便地生成“五颜六色的BOX布局”的表格。
2、JotForm - JotForm是一个“所见即所得”的表格生成器。

导航/按钮类

1、CSS Buttons - CSS按钮和文本在线生成工具。
2、CSS Menu Generator - CSS Menu Generator可以同时生成基于CSS和HTML代码的漂亮的按钮。

生成器

1、CSS Creator - Css Creator是一个可以创建自适应宽度或者是固定宽度的浮动布局生成器,可以生成带有Header和Footer的三栏布局。
2、QrONE CSS Designer - QrONE是一个CSS在线生成与编辑器。
3、Web 2.0 Generator - Web 2.0 Generator可以利用HTML和CSS生成一个完整的网站布局。
4、CSS Mate - CSS Mate是一个在线CSS编辑器。

除了上面译文中的14个小工具外,Chada还介绍过如下几款小工具,它们也是非常棒的,你可以打开下面的文章看它们的详细介绍:

1、CSS Menu Maker - 在线生成丰富多样的CSS导航按钮。
2、CSS Type Set - 在线轻松调试CSS文本样式。
3、CSS Frame Generator - 写好DIV架构之后,使用这个在线工具可以很快生成CSS样式结构表。

如果你有知道的其他可以节省时间的CSS在线工具,欢迎写下评论把它[们]介绍给Chada。

来自译言-电脑/网络/数码

2008-6
27

简单的例子

这里我们做了一些工作,完成了一些例子来说明框架的基本语法。你可以通过点击 web2py 的关键字(文档中高亮的部分)来获取相关的说明文档。

例子1

控制器: simple_examples.py

1.

2.
def hello1():

    return “Hello World”

如果控制器的函数返回一个字符串,那这个字符串就是渲染之后页面的主体内容了。

点击预览: hello1

例子2

控制器: simple_examples.py

1.

2.
def hello2():

    return T(“Hello World”)

函数 T() 将字符串标示为待翻译的字符串。翻译的字典可以通过管理界面中 /admin/default/design 链接来创建。

点击预览: hello2

例子3

控制器: simple_examples.py

1.

2.
def hello3():

    return dict(message=T(“Hello World”))

视图: simple_examples/hello3.html

1.
2.
3.
{{extend ‘layout.html’}}

<h1>{{=message}}</h1>

如果你在控制器中返回了一个字典,那么字典中定义的变量对于视图(模板)来说将是可见的了。

点击预览: hello3

例子4

控制器: simple_examples.py

1.

2.

3.
def hello4():

    response.view=’simple_examples/hello3.html’

   return dict(message=T(“Hello World”))

在控制器中你可以选择使用哪个视图模板来渲染数据,但是系统默认的是 /[controller]/[function].html。 如果没找到默认模板 web2py 会尝试使用内置的 generic.html 来渲染视图。 点击预览: hello4

例子5

控制器: simple_examples.py

1.

2.
def hello5():

    return HTML(BODY(H1(T(‘Hello World’),_style=“color: red;”))).xml() # .xml 用于序列化

你可以使用系统的HTML,BODY,H1等助手对象来生成 HTML代码。这些标签中的任意一个都是一个类,而视图也知道如何去渲染相应的对象。.xml() 方法负责序列化这些对象并为页面产生 html 或 xml 代码。 每一个标签,比如 DIV,可接收如下三个参数:

  • 未命名参数,负责嵌套的标签。
  • 以 ‘_’ 开头的命名参数。 这些参数会移除 ‘_’ 从而和 html 的标签属性对应上,像 “READONLY” 这样的无值属性可以用 “_readonly=ON” 参数来创建。
  • 不以 ‘_’ 开头的命名参数。他们有一个特殊的意义,等会儿看下 INPUT, TEXTAREA, SELECT 标签的 “value=” 参数。

点击预览: hello5

例子6

控制器: simple_examples.py

1.

2.
def status():

    return dict(request=request,session=session,response=response)

这里我们通过 generic.html 模板来展示 request, session ad response 对象。

点击预览: status

例子 7

控制器: simple_examples.py

1.

2.
def redirectme():

    redirect(URL(r=request,f=‘hello3′))

你也可以在控制器中做跳转操作。

点击预览: redirectme

例子 8

控制器: simple_examples.py

1.

2.
def raisehttp():

    raise HTTP(400,“internal error”)

你可以通过引发一个 HTTP 异常来向客户端返回一个错误页面。

点击这里看下效果: raisehttp

例子 9

控制器: simple_examples.py

1.

2.

3.
def raiseexception():

     1/0

    return ‘oops’

如果系统发生异常(不同于 HTTP),web2py 会为管理员生成一个出错的票据并记录下这个事件。这些票据和日志随后可以被存取、回顾和删除。
点击预览: raiseexception

例子10

控制器: simple_examples.py

1.

2.

3.

4.
def servejs():

    import gluon.contenttype

     response.headers[‘Content-Type’]=gluon.contenttype.contenttype(‘.js’)

    return ‘alert(”This is a Javascript document, it is not supposed to run!”);’

通过 response.headers 改变 contenttype(web2py的一个内容类型模块)你可以处理除了 HTML 页面之外的其他内容类型。gluon.contenttype 模块可以帮助你确认需要处理的文件类型。注意: 对于静态文件而言没必要通过这种方式处理,除非你想进行权限验证。
点击预览: servejs

例子11

控制器: simple_examples.py

1.

2.

3.
def makejson():

    import gluon.contrib.simplejson as sj

    return sj.dumps([‘foo’, {‘bar’: (‘baz’, None, 1.0, 2)}])

如果你在使用 Ajax, web2py 包含了gluon.contrib.simplejson 模块, 该模块由 Bob Ippolito 开发。这个模块提供了一个快速、简单的方式来处理 Ajax 页面上的异步内容。gluon.simplesjson.dumps(…) 方法可以将大部分的 Python 类型序列化为 JSON。gluon.contrib.simplejson.loads(…) 方法执行相反的操作。
点击预览: makejson

例子12

控制器: simple_examples.py

1.
2.
3.
4.
5.
6.
7.
8.
9.
def makertf():
    import gluon.contrib.pyrtf as q
    doc=q.Document()
    section=q.Section()
    doc.Sections.append(section)
    section.append(‘Section Title’)
    section.append(‘web2py is great. ‘*100)
    response.headers[‘Content-Type’]=‘text/rtf’
    return q.dumps(doc)

web2py 也包含了 gluon.contrib.pyrtf, 由 Simon Cusack 开发,Grant Edwards 维护。这个模块允许你生成包含彩色化、格式化文字和图片的 Rich Text Format(富文本格式)文档。
点击预览: makertf

例子13

控制器: simple_examples.py

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
def rss_aggregator():
    import datetime
    import gluon.contrib.rss2 as rss2
    import gluon.contrib.feedparser as feedparser
    d = feedparser.parse(“http://rss.slashdot.org/Slashdot/slashdot/to”)

    rss = rss2.RSS2(title=d.channel.title,
                  link = d.channel.link,
                  description = d.channel.description,
                     lastBuildDate = datetime.datetime.now(),
                     items = [rss2.RSSItem(
                            title = entry.title,
                            link = entry.link,
                            description = entry.description,
                            # guid = rss2.Guid(’unkown’),
                            pubDate = datetime.datetime.now()) for entry in d.entries]
                  )
response.headers[‘Content-Type’]=‘application/rss+xml’
return rss2.dumps(rss)

web2py 包含了 gluon.contrib.rss2, 由 Dalke Scientific 软件开发, 可以用来生成 RSS2 订阅源, 而 gluon.contrib.feedparser, 由 Mark Pilgrim 开发, 用于聚集 RSS and ATOM 订阅源。 上面的这个控制器使用 feedparser 模块聚集了一个 slashdot 网站的订阅源,并使用 rss2 模块生成了一个新的订阅源。
点击预览: rss_aggregator

例子14

控制器: simple_examples.py

1.
2.
3.
4.
5.
6.
7.
8.
9.
from gluon.contrib.markdown import WIKI

def ajaxwiki():
    form=FORM(TEXTAREA(_id=‘text’),INPUT(_type=‘button’,_value=‘markdown’,
_onclick=“ajax(’ajaxwiki_onclick’,[’text’],’html’)”))
return dict(form=form,html=DIV(_id=‘html’))

def ajaxwiki_onclick():
return WIKI(request.vars.text).xml()

web2py 也包含了 gluon.contrib.markdown (markdown2)模块 ,用于使用如下语法转换 WIKI 标签为 HTML代码 . 在这个例子中我们添加了一个精美的 ajax 效果。
点击预览: ajaxwiki