web.py 十分钟创建简易博客实现代码

 更新时间:2016年04月22日 22:04:53   作者:TCM-caleng  
web.py是一款轻量级的Python web开发框架,简单、高效、学习成本低,特别适合作为python web开发的入门框架

一、web.py简介
web.py是一款轻量级的Python web开发框架,简单、高效、学习成本低,特别适合作为python web开发的入门框架。官方站点:http://webpy.org/

二、web.py安装
1、下载:http://webpy.org/static/web.py-0.33.tar.gz
2、解压并进入web.py-0.33目录,安装:python setup.py install

三、创建简易博客
1、目录说明:主目录blog/,模板目录blog/templates
2、在数据库“test”中创建表“entries”

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

3、在主目录创建blog.py,blog/blog.py

#载入框架
import web
#载入数据库操作model(稍后创建)
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:
 def GET(self, id):
  post = model.get_post(int(id))
  return render.view(post)
#新建文章类
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 POST(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()

4、在主目录创建model.py,blog/model.py

import web
import datetime
#数据库连接
db = web.database(dbn = 'MySQL', db = 'test', user = 'root', pw = '123456')
#获取所有文章
def get_posts():
 return db.select('entries', order = 'id DESC')
 
#获取文章内容
def get_post(id):
 try:
  return db.select('entries', where = 'id=$id', vars = locals())[0]
 except IndexError:
  return None
#新建文章
def new_post(title, text):
 db.insert('entries',
  title = title,
  content = text,
  posted_on = datetime.datetime.utcnow())
#删除文章
def del_post(id):
 db.delete('entries', where = 'id = $id', vars = locals())
 
#修改文章
def update_post(id, title, text):
 db.update('entries',
  where = 'id = $id',
  vars = locals(),
  title = title,
  content = text)

5、在模板目录依次创建:base.html、edit.html、index.html、new.html、view.html

<!-- base.html -->
$def with (page)
<html>
 <head>
  <title>My Blog</title>
  <mce:style><!--
   #menu {
    width: 200px;
    float: right;
   }
  
--></mce:style><style mce_bogus="1">   #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>

<!-- 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>

<!-- 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>

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

<!-- view.html -->
$def with (post)
<h1>$post.title</h1>
$post.posted_on<br />
$post.content

6、进入主目录在命令行下运行:python blog.py,将启动web服务,在浏览器输入:http://localhost:8080/,简易博客即已完成。

相关文章

  • python格式化输出保留2位小数的实现方法

    python格式化输出保留2位小数的实现方法

    这篇文章主要介绍了python格式化输出保留2位小数的实现方法,需要的朋友可以参考下
    2019-07-07
  • OpenCV立体图像深度图Depth Map基础

    OpenCV立体图像深度图Depth Map基础

    这篇文章主要为大家介绍了OpenCV立体图像深度图Depth Map基础详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-05-05
  • 何用Python实现一个 “系统声音” 的实时律动挂件

    何用Python实现一个 “系统声音” 的实时律动挂件

    这篇文章将给大家介绍了如何用 Python 实现一个 “系统声音” 的实时律动挂件,采集后直接实时地在电脑上绘制波形动画,主要是用来作为 FL Studio 播放时的一个桌面小挂件,文中有相关的代码示例供大家参考,需要的朋友可以参考下
    2024-01-01
  • pytorch分类模型绘制混淆矩阵以及可视化详解

    pytorch分类模型绘制混淆矩阵以及可视化详解

    混淆矩阵是ROC曲线绘制的基础,同时它也是衡量分类型模型准确度中最基本,最直观,计算最简单的方法,下面这篇文章主要给大家介绍了关于pytorch分类模型绘制混淆矩阵以及可视化的相关资料,需要的朋友可以参考下
    2022-04-04
  • Python Pygame绘制直线实现光线反射效果

    Python Pygame绘制直线实现光线反射效果

    这篇文章主要为大家详细介绍了如何利用Python Pygame绘制直线以实现光线反射效果,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2023-11-11
  • Python实现自动计算Excel数据指定范围内的区间最大值

    Python实现自动计算Excel数据指定范围内的区间最大值

    这篇文章主要为大家详细介绍了如何基于Python自动计算Excel数据指定范围内的区间最大值,文中的示例代码简洁易懂,感兴趣的小伙伴可以了解下
    2023-07-07
  • Python OpenCV实现视频追踪

    Python OpenCV实现视频追踪

    这篇文章主要为大家详细介绍了Python OpenCV实现视频追踪,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-08-08
  • python下载卫星云图合成gif的方法示例

    python下载卫星云图合成gif的方法示例

    这篇文章主要介绍了python下载卫星云图合成gif的方法示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-02-02
  • Py之pycocotools库的简介、安装、使用方法及说明

    Py之pycocotools库的简介、安装、使用方法及说明

    这篇文章主要介绍了Py之pycocotools库的简介、安装、使用方法及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-02-02
  • python+Matplotlib 绘制带置信区间的折线图

    python+Matplotlib 绘制带置信区间的折线图

    这篇文章主要介绍了python绘制带置信区间的折线图,在本文中,我们将使用 numpy 模块生成随机数据,并使用 matplotlib 库实现数据可视化,需要的朋友可以参考下
    2023-05-05

最新评论