1. 程式人生 > >python基於web.py的簡易blog

python基於web.py的簡易blog

初始化 init.sql:

CREATE TABLE blog (
    id INT AUTO_INCREMENT,
    title TEXT,
    content TEXT,
    posted_on DATETIME,
    primary key (id)
);

CREATE TABLE comment(
     id INT AUTO_INCREMENT,
     content TEXT,
     posted_on DATETIME,
     blog_id INT,
     primary key (id)
     );


my_blog.py

#! /usr/bin/python
# encoding:utf-8

import web
import model
# url對映
urls = (
    '/', 'Index',
    '/view/(\d+)', 'View',
    '/new', 'New',
    '/delete/(\d+)', 'Delete',
    '/edit/(\d+)', 'Edit',
    '/login', 'Login',
    '/logout', 'Logout',
)

app=web.application(urls,globals())
# 模板公共變數
t_globals = {
    'datestr': web.datestr,
    'cookie': web.cookies,
}
# 指定模板目錄,並設定公共模板
render=web.template.render('templates',base='base',globals=t_globals)
# 建立登入表單
login = web.form.Form(
    web.form.Textbox('username'),
    web.form.Password('password'),
    web.form.Button('login')
)
# 首頁類
class Index:
    def GET(self):
        login_form=login()
        posts=model.get_posts()
        return render.index(posts,login_form)
    def POST(self):
        login_form=login()
        if login_form.validates():
            if login_form.d.username=='admin' \
                and login_form.d.password=='admin':
                web.setcookie('username',login_form.d.username)
        raise  web.seeother('/')
# 檢視/評論文章類,
class View():
    form=web.form.Form(
        web.form.Textarea('comments',
                         web.form.notnull,
                         rows=5,
                         cols=40,
                         description='comment contents:'),
        web.form.Button('commit')
    )
    def GET(self,id):
        form=self.form()
        print id
        post = model.get_post(int(id))
        comments=model.get_comments(int(id))
        return render.view(post,comments,form)
    def POST(self,id):
        form=self.form()
        post=model.get_post(int(id))
        comments=model.get_comments(int(id))
        if not form.validates():
            return render.view(post,comments,form)
        model.new_comment(form.d.comments,id)
        comments_new=model.get_comments(int(id))
        return render.view(post,comments_new,form)

# 新建文章類
class New:
    form=web.form.Form(
        web.form.Textbox('title',
                         web.form.notnull,
                         size=30,
                         description='Post title: '),
        web.form.Textarea('content',
                          web.form.notnull,
                          rows=30,
                          cols=80,
                          description='Post content: '),
        web.form.Button('Post entry'),
    )
    def GET(self):
        form=self.form()
        return render.new(form)
    def POST(self):
        form=self.form()
        if not form.validates():
            return render.new(form)
        model.new_post(form.d.title,form.d.content)
        raise web.seeother('/')
# 刪除文章類
class Delete:
    def GET(self,id):
        model.del_post(int(id))
        raise web.seeother('/')
# 編輯文章類
class Edit:
    def GET(self,id):
        post=model.get_post(int(id))
        form=New.form()
        form.fill(post)
        return render.edit(post,form)
    def POST(self,id):
        form=New.form()
        post=model.get_post(int(id))
        if not form.validates():
            return render.edit(post,form)
        model.update_post(int(id),form.d.title,form.d.content)
        raise web.seeother('/')
# 退出登入
class Logout:
    def GET(self):
        web.setcookie('username','',expires=-1)
        raise web.seeother('/')
# 定義404
def notfound():
    return web.notfound("sorry,the page you were looking for was not found")
app.notfound=notfound

# 執行
if __name__ == '__main__':
    app.run()

model.py:
#! /usr/bin/pythpn
# encoding:utf-8

import web
import datetime
# 資料庫連線
db=web.database(dbn='mysql',host='192.168.48.10',port=3306,db='test',user='test',pw='mysql')
# 獲取所有文章
def get_posts():
    return db.select('blog',order='id')
# 獲取文章內容
def get_post(id):
    try:
        return db.select('blog',where = 'id=$id',vars=locals())[0]
    except IndexError:
        return None
# 獲取文章評論
def get_comments(id):
    try:
        return db.select('comment',where= 'blog_id=$id',vars=locals())
    except IndexError:
        return None
# 新建評論
def new_comment(comment,id):
    db.insert('comment',
              content=comment,
              posted_on=datetime.datetime.utcnow(),
              blog_id=id)
# 新建文章
def new_post(title,text):
    db.insert('blog',
              title=title,
              content=text,
              posted_on=datetime.datetime.utcnow())
# 刪除文章
def del_post(id):
    db.delete('blog',where='id = $id',vars=locals())

#修改文章
def update_post(id, title, text):
    db.update('blog',
        where = 'id = $id',
        vars = locals(),
        title = title,
        content = text)

html模板:

base.html:

$def with (page)
<html>
    <head>
        <title>My Blog</title>
        <style>
            #menu {
                width: 200px;
                float: right;
            }
        </style>
    </head>

    <body>
        <ul id="menu">
            <li><a href="/" mce_href="">Home</a></li>
            $if cookie().get('username'):
                <li><a href="/new" mce_href="new">New Post</a></li>
        </ul>

        $:page
    </body>
</html>
index.html
$def with (posts, login_form)
<h1>Blog posts</h1>
$if not cookie().get('username'):
    <form action="" method="post">
    $:login_form.render()
    </form>
$else:
    Welcome $cookie().get('username')!<a href="/logout" mce_href="logout">Logout</a>

<ul>
    $for post in posts:
        <li>
            <a href="/view/$post.id" mce_href="view/$post.id">$post.title</a>
            on $post.posted_on
            $if cookie().get('username'):
                <a href="/edit/$post.id" mce_href="edit/$post.id">Edit</a>
                <a href="/delete/$post.id" mce_href="delete/$post.id">Del</a>
        </li>
</ul>

view.html
$def with (post,comments,form)
<h1>$post.title</h1>
$post.posted_on<br />
$post.content
<ul>
    $for comment in comments:
        <li>
            <a> $comment.content</a>
            on $comment.posted_on
        </li>
</ul>
<form action="" method="post">
$:form.render()
</form>

new.html:
$def with (form)
<h1>New Blog Post</h1>
<form action="" method="post">
$:form.render()
</form>

edit.html:
$def with (post, form)
<h1>Edit $form.d.title</h1>
<form action="" method="post">
    $:form.render()
</form>
<h2>Delete post</h2>
<form action="/delete/$post.id" method="post">
    <input type="submit" value="Delete post" />
</form>