web.py学习总结

来源:互联网 发布:org.apache.shiro文档 编辑:程序博客网 时间:2024/05/22 08:17
1.
    pip  install  web.py
2.
    hello  world 程序
    import web
urls = ("/.*", "hello")
app = web.application(urls, globals())
class hello:    #定义的类没有括号
    def GET(self):     #类中的GET为大写
        return 'Hello, world!'    #return直接
if __name__ == "__main__":
    app.run()   #运行服务
3.
    静态文件 当前文件下建文件夹static 注意目录名只能是static  ,然后http://127.0.0.1:8080/static/1.jpg 即可访问
4.
    urls = (
         '/', 'Index',
        '/login', 'Login' ,
        ‘/home/(\d*)’, 'Home',          #url同样可以路径传值,  def  GET(self, id):  接收即可
 )  所有urls皆放在一个元组中
5.
     重定向   raise  web.seeother('/new')      raise   web.redirect('/new')    注意是raise
    用web.redirect方法似乎也能做同样的事情,但通常来说,这并太友好。因为web.redirect发送的是301消息-这是永久重定向。因为大多数Web浏览器会缓存新的重定向,所以当我们再次执行该操作时,会自动直接访问重定向的新网址。很多时候,这不是我们所想要的结果。所以在提交表单时,尽量使用seeother。但是在下面要提到的这种场合,用redirect却是最恰当的:我们已经更改了网站的网址结构,但是仍想让用户书签/收藏夹中的旧网址不失效。
6.
      def POST():
        data = web.data()   表单提交后获取数据
7.
       添加钩子卸载钩子http://webpy.org/cookbook/application_processors.zh-cn
      即在视图处理方法之前或之后,其中result = handler() 为视图处理方式进行状态
8,
      web.header('Content-type', "text/html; charset=utf-8")   返回头信息
      input = web.input()
         1.得到post表单提交的数据同web.data()   2.得到url参数传值 ?key=var 的内容,类型为web.storage 类似字典      访问方式和字典相同input['key']   input.get('key')   属性访问input.key
      age = web.input(age='23') 设置age默认值为23
     如果传递的是多值变量,如多选等   /?id=1&id=2 则要给个默认值为空列表才能完整接收到  id=web.input(id=[])
 9.
     web.setcookie(‘username’,  'jim', 3600)设置cookie,有效期为3600秒  ,如果第三个参数为空,cookie就永不过期。
     web.setcookie('username', '',  -1)   将时间设置成-1,则是删除cookie
    方法1(如果找不到cookie,就返回None):
web.cookies().get(cookieName)
    #cookieName is the name of the cookie submitted by the browser
方法2(如果找不到cookie,就抛出AttributeError异常):
foo = web.cookies()
foo.cookieName
方法3(如果找不到cookie,可以设置默认值来避免抛出异常):
foo = web.cookies(cookieName=defaultValue)
foo.cookieName   # return the value (which could be default)
    #cookieName is the name of the cookie submitted by the browser
10.
     所有模板放在templates文件下
   $def with (name, age)  #模板接收变量,必须是模板的第一行
   Hello $name!    #模板中用变量
   程序中,如果上模板叫hello.html
方法一:
   render = web.template.render('templates')    #此处templates 为模板目录
   return render.hello(name='world', age='23')     #调用hello.html模板,且向其中传入变量值,这里传入的值模板必须主动接收
   globals = {'a': 'aaaa', 'b': 'bbbb','fun': fun, 'obj': obj}    #其中可以传函数,还可以传对象
    render = web.template.render('templates',  globals=globals)   #传入多个值也可用globals参数,且模板不必主动接收,直接用即可
    return  render.hello()


方式二:
  用文件的方式来处理模板 frender:
hello = web.template.frender('templates/hello.html')      #也有globals参数,用来传多值。
return hello('world')
方式三:
直接使用字符串方式:
template = "$def with (name)\nHello $name"
hello = web.template.Template(template)
return hello('world')
11.
  如上hello('world')是向模板中传入一个值,hello()则是直接渲染模板不传值,注意一定要加()否则只传了模板对象
  传值接收  $def  with (name)
  在模板中直接定义一个变量  $  name = 'jim'   注意$与变量名之间一定要有空格
12.
   $# 是注释指示符。任何以 $# 开始的某行内容都被当做注释。
13.
   模板系统支持 for, while, if, elif 和 else。像 python 一样,这里是需要缩进的。
    $for i in range(10):
         I like $i
for 循环内的成员变量只在循环内发生可用:
loop.index: the iteration of the loop (1-indexed)
loop.index0: the iteration of the loop (0-indexed)
loop.first: True if first iteration
loop.last: True if last iteration
loop.odd: True if an odd iteration
loop.even: True if an even iteration
loop.parity: "odd" or "even" depending on which is true
loop.parent: the loop above this in nested loops
14.
     可以使用 $def 定义一个新的模板函数,支持使用参数。
$def say_hello(name='world'):
    Hello $name!
$say_hello('web.py')
$say_hello()
15.
   $def fun(value):
<div>
$value
</div>
<hr />
$:fun('ok')   $#结果<div>这类html标签发挥作用
$fun('ok')    $#结果html的标签不发挥作用,作为字符串输出  <div>ok</div><hr />
16.
   可以在 code 块书写任何 python 代码:


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


    def limit(s, width=10):
        """limits a string to the given width"""
        if len(s) >= width:
            return s[:width] + "..."
        else:
            return s
然后在模板中就可以用$x,  $y, $z, $limit('ok')
17.
     var 块可以用来定义模板结果的额外属性:
$def with (title, body)
$var title: $title
$var content_type: text/html
<div id="body">
$body
</div>
18.
    模板继承通过base参数
    render = web.template.render('templates/', base='base')
    return render.index()   继承了模板base.html
base.html中挖坑通过定义变量来实现
$def with (content)     $#必须为模板的第一句话,第一行
<html>
<body>
$:content
</body>
</html>
19.
文件上传
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={})      #注意最好加默认值为空字典
        file_name = x['myfile'].filename # 这里是文件名
        file_value = x['myfile'].value # 这里是文件内容
       # file_value = x['myfile'].file.read() # 或者使用一个文件对象
        f_var = file('static/'+filename, 'wb')
        f_var.write(filevalue)
        f_var.close()
        raise web.seeother('/upload')
20.
   使用web自带的form模块
    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 address")


register_form = form.Form(
    form.Textbox("username", description="Username"),
    form.Textbox("email", vemail, description="E-Mail"),
    form.Password("password", vpass, description="Password"),
    form.Password("password2", description="Repeat password"),
    form.Button("submit", type="submit", description="Register"),
    validators = [
        form.Validator("Passwords did't match", lambda i: i.password == i.password2)]


)


class register:
    def GET(self):
        # do $:f.render() in the template
        f = register_form()
        return render.register(f)


    def POST(self):
        f = register_form()
        if not f.validates():
            return render.register(f)
        else:
            # do whatever is required for registration
模板中
$def with(form)


<h1>Register</h1>
<form method="POST">
    $:form.render()
</form>
21.
   数据库
   db = web.database(dbn='mysql', db='dbname', user='root', pw='123456')
   user = db.select('users', where='id=id')   查找  user[0]或者  user.i.next()  可以看内容,格式为web.storage类字典
   db.update('users',  where='id=id', username='jim' )   更改
   db.delete('mytable', where="id=10")   删除
   sequence_id = db.insert('mytable', username="Bob",joindate=web.SQLLiteral("NOW()"))   增加数据
 查询也可直接用:
results = db.query("SELECT * FROM users")    注意没有db.excute()
print results[0].username
22.
  注意事项
  1. 在<form>  标签内不能写action=' . '  这样会直接跳到根路径,而不是当前url。可以不写,最好写全
 2.   data = web.input(headimg={})
       headimg =  data.get('headimg')
     上传文件,此时headimg如果转化为布尔值的话,无论是否有上传文件,都是False。如果要判断,是否用户上传了,这样  if   headimg.filename:
就可以了
3.翻页,用$code在
$code:
def next(page):
page += 1
return page
def up(page):
page -= 1
return page
$if page != last_page and last_page != 0:
<a href="?page=$next(page)" >下一页</a>
$if page != 1:
<a href="?page=$up(page)" >上一页</a>