web.py 十分鐘建立簡易部落格
阿新 • • 發佈:2019-02-09
【原文:http://blog.csdn.net/caleng/article/details/5712850】
【本文章來源於網路,僅作為學習日記之用,版權歸原作者所有,如果侵犯了您的權益,請來信告知,我會盡快處理】
======================================================
一、web.py簡介
web.py是一款輕量級的python web開發框架,簡單、高效、學習成本低,特別適合作為python web開發的入門框架。官方站點:http://webpy.org/
二、web.py安裝
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()
- ifnot 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))
- ifnot 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