文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>web.py 0.3 教程(2)

web.py 0.3 教程(2)

时间:2010-12-29  来源:sun5411

发邮件

用 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

  1. environ a.k.a. env — a dictionary containing the standard WSGI environment variables
  2. home — the base path for the application http://example.org
  3. homedomain — ??? http://example.org
  4. homepath — ???
  5. host — the domain requested by the user example.org
  6. ip — the IP address of the user xxx.xxx.xxx.xxx
  7. method — the HTTP method used GET
  8. path — the path requested by the user /articles/845
  9. protocol — the protocol used https
  10. query — an empty string if there are no query arguments otherwise a ? followed by the query string ?foo=amorphous&bar=blasphemous
  11. fullpath a.k.a. path + query — the full path requested including query arguments /articles/845?foo=amorphous&bar=blasphemous

Response

  1. status — the HTTP status code (default '200 OK') 401 Unauthorized
  2. headers — a list of 2-tuples containing HTTP headers
  3. 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()

注意

  1. form 表单必须有属性 enctype="multipart/form-data",否则文件上传会不正常。
  2. 在 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')
排行榜 更多 +
找茬脑洞的世界安卓版

找茬脑洞的世界安卓版

休闲益智 下载
滑板英雄跑酷2手游

滑板英雄跑酷2手游

休闲益智 下载
披萨对对看下载

披萨对对看下载

休闲益智 下载