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实现简单状态框架的方法
Mar 19 Python
python读取json文件并将数据插入到mongodb的方法
Mar 23 Python
Python中尝试多线程编程的一个简明例子
Apr 07 Python
apache部署python程序出现503错误的解决方法
Jul 24 Python
python中字符串的操作方法大全
Jun 03 Python
Python中的Numpy矩阵操作
Aug 12 Python
python装饰器常见使用方法分析
Jun 26 Python
使用selenium和pyquery爬取京东商品列表过程解析
Aug 15 Python
Python实现某论坛自动签到功能
Aug 20 Python
Python使用__new__()方法为对象分配内存及返回对象的引用示例
Sep 20 Python
Django数据库迁移常见使用方法
Nov 12 Python
Python闭包的定义和使用方法
Apr 11 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 无限级数据JSON格式及JS解析
2010/07/17 PHP
php入门学习知识点六 PHP文件的读写操作代码
2011/07/14 PHP
使用php判断浏览器的类型和语言的函数代码
2013/02/28 PHP
PHP图片处理之图片旋转和图片翻转实例
2014/11/19 PHP
浅析php适配器模式(Adapter)
2014/11/25 PHP
php建立Ftp连接的方法
2015/03/07 PHP
用javascript实现的图片马赛克后显示并切换加文字功能
2007/04/21 Javascript
javascript实现tabs选项卡切换效果(扩展版)
2013/03/19 Javascript
基于jQuery实现图片的前进与后退功能
2013/04/24 Javascript
Egret引擎开发指南之编译项目
2014/09/03 Javascript
js中javascript:void(0) 真正含义
2020/11/05 Javascript
深入php面向对象、模式与实践
2016/02/16 Javascript
使用jquery提交form表单并自定义action的实现代码
2016/05/25 Javascript
jQuery实现的超链接提示效果示例【附demo源码下载】
2016/09/09 Javascript
浅谈Angular中ngModel的$render
2016/10/24 Javascript
分享bootstrap学习笔记心得(组件及其属性)
2017/01/11 Javascript
微信小程序 本地存储及登录页面处理实例详解
2017/01/11 Javascript
mui上拉加载功能实例详解
2017/04/13 Javascript
详解vue.js的devtools安装
2017/05/26 Javascript
微信小程序 密码输入(源码下载)
2017/06/27 Javascript
Vue组件模板形式实现对象数组数据循环为树形结构(实例代码)
2017/07/31 Javascript
jQuery封装animate.css的实例
2018/01/04 jQuery
微信打开网址添加在浏览器中打开提示的办法
2019/05/20 Javascript
解决layui表格的表头不滚动的问题
2019/09/04 Javascript
[01:04:22]2018DOTA2亚洲邀请赛 3.31 小组赛 B组 IG vs EG
2018/04/01 DOTA
[42:34]VP vs VG 2018国际邀请赛小组赛BO2 第一场 8.19
2018/08/21 DOTA
Python使用cx_Oracle模块将oracle中数据导出到csv文件的方法
2015/05/16 Python
python画环形图的方法
2020/03/25 Python
在pycharm中关掉ipython console/PyDev操作
2020/06/09 Python
python用Tkinter做自己的中文代码编辑器
2020/09/07 Python
马来西亚网上购物:Youbeli
2018/03/30 全球购物
沙特阿拉伯电子产品和家用电器购物网站:Black Box
2019/07/24 全球购物
沙特阿拉伯排名第一的在线时尚购物应用程序:1Zillion
2020/08/08 全球购物
自主招生自荐信
2013/12/08 职场文书
校园新闻广播稿5篇
2014/10/10 职场文书
Python各协议下socket黏包问题原理
2022/04/12 Python