globals = {'markdown': markdown.markdown}全局对象参数传递

GET and POST: the difference

  • GET is the one we're all familiar with, the one used to request the text of a web page.
  • The second-most famous, POST, is often used when submitting certain kinds of forms, like a request to purchase something.

实例如下:

import web

render = web.template.render('templates/')
#This tells web.py to look for templates in your templates directory.

urls = (
    '/', 'index'
)
#This line says we want the URL / (i.e. the front page) to be handled by the class named index.

name = 'Bob'    
return render.index(name)
#'index' is the name of the template and 'name' is the argument passed to it

if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()
#First we tell web.py to create an application with the URLs we listed above, looking up the classes in the global namespace of this file. And finally we make sure that web.py serves the application we created above.

当有人用GET请求/时,类中的GET函数随时会被web.py调用。

url匹配:

  • /list/?id=10,?之后的部分表示是’查询‘,不会被匹配,可通过web.input获取输入,user_data=web.input(id='no data'),指定默认值为no data而不是None
  • /list/(.+),list/之后的将会被捕捉,作为参数被用在GET或POST。

template:

  • As you can see, the templates look a lot like Python files except for the def with statement at the top (saying what the template gets called with) and the $ placed in front of any code.
  • Also, note that web.py automatically escapes any variables used here, so that if for some reason name is set to a value containing some HTML, it will get properly escaped and appear as plain text. If you want to turn this off, write $:name instead of $name.

template文件中$:表示不转义,$表示转义:

  • $ name=1在赋值变量名称之前要有一个空格,区别于常规的赋值。
  • $greeting的内容都会被替换成对应这个变量名的参数
  • web.py 将会转义任何用到的变量,所以当你将 name 的值设为是一段 HTML 时,它会被转义显示成纯文本。如果要关闭该选项,可以写成$:name来代替$name
    $def with (name)
    Hello $name!

    The first line says that the template is defined with one argument called name. $name in the second line will be replaced with the value of name when the template is rendered.

web.py流程

  • 运行脚本(创建一个端口通信)
  • 浏览器输入localhost:端口(本地电脑)
  • 浏览器对脚本发出HTTP请求(request),请求访问URL/
  • 脚本根据URL和类的匹配关系,加载相应的类
  • 针对类的实例调用方法函数,返回相应的值
  • web.py将返回值传递给浏览器以完成浏览器的请求处理

web.datestr

Converts a (UTC) datetime object to a nice string representation.

最后由 oucb 编辑于2016年05月03日 17:26