Web.py Cookbook 简体中文版 - 模板文件中的i18n支持

justjavac 发表于 2012-04-19

问题:

在web.py的模板文件中, 如何得到i18n的支持?

Solution:

项目目录结构:

 proj/ |- code.py |- i18n/ |- messages.po |- en_US/ |- LC_MESSAGES/ |- messages.po |- messages.mo |- templates/ |- hello.html 

文件: proj/code.py

 #!/usr/bin/env python # encoding: utf-8 import web import gettext...

Web.py Cookbook 简体中文版 - Hello World!

justjavac 发表于 2012-04-19

问题

如何用web.py实现Hello World!?

解法

import web urls = ("/.*", "hello") app = web.application(urls, globals()) class hello: def GET(self): return 'Hello, world!' if __name__ == "__main__": app.run()

提示:要保证网址有无’/’结尾,都能指向同一个类。就要多写几行代码,如下:

在URL开头添加代码:

'/(.*)/', 'redirect', 

然后用redirect类处理以’/’结尾的网址:

class redirect: def GET(self, path):...

Web.py Cookbook 简体中文版 - 怎样使用表单 forms

justjavac 发表于 2012-04-19

问题:

怎样使用表单 forms

解决:

‘web.form’模块提供支持创建,校验和显示表单。该模块包含一个’Form’类和各种输入框类如’Textbox’,’Password’等等。

当’form.validates()’调用时,可以针对每个输入检测的哪个是有效的,并取得校验理由列表。

‘Form’类同样可以使用完整输入附加的关键字参数’validators’来校验表单。

这里是一个新用户注册的表单的示例:

import web from web import form render = web.template.render('templates') # your templates vpass = form.regexp(r".{3,20}$", 'must be between 3 and 20 characters') vemail = form.regexp(r".*@.*", "must be a valid email...

Web.py Cookbook 简体中文版 - 个别显示表单字段

justjavac 发表于 2012-04-19

问题:

怎样在模板中个别显示表单字段?

解决:

你可以使用’render()’方法在你的模板中显示部分的表单字段。

假设你想创建一个名字/姓氏表单。很简单,只有两个字段,不需要验证,只是为了测试目的。

from web import form simple_form = form.Form( form.Textbox('name', description='Name'), form.Textbox('surname', description='Surname'), )

通常你可以使用simple_form.render()simple_form.render_css()。 但如你果你想一个一个的显示表单的字段,或者你怎样才能对模板中的表单显示拥有更多的控制权限?如果是这样,你可以对你的个别字段使用render()方法。

我们定义了两个字段名称为namesurname。这些名称将自动成为simple_form对象的属性。

>>> simple_form.name.render() '<input type="text" name="name" id="name" />' >>> simple_form.surname.render() '<input type="text" name="surname" id="surname" />' 

你同样可以通过类似的方法显示个别的描述:

>>> simple_form.surname.description...

Web.py Cookbook 简体中文版 - File Upload Recipe

justjavac 发表于 2012-04-19

问题

如果你不是很了解表单上传或者CGI的话, 你会觉得文件上传有点奇特.

解决方法

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={}) web.debug(x['myfile'].filename) # 这里是文件名...