Web.py Cookbook 简体中文版 - Use Jinja2 template engine in webpy

justjavac 发表于 2012-04-19

问题

如何在web.py中使用 Jinja2 模板引擎?

方案

首先需要安装Jinja2和webpy(0.3), 然后使用下面的代码做测试:

import web from web.contrib.template import render_jinja urls = ( '/(.*)', 'hello' ) app = web.application(urls, globals()) render = render_jinja( 'templates', # 设置模板路径. encoding = 'utf-8', # 编码. ) #添加或者修改一些全局方法. #render._lookup.globals.update(...

Web.py Cookbook 简体中文版 - Import functions into templates

justjavac 发表于 2012-04-19

Problem: How can I import a python module in template?

Solution:

While you write templates, inevitably you will need to write some functions which is related to display logic only. web.py gives you the flexibility to write large blocks of...

Web.py Cookbook 简体中文版 - 在webpy中使用Cheetah模板引擎

justjavac 发表于 2012-04-19

问题:

怎样在webpy中使用Cheetah模板引擎?

解决:

您需要先安装webpy(0.3)和Cheetah:http://www.cheetahtemplate.org/. 然后尝试使用下面的代码段:

# encoding: utf-8 # File: code.py import web from web.contrib.template import render_cheetah render = render_cheetah('templates/') urls = ( '/(first)', 'first', '/(second)', 'second' ) app = web.application(urls, globals(), web.reloader) class first: def GET(self,...

Web.py Cookbook 简体中文版 - 使用子应用

justjavac 发表于 2012-04-19

问题

如何在当前应用中包含定义在其他文件中的某个应用?

解法

blog.py中:

import web urls = ( "", "reblog", "/(.*)", "blog" ) class reblog: def GET(self): raise web.seeother('/') class blog: def GET(self, path): return "blog " + path app_blog = web.application(urls, locals())

当前的主应用code.py:

import web import...

Web.py Cookbook 简体中文版 - 如何流传输大文件

justjavac 发表于 2012-04-19

问题

如何流传输大文件?

解法

要流传输大文件,需要添加传输译码(Transfer-Encoding)区块头,这样才能一边下载一边显示。否则,浏览器将缓冲所有数据直到下载完毕才显示。

如果这样写:直接修改基础字符串(例中就是j),然后用Yield返回--是没有效果的。如果要使用Yield,就要向对所有内容使用yield。因为这个函式此时是一个产生器。(注:请处请详看Yield文档,在此不做过多论述。)

例子

# Simple streaming server demonstration # Uses time.sleep to emulate a large file read import web import time urls = ( "/", "count_holder", "/(.*)", "count_down", ) app = web.application(urls, globals()) class count_down:...