web.py Templetor

本文深入介绍了web.py模版语言Templetor的使用方法,包括语法、表达式替换、赋值、过滤、续行、转义、注释、控制结构等核心特性,并展示了如何通过多种方式渲染模版。此外,文章还详细阐述了变量、代码块、var块、内置函数和全局变量的使用,以及安全性和升级指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. http://blog.chinaunix.net/uid-7429703-id-461731.html
  2. Summary
  3. 介绍
  4. 模版系统用法
  5. 语法
  6. 表达式替换
  7. 赋值
  8. 过滤
  9. Newline suppression
  10. 转义Escaping '$'
  11. 注释Comments
  12. 控制结构Control Structures
  13. 其他语句Other Statements
  14. $def : define a new template function using $def
  15. $code : arbitrary python code can be written
  16. $var : can be used to define additional properties
  17. Builtins and globals
  18. Security
  19. Upgrading from web.py 0.2 templates

介绍
  1. 设计 web.py 模版语言 Templetor 是想把 Python的强悍扩张到模版这块. 它重用了 python 语法,而不是重创一个. Templetor 限制从模版内访问变量.

  2. 下面是一个简单的模版:

  3. $def with (name)
  4. Hello $name!

  5. 首行在模版声明接受一个叫做 name 的参数. 渲染模版时第二行的 $name 将被替换成 name 的值.


  6. 使用模版系统
  7. 渲染模版最常用方式是:

  8. render = web.template.render('templates')
  9. print render.hello('world')

  10. 函数 render 接受一个模版库路径作为参数. render.hello(..) 使用给定的参数调用模版 hello.html. 实际上是在模版库下搜索首个匹配 hello.* 的文件.

  11. 当然,也可以用 frender 从指定文件创建模版.

  12. hello = web.template.frender('templates/hello.html')
  13. print hello('world')

  14. 当然,还可以将模版放到一个字符串中:

  15. template = "$def with (name)\nHello $name"
  16. hello = web.template.Template(template)
  17. print hello('world')



  18. 语法

  19. 表达式替换, 特殊字符 $ 用来指定 python 表达式. 
  20. 表达式可以用 ()  {} 括起来以显式区分.

  21. Look, a $string.
  22. Hark, an ${arbitrary + expression}.
  23. Gawk, a $dictionary[key].function('argument').
  24. Cool, a $(limit)ing.


  25. 赋值
  26. 有时需要定义新变量和重新赋值给某些变量.

  27. $ bug = get_bug(id)
  28. <h1>$bug.title</h1>
  29. <div>
  30.     $bug.description
  31. <div>

  32. 注意赋值表达式中 $ 之后的空格.这里是必需的,以用来区别于表达式替换(如果没有空格: $bug = get(id), 则只是将 $bug 替换成值, 而不是赋值).


  33. 过滤
  34. Templetor默认采用 web.websafe 过滤器进行 HTML-编码.

  35. >>> render.hello("1 < 2")
  36. "Hello 1 &lt; 2"

  37. 如果不需要过滤器,则在 '$' 后面加一个 ':', 就可以为其后(该行)的代码关闭暂时过滤器:

  38. 下面例子将不会被 html 转义.
  39. $:form.render()

  40. 续行
  41. 通过在行尾加反斜杠 \ 可以续行

  42. If you put a backslash \
  43. at the end of a line \
  44. (like these) \
  45. then there will be no newline.

  46. 转义 '$'
  47. 用 $$ 可在输出中得到一个'$':
  48. Can you lend me $$50?

  49. 注释
  50. $# 用来表示注释. 该行其后所有内容都被忽略.
  51.          $# this is a comment   
  52. Hello $name.title()! $# display the name in title case


  53. 控制结构
  54. T模版系统支持 for, while, if, elif  else. 注意,和 python 一样, 控制体需要缩进.

  55. $for i in range(10):
  56.     I like $i

  57. $for i in range(10): I like $i

  58. $while a:
  59.     hello $a.pop()

  60. $if times > max:
  61.     Stop! In the name of love.
  62. $else:
  63.     Keep on, you can do it.

  64. 不同的是这里的 for 循环设置了循环中可以访问的一系列变量:
    1. loop.index: the iteration of the loop (1-indexed)
    2. loop.index0: the iteration of the loop (0-indexed)
    3. loop.first: True if first iteration
    4. loop.last: True if last iteration
    5. loop.odd: True if an odd iteration
    6. loop.even: True if an even iteration
    7. loop.parity: "odd" or "even" depending on which is true
    8. loop.parent: the loop above this in nested loops

    9. 有时,这是非常有用的.
  65. <table>
  66. $for c in ["a", "b", "c", "d"]:
  67.     <tr class="$loop.parity">
  68.         <td>$loop.index</td>
  69.         <td>$c</td>
  70.     </tr>
  71. </table>


  1. 其他语句
  2. def
  3. 使用 $def 可以定义新的模版函数. 同时还支持 Keyword arguments .

  4. $def say_hello(name='world'):
  5.     Hello $name!

  6. $say_hello('web.py')
  7. $say_hello()
  8. Another example:

  9. $def tr(values):
  10.     <tr>
  11.     $for v in values:
  12.         <td>$v</td>
  13.     </tr>

  14. $def table(rows):
  15.     <table>
  16.     $for row in rows:
  17.         $:row
  18.     </table>

  19. $ data = [['a', 'b', 'c'], [1, 2, 3], [2, 4, 6], [3, 6, 9] ]
  20. $:table([tr(d) for d in data])




  1. code
  2. 在 code 块中可以写任意的 python 代码.

  3. $code:
  4.     x = "you can write any python code here"
  5.     y = x.title()
  6.     z = len(x + y)

  7.     def limit(s, width=10):
  8.         """limits a string to the given width"""
  9.         if len(s) >= width:
  10.             return s[:width] + "..."
  11.         else:
  12.             return s
  13. 其中在 code 块中定义的变量就可以在之后使用了. 例如, $limit(x)


  14. var
  15. var 块中用来定义模版结果中的其他属性.

  16. $def with (title, body)

  17. $var title: $title
  18. $var content_type: text/html

  19. <div id="body">
  20. $body
  21. </div>
  22. 上面模版的结果可以如下使用:

  23. >>> out = render.page('hello', 'hello world')
  24. >>> out.title
  25. u'hello'
  26. >>> out.content_type
  27. u'text/html'
  28. >>> str(out)
  29. '\n\n
    \nhello world\n
    \n'



  1. builtins  globals

  2. Just like any Python function, template can also access builtins along with its arguments and local variables. Some common builtin functions like range, min, max etc. and boolean values True and False are made available to all the templates. Apart from the builtins, application specific globals can be specified to make them accessible in all the templates.

  3. Globals can be specified as an argument to web.template.render.

  4. import web
  5. import markdown

  6. globals = {'markdown': markdown.markdown}
  7. render = web.template.render('templates', globals=globals)
  8. Builtins that are exposed in the templates can be controlled too.

  9. # disable all builtins
  10. render = web.template.render('templates', builtins={})

  11. Security

  12. One of the design goals of Templetor is to allow untrusted users to write templates.
  13. To make the template execution safe, the following are not allowed in the templates.

  14. Unsafe statements like import, exec etc.
  15. Accessing attributes starting with _
  16. Unsafe builtins like open, getattr, setattr etc.
  17. SecurityException is raised if your template uses any of these.


  18. Upgrading from web.py 0.2 templates

  19. The new implementation is mostly compatible with the earlier implementation. However some cases might not work because of the following reasons.

  20. Template output is always storage like TemplateResult object, however converting it to unicode or str gives the result as unicode/string.
  21. Reassigning a global value will not work. The following will not work if x is a global.

  22.   $ x = x + 1
  23. The following are still supported but not preferred.

  24. Using \$ for escaping dollar. Use $$ instead.
  25. Modifying web.template.Template.globals. pass globals to web.template.render as argument instead.
内容概要:本文介绍了基于Python实现的SSA-GRU(麻雀搜索算法优化门控循环单元)时间序列预测项目。项目旨在通过结合SSA的全局搜索能力和GRU的时序信息处理能力,提升时间序列预测的精度和效率。文中详细描述了项目的背景、目标、挑战及解决方案,涵盖了从数据预处理到模型训练、优化及评估的全流程。SSA用于优化GRU的超参数,如隐藏层单元数、学习率等,以解决传统方法难以捕捉复杂非线性关系的问题。项目还提供了具体的代码示例,包括GRU模型的定义、训练和验证过程,以及SSA的种群初始化、迭代更新策略和适应度评估函数。; 适合人群:具备一定编程基础,特别是对时间序列预测和深度学习有一定了解的研究人员和技术开发者。; 使用场景及目标:①提高时间序列预测的精度和效率,适用于金融市场分析、气象预报、工业设备故障诊断等领域;②解决传统方法难以捕捉复杂非线性关系的问题;③通过自动化参数优化,减少人工干预,提升模型开发效率;④增强模型在不同数据集和未知环境中的泛化能力。; 阅读建议:由于项目涉及深度学习和智能优化算法的结合,建议读者在阅读过程中结合代码示例进行实践,理解SSA和GRU的工作原理及其在时间序列预测中的具体应用。同时,关注数据预处理、模型训练和优化的每个步骤,以确保对整个流程有全面的理解。
内容概要:本文详细介绍了如何使用PyQt5创建一个功能全面的桌面备忘录应用程序,涵盖从环境准备、数据库设计、界面设计到主程序结构及高级功能实现的全过程。首先,介绍了所需安装的Python库,包括PyQt5、sqlite3等。接着,详细描述了SQLite数据库的设计,创建任务表和类别表,并插入默认类别。然后,使用Qt Designer设计UI界面,包括主窗口、任务列表、工具栏、过滤器和日历控件等。主程序结构部分,展示了如何初始化UI、加载数据库数据、显示任务列表以及连接信号与槽。任务管理功能方面,实现了添加、编辑、删除、标记完成等操作。高级功能包括类别管理、数据导入导出、优先级视觉标识、到期日提醒、状态管理和智能筛选等。最后,提供了应用启动与主函数的代码,并展望了扩展方向,如多用户支持、云同步、提醒通知等。 适合人群:零基础或初学者,对Python和桌面应用程序开发感兴趣的开发者。 使用场景及目标:①学习PyQt5的基本使用方法,包括界面设计、信号与槽机制;②掌握SQLite数据库的基本操作,如创建表、插入数据、查询等;③实现一个完整的桌面应用程序,具备增删改查和数据持久化功能;④了解如何为应用程序添加高级特性,如类别管理、数据导入导出、到期日提醒等。 阅读建议:此资源不仅适用于零基础的学习者,也适合有一定编程经验的开发者深入理解PyQt5的应用开发。建议读者跟随教程逐步实践,结合实际操作来理解和掌握每个步骤,同时可以尝试实现扩展功能,进一步提升自己的开发技能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值