webpy入门

webpy_tutorial

import web

urls = (
    '/', 'index'
    )

这行表示我们要URL/(首页)被一个叫index的类处理

创建一个列举这些url的application

app = web.application(urls, globals())

现在来写index类,首先定义GET或者POST两个方法

class index:
    def GET(self):
        return "hello, world"

有人用GET发出请求时,GET函数会被web.py调用

最后开始运行代码:

if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()

完整的代码保存为server.py:

import web

urls = (
    '/', 'index'
)

class index:
    def GET(self):
        return "Hello, world!"

if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()

命令行输入python server.py就可以运行这个简单的服务器,也可以指定端口号:

python server.py 1234

 

模板

给模板新建一个目录,命名为templates,在该目录下新建一个hello.html文件,内容如下:

<em>Hello</em>, world!

然后在server.py的第一行下面添加:

render = web.py.template.render('templates/')

这会告诉web.py到模板目录去查找模板,然后修改index.GET:

return render.hello()

这里hello是刚才创建的模板名字hello.html

修改之后运行server.py,访问站点将会显示粗体的'hello,world!'

接下来可以再模板中增加一些交互功能,修改hello.html:

$def with (name)

$if name:
    I just wanted to say <em>hello</em> to $name.
$else:
    <em>Hello</em>, world!

这里的模板代码与python代码类似,代码段之前都有$

然后修改server.py中的index.GET:

def GET(self):
    name = 'Alice'
    return render.hello(name)

这里name会作为参数传入到模板里面,正如模板文件的开头要求传入的参数

现在运行server.py后访问将会显示I just wanted to say hello to Alice. ,当然如果参数是空字符串将会显示Hello, world!

如果让用户输入自己的名字,修改index.GET:

i = web.input(name=None)
return render.index(i.name)

在访问的地址后面加上/?name=Alice就可以通过GET的形式访问,将会显示I just wanted to say hello to Joe.

如果觉得URL后面跟着?看起来不好看,可以修改URL的配置:

'/(.*)', 'index'

然后修改URL配置:

def GET(self, name):
    return render.hello(name)

这样对于/后面的任何字符串都可以进行处理,作为name参数进行传递

 
使用mysqldb

首先安装好mysqldb,在数据库中创建一个表todo,并插入一项数据:

CREATE TABLE todo (
  id serial primary key,
  title text,
  created timestamp default now(),
  done boolean default false);
  
INSERT INTO todo (title) VALUES ('Learn web.py');

在server.py中创建一个数据库对象,

db = web.database(dbn = 'mysql',
        user = 'root',
        pw = 'password',
        db = 'dbname')

将URL列表修改回只有'/', 'index',然后hello.html修改如下:

$def with (todos)
<ul>
$for todo in todos:
    <li id="t$todo.id">$todo.title</li>
</ul>

修改index.GET函数:

def GET(self):
    todos = db.select('todo')
    return render.hello(todos)

现在重新访问服务器可以看到运行页面为learn web.py,这样就做到了在数据库读取数据。

现在再写一个把数据写入数据库的程序,首先在hello.html尾部添加:

<form method="post" action="add">
<p><input type="text" name="title" /> <input type="submit" value="Add" /></p>
</form>

给html增加了一个输入表格还有提交的按钮

修改URL列表为:

'/', 'index',
'/add', 'add'

上面添加了一个add类来处理这种情况,所以在server.py中增加add类:

class add:
    def POST(self):
        i = web.input()
        n = db.insert('todo', title = i.title)
        raise web.seeother('/')

这里web.input()可以访问用户通过form提交的任何数据,保存之后重新运行server.py,就可以在网页上给数据库添加记录了

原文地址:https://www.cnblogs.com/jolin123/p/4071919.html