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


Posted in Python onApril 22, 2016

一、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 相关文章推荐
Python使用plotly绘制数据图表的方法
Jul 18 Python
python编写微信远程控制电脑的程序
Jan 05 Python
pytorch中tensor的合并与截取方法
Jul 26 Python
flask session组件的使用示例
Dec 25 Python
Python实现去除图片中指定颜色的像素功能示例
Apr 13 Python
Python模块、包(Package)概念与用法分析
May 31 Python
Python中bisect的使用方法
Dec 31 Python
python GUI库图形界面开发之PyQt5树形结构控件QTreeWidget详细使用方法与实例
Mar 02 Python
Python3之外部文件调用Django程序操作model等文件实现方式
Apr 07 Python
Python使用eval函数执行动态标表达式过程详解
Oct 17 Python
OpenCV实现机器人对物体进行移动跟随的方法实例
Nov 09 Python
Python中pass的作用与使用教程
Nov 13 Python
在windows下快速搭建web.py开发框架方法
Apr 22 #Python
基于python实现的抓取腾讯视频所有电影的爬虫
Apr 22 #Python
Python开发之快速搭建自动回复微信公众号功能
Apr 22 #Python
Django小白教程之Django用户注册与登录
Apr 22 #Python
python中PIL安装简单教程
Apr 21 #Python
Python for Informatics 第11章之正则表达式(四)
Apr 21 #Python
Python for Informatics 第11章之正则表达式(二)
Apr 21 #Python
You might like
全国FM电台频率大全 - 5 内蒙古自治区
2020/03/11 无线电
遍历指定目录下的所有目录和文件的php代码
2011/11/27 PHP
php随机获取金山词霸每日一句的方法
2015/07/09 PHP
PHP实现单例模式建立数据库连接的方法分析
2020/02/11 PHP
suggestion开发小结以及对键盘事件的总结(针对中文输入法状态)
2011/12/20 Javascript
JavaScript实现简单图片滚动附源码下载
2014/06/17 Javascript
js实现飞入星星特效代码
2014/10/17 Javascript
chrome不支持form.submit的解决方案
2015/04/28 Javascript
jQuery+jsp实现省市县三级联动效果(附源码)
2015/12/03 Javascript
仅9张思维导图帮你轻松学习Javascript 就这么简单
2016/06/01 Javascript
JavaScript生成.xls文件的代码
2016/12/22 Javascript
关于前后端json数据的发送与接收详解
2017/07/30 Javascript
JavaScript实现简单评论功能
2017/08/17 Javascript
基于vue2.0实现简单轮播图
2017/11/27 Javascript
Vue Render函数创建DOM节点代码实例
2020/07/08 Javascript
Python中的匿名函数使用简介
2015/04/27 Python
Windows安装Python、pip、easy_install的方法
2017/03/05 Python
python实现年会抽奖程序
2019/01/22 Python
解决win7操作系统Python3.7.1安装后启动提示缺少.dll文件问题
2019/07/15 Python
安装pyecharts1.8.0版本后导入pyecharts模块绘图时报错: “所有图表类型将在 v1.9.0 版本开始强制使用 ChartItem 进行数据项配置 ”的解决方法
2020/08/18 Python
Python利用Pillow(PIL)库实现验证码图片的全过程
2020/10/04 Python
python学习之使用Matplotlib画实时的动态折线图的示例代码
2021/02/25 Python
Swisse官方海外旗舰店:澳大利亚销量领先,自然健康品牌
2017/12/15 全球购物
数组越界问题
2015/10/21 面试题
关于廉洁的广播稿
2014/01/30 职场文书
工厂总经理岗位职责
2014/02/07 职场文书
模特大赛策划方案
2014/05/28 职场文书
在校实习生求职信
2014/06/18 职场文书
公安纪律作风整顿剖析材料
2014/10/10 职场文书
2014年人大工作总结
2014/12/10 职场文书
初中化学教学反思
2016/02/22 职场文书
Nginx进程管理和重载原理详解
2021/04/22 Servers
Matplotlib绘制混淆矩阵的实现
2021/05/27 Python
SpringBoot整合Redis入门之缓存数据的方法
2021/11/17 Redis
JavaScript高级程序设计之基本引用类型
2021/11/17 Javascript
Win11怎么添加用户?Win11添加用户账户的方法
2022/07/15 数码科技