web.py 0.3 新手指南 - 发送邮件

justjavac 发表于 2012-04-19

问题

在web.py中,如何发送邮件?

解法

在web.py中使用web.sendmail()发送邮件.

web.sendmail('cookbook@webpy.org', 'user@example.com', 'subject', 'message')

如果在web.config中指定了邮件服务器,就会使用该服务器发送邮件,否则,就根据/usr/lib/sendmail中的设置发送邮件。

web.config.smtp_server = 'mail.mydomain.com'

如果要发送邮件给多个收件人,就给to_address赋值一个邮箱列表。

web.sendmail('cookbook@webpy.org', ['user1@example.com', 'user2@example.com'], 'subject', 'message')

ccbcc关键字参数是可选的,分别表示抄送和暗送接收人。这两个参数也可以是列表,表示抄送/暗送多人。

web.sendmail('cookbook@webpy.org', 'user@example.com', 'subject', 'message', cc='user1@example.com', bcc='user2@example.com')

headers参数是一个元组,表示附加标头信息(Addition headers)

web.sendmail('cookbook@webpy.org', 'user@example.com', 'subject', 'message', cc='user1@example.com', bcc='user2@example.com', headers=({'User-Agent': 'webpy.sendmail', 'X-Mailer': 'webpy.sendmail',}) )
...

web.py 0.3 新手指南 - db.select 查询

justjavac 发表于 2012-04-19

问题:

怎样执行数据库查询?

解决方案:

如果是0.3版本, 连接部分大致如下:

db = web.database(dbn='postgres', db='mydata', user='dbuser', pw='')

当获取数据库连接后, 可以这样执行查询数据库:

# Select all entries from table 'mytable' entries = db.select('mytable')

select方法有下面几个参数:

  • vars
  • what
  • where
  • order
  • group
  • limit
  • offset
  • test

vars

vars变量用来填充查询条件. 如:

...

web.py 0.3 新手指南 - 实时语言切换

justjavac 发表于 2012-04-19

layout: default

title: 实时语言切换

实时语言切换

问题:

如何实现实时语言切换?

解法:

文件: code.py

import os import sys import gettext import web # File location directory. rootdir = os.path.abspath(os.path.dirname(__file__)) # i18n directory....

web.py 0.3 新手指南 - RESTful doctesting using app.request

justjavac 发表于 2012-04-19

!/usr/bin/env python

""" RESTful web.py testing usage: python webapp.py 8080 [--test] >>> req = app.request('/mathematicians', method='POST') >>> req.status '400 Bad Request' >>> name = {'first': 'Beno\xc3\xaet', 'last': 'Mandelbrot'} >>> data = urllib.urlencode(name) >>> req = app.request('/mathematicians', method='POST', data=data) >>>...

Web.py Cookbook 简体中文版 - 跳转(seeother)与重定向(redirect)

justjavac 发表于 2012-04-19

web.seeother 和 web.redirect

问题

在处理完用户输入后(比方说处理完一个表单),如何跳转到其他页面?

解法

class SomePage:
    def POST(self):
        # Do some application logic here, and then:
        raise web.seeother('/someotherpage')

POST方法接收到一个post并完成处理之后,它将给浏览器发送一个303消息和新网址。接下来,浏览器就会对这个新网址发出GET请求,从而完成跳转。

注意:web.seeother和web.redirect不支持0.3以下版本。

区别

用web.redirect方法似乎也能做同样的事情,但通常来说,这并太友好。因为web.redirect发送的是301消息-这是永久重定向。因为大多数Web浏览器会缓存新的重定向,所以当我们再次执行该操作时,会自动直接访问重定向的新网址。很多时候,这不是我们所想要的结果。所以在提交表单时,尽量使用seeother。但是在下面要提到的这种场合,用redirect却是最恰当的:我们已经更改了网站的网址结构,但是仍想让用户书签/收藏夹中的旧网址不失效。

(注:要了解seeother和redirect的区别,最好是看一下http协议中不同消息码的含义。)