# -*- encoding: utf-8 -*- from flask import Flask,request,jsonify,render_template #导入pymongo来连接mongodb
from pymongo import MongoClient app = Flask(__name__) app.config.from_pyfile('config.ini') #建立数据库连接对象
conn = MongoClient('localhost',27017) #指定数据库
db = conn.p2p #注册逻辑
@app.route('/reg/<username>/<password>',methods=['GET','POST'])
def reg(username,password):
#查询数据库,判断该用户名是否以及存在,find_one查询第一条
res = db.user.find_one({'username':username})
if res is None:
#指定集合入库
db.user.insert({'username':username,'password':password})
return jsonify({'result':1})
else:
return jsonify({'result':0}) @app.route('/yqdp_json')
def uqdp_json():
#先第一sql语句,这条sql为分组计数查询
group = {'$group':{'_id':'$source','count':{"$sum":1}}}
#执行sql语句,用聚合函数(aggregate)运行sql语句要用[]把sql包含
result = db.news.aggregate([group])
#强转list
result = list(result)
#遍历list
for val in result:
#将数据输出
val['_id']
val['count']
return jsonify({'name':_dname,'data':_data}) @app.route('/info/<tabelname>/<id>')
def infodetail(tabelname,id):
#查询单条内容,当集合名为动态时可以用这个方法来动态给值
res = db[tabelname].find_one({'_id':id})return res if __name__ == "__main__":
app.run()