简单的webpy+mongoDB框架
2017-10-31 本文已影响0人
moodi
1.部署准备,往mongoDB插入一些数据
db.col.insert({name:"bot",body:"my name is bot, love:"girl"})
2.文件目录结构
屏幕快照 2017-10-31 下午5.36.26.png3.创建配置文件config.py,使用pymongo操作mongoDB
#config.py
from pymongo import MongoClient
#连接mongoDB服务
client = MongoClient('localhost',27017)
#连接指定数据库
db = client['test']
#选择指定聚合
collection = db['col']
cache = False
4.创建db.py, 这个文件放些增删改查方法
import config
import pprint
#**k接收一个字典 例如 listing(love='girl') 查询love='girl'所有的数据
def listing(**k):
list = []
li = config.collection.find(k)
for post in li:
print(post)
list.append(post)
return list
5.创建code.py
import web
import view,config
from view import render
#设置路由
urls = (
'/', 'index'
)
class index:
def GET(self):
return render.base(view.listing(love='girl'))#显示love='girl'所有数据
if __name__ == "__main__":
app = web.application(urls, globals())
app.internalerror = web.debugerror
app.run()
6.创建view.py
import web
import db
import config
t_globals = dict(
datestr=web.datestr,
)
render = web.template.render('templates/', cache=config.cache,
globals=t_globals)
render._keywords['globals']['render'] = render
def listing(**k):
llist = db.listing(**k)
return render.listing(llist)
7.模板文件 base.html
$def with (page, title=None)
<html><head>
<title>my site\
$if title: : $title\
</title>
</head><body>
<h1><a href="/"> $title</a></h1>
$:page
</body></html>
8.模板listing.html
$def with (items)
$for item in items:
$:render.item(item)
9.item.html
$def with (item)
<p>$item['name']</p>
<p class="details">$item['body']</p>