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的Twisted框架编写非阻塞程序的代码示例
May 25 Python
python实现聚类算法原理
Feb 12 Python
Python使用pandas处理CSV文件的实例讲解
Jun 22 Python
python实现石头剪刀布程序
Jan 20 Python
Python小进度条显示代码
Mar 05 Python
python requests库爬取豆瓣电视剧数据并保存到本地详解
Aug 10 Python
利用python绘制数据曲线图的实现
Apr 09 Python
Python实现清理微信僵尸粉功能示例【基于itchat模块】
May 29 Python
python代码中怎么换行
Jun 17 Python
Python ckeditor富文本编辑器代码实例解析
Jun 22 Python
python使用nibabel和sitk读取保存nii.gz文件实例
Jul 01 Python
pandas按条件筛选数据的实现
Feb 20 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
解析PHP实现多进程并行执行脚本
2013/06/18 PHP
PHP连接SQLServer2005的方法
2015/01/27 PHP
mysql desc(DESCRIBE)命令实例讲解
2016/09/24 PHP
PHP递归实现文件夹的复制、删除、查看大小操作示例
2017/08/11 PHP
实例讲解php将字符串输出到HTML
2019/01/27 PHP
JavaScript传递变量: 值传递?引用传递?
2011/02/22 Javascript
动态的绑定事件addEventListener方法的使用
2014/01/24 Javascript
2014年最火的Node.JS后端框架推荐
2014/10/27 Javascript
jQuery多级手风琴菜单实例讲解
2015/10/22 Javascript
jQuery实现用户输入自动完成功能
2017/02/13 Javascript
详解nodejs中exports和module.exports的区别
2017/02/17 NodeJs
详解vue-cli + webpack 多页面实例应用
2017/04/25 Javascript
jquery中封装函数传递当前元素的方法示例
2017/05/05 jQuery
原生JavaScript实现精美的淘宝轮播图效果示例【附demo源码下载】
2017/05/27 Javascript
vue内置组件component--通过is属性动态渲染组件操作
2020/07/28 Javascript
Python 代码性能优化技巧分享
2012/08/07 Python
Python fileinput模块使用介绍
2014/11/30 Python
Python 3.x 新特性及10大变化
2015/06/12 Python
Python爬虫抓取手机APP的传输数据
2016/01/22 Python
利用Python进行异常值分析实例代码
2017/12/07 Python
python和opencv实现抠图
2018/07/18 Python
Python 网络编程之TCP客户端/服务端功能示例【基于socket套接字】
2019/10/12 Python
python pygame实现滚动横版射击游戏城市之战
2019/11/25 Python
后端开发使用pycharm的技巧(推荐)
2020/03/27 Python
解决json中ensure_ascii=False的问题
2020/04/03 Python
Python爬虫使用bs4方法实现数据解析
2020/08/25 Python
python用Configobj模块读取配置文件
2020/09/26 Python
Django Auth用户认证组件实现代码
2020/10/13 Python
Chemist Warehouse官方海外旗舰店:澳洲第一连锁大药房
2017/08/25 全球购物
美国知名的隐形眼镜电商:Contacts America
2019/11/19 全球购物
护士个人简历自荐信
2013/10/18 职场文书
办理房产证委托书
2014/09/18 职场文书
美丽心灵观后感
2015/06/01 职场文书
埃及王子观后感
2015/06/16 职场文书
2019开业庆典剪彩仪式主持词!
2019/07/22 职场文书
mysql left join快速转inner join的过程
2021/06/30 MySQL