web.py

    xiaoxiao2023-09-29  150

    之前一直做PHP开发,习惯了MVC模式,初学Python不久,在网上找web.py教程也不是很多,自己摸索写个MVC。因为一直自学的Python,可能不太符合Python写法,望指正下。

     目录结构

     

    http://127.0.0.1/home/blog/blog/list

    #!/usr/bin/env python3 #-*- coding: utf-8 -*- import web web.config.debug = True urls = ( "/?(.*)", "url" ) class url: def GET(self, path): PATH_INFO = web.ctx.env.get("REDIRECT_PATH_INFO") if web.ctx.env.get("REDIRECT_PATH_INFO") else web.ctx.env.get("PATH_INFO") url = PATH_INFO.strip("/").split("/") m = __import__("Application." + url[0] + "." + url[1], fromlist=True) c = getattr(m, url[2] if len(url)==4 else url[1]) a = getattr(c(), url[3] if len(url)==4 else url[2]) web.header('Content-Type', 'text/html; charset=utf-8') return a(web.input()) def POST(self, path): #return web.data() web.header('Content-Type', 'text/html; charset=utf-8') return self.GET(path) if __name__ == "__main__": def _notfound(msg="对不起文件不存在"): web.header('Content-Type', 'text/html; charset=utf-8') return web.notfound(msg) app = web.application(urls, globals()) app.notfound = _notfound app.run()

    /Application/home/blog.py

    #!/usr/bin/env python3 #-*- coding: utf-8 -*- import web import math class blog: db = web.database(dbn='mysql', host='127.0.0.1', db='test', user='root', pw='password', buffered=True) render = web.template.render("templates") def list(self, _REQUEST): page = 1 if "page" not in _REQUEST else int(_REQUEST["page"]) count = self.db.select('do_admin', what="count(admin_id) as total").list() pages = web.utils.storage(total=count[0]["total"], current=page, page=math.ceil(count[0]["total"]/10)) lists = self.db.select('do_admin', limit=10, offset=(page-1)*10).list() laypage = self.render.lay_page(pages) return self.render.blog_list(laypage, lists) def see(self, _REQUEST): #print('这是app_blog') return web.ctx.env.get("REDIRECT_PATH_INFO") def edit(self, _REQUEST): if web.ctx.env.get("REQUEST_METHOD")=="GET": info = self.db.select('do_admin', where="admin_id="+_REQUEST["id"]).list() if len(info)==0: raise web.notfound('未找到数据') return self.render.blog_edit(info[0]) if web.ctx.env.get("REQUEST_METHOD")=="POST": re = self.db.update('do_admin', where="admin_id="+_REQUEST["admin_id"], phone=_REQUEST["phone"], realname=_REQUEST["realname"]) #return re raise web.seeother('/home/blog/blog/list')

     

    最新回复(0)