用 gmail 发邮件
先用 web.config 配置 smtp
web.config.smtp_server = 'smtp.gmail.com'
web.config.smtp_port = 587
web.config.smtp_username = '[email protected]'
web.config.smtp_password = 'secret'
web.config.smtp_starttls = True
再用类似下边的发邮件
web.sendmail('[email protected]', '[email protected]', 'subject', 'message')
或者可以附上邮件头
web.sendmail('[email protected]', ['[email protected]', '[email protected]'],
'subject', 'message',
cc='[email protected]', bcc='[email protected]',
headers=({'User-Agent': 'webpy.sendmail', 'X-Mailer': 'webpy.sendmail',})
)
获取客户端信息
web.ctx
例子
class example:
def GET(self):
referer = web.ctx.env.get('HTTP_REFERER', 'http://google.com')
useragent = web.ctx.env.get('HTTP_USER_AGENT')
raise web.seeother(referer)
ctx 里的数据
Request
- environ a.k.a. env — a dictionary containing the standard WSGI environment variables
- home — the base path for the application http://example.org
- homedomain — ??? http://example.org
- homepath — ???
- host — the domain requested by the user example.org
- ip — the IP address of the user xxx.xxx.xxx.xxx
- method — the HTTP method used GET
- path — the path requested by the user /articles/845
- protocol — the protocol used https
- query — an empty string if there are no query arguments otherwise a ? followed by the query string ?foo=amorphous&bar=blasphemous
- fullpath a.k.a. path + query — the full path requested including query arguments /articles/845?foo=amorphous&bar=blasphemous
Response
- status — the HTTP status code (default '200 OK') 401 Unauthorized
- headers — a list of 2-tuples containing HTTP headers
- output — a string containing the response entity
模板
web.py 支持模板(注意需要 python-cheetah)
先看看将 第一个程序 改为使用模板
写入 templates/hello.html :
$def with (name, todos={})
$if name:
<h1>你好,$name!</h1>
$else:
<h1>你好,世界!</h1>
注意模板文件首行要个 $def with() ,
在 code.py 里用
render = web.template.render('templates/')
class hello:
def GET(self, name):
return render.hello(name)
变量替换
Look, a $string.
Hark, an ${arbitrary + expression}.
Gawk, a $dictionary[key].function('argument').
Cool, a $(limit)ing.
Stop, \$money isn't uated.
We use basically the same semantics as (rejected) PEP 215. Variables can go anywhere in a document.
连接多行
If you put a backslash \
at the end of a line \
(like these) \
then there will be no newline.
这会输出一整行
异常
Here are some expressions:
$for var in iterator: I like $var!
$if times > max:
Stop! In the name of love.
$else:
Keep on, you can do it.
$try:
$get(input)
$except:
Couldn't find it.
That's all, folks.
注释
$# Here's where we hoodwink the folks at home:
Please enter in your deets:
CC: [ ] $#this is the important one
SSN: $#Social Security Number#$ [ ]
$# 到行末的是注释
代码
可以将 python 语句放在行首的 "$ " 后(从"$ " 开始,之道行尾,或下一个 "$" )
$def with()
$ mapping = dict(a=[1, 2, 3],
$ b=[4, 5, 6])
<b>$mapping['a'][0]</b>
传递变量
可以这样设置模板里的全局变量
len = 'cn'
web.template.Template.globals[len] = len
或者直接传递 globals()
web.template.Template.globals = globals()
也可以在 metaclass.func 里传递 locals()
class index:
def GET(self):
title = '你好,世界'
entrys = ['第一个', '第二个', '第三个']
s = web.Storage(locals())
return render.index(s)
而 templates/index.html 里用
$def with(s)
...<title>$s.title</title>
...
<ul>
$for entry in s.entrys:
<li>$entry</li>
</ul>
用户输入
表单
重复表单项
复选框有重复的表单项,譬如 http://example.com?id=10&id=20 这样的请求,可以用类似下边代码获得多个id 项值
class SomePage:
def GET(self):
user_data = web.input(id=[])
return "<h1>" + ",".join(user_data.id) + "</h1>"
文件上传
例子
import web
urls = ('/upload', 'Upload')
class Upload:
def GET(self):
return """<html><head></head><body>
<form method="POST" enctype="multipart/form-data" action="">
<input type="file" name="myfile" />
<br/>
<input type="submit" />
</form>
</body></html>"""
def POST(self):
x = web.input(myfile={})
return "filename: %s\n value: \n%s" % (x['myfile'].filename, x['myfile'].value)
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
注意
- form 表单必须有属性 enctype="multipart/form-data",否则文件上传会不正常。
- 在 webpy 代码里,web.input() 参数必须有默认值(如上边的 myfile={} )。否则 web.input 不能获取文件名,而只能获取文件内容。
数据库
web.py 0.3 有更好的 db 处理
import web
db = web.database(dbn='postgres', db='todo', user='you', pw='')
db.select('todo')
db.select('todo', where='id=$id', vars={'id': 2})
db.query('SELECT * FROM todo')