jianpeng.diao 发布的文章

flask与mongodb连接


这里使用的python:3.7,工具pycharm:File-settings-project-Interpreter可以进行导包
mongodb安装:https://www.cnblogs.com/tonylaoshi/p/11052427.html
manage.py

import json

from flask import Flask, request
from flask_cors import CORS
#flask_cor解决跨域
from flask_script import Manager
from app import app
from models import User

manager = Manager(app)
CORS(app, supports_credentials=True)

@app.route('/savedata', methods=['GET', 'POST'])
@manager.command
def save():
    datas = request.get_data()
    print(datas)
    user = User('diaodiao',datas)
    user.save()
    return datas

@app.route('/getdata', methods=['GET', 'POST'])
@manager.command
def query_users():
    users = User.query_users()
    # str(users['ObjectId'])
    list = []
    for user in users:
        del user['_id']
        print(user)
        list.append(user)
        # json.dumps(user)
    print(list)
    jsondata = json.dumps(list)
    return jsondata

@app.route('/delete', methods=['GET', 'POST'])
@manager.command
def delete():
    datas = request.get_data()
    print(datas)
    print("------")
    # print(datas['name'])
    name = "DiaoDiao"
    users = User.delete(name)
    if name:
        # return "Remove " + datas.name["name"] + " Ok!"
        return "Remove " + ["name"] + " Ok!"
    else:
        return "用户不存在,请核对后再操作!"

@app.route('/update', methods=['GET', 'POST'])
@manager.command
def update():
    datas = request.get_data()
    print(datas)
    print("------")
    # print(datas['name'])
    name = "DiaoDiao"
    email = "562957147@qq.com"
    users = User.update(name,email)
    if name:
        return "update " + name + " Ok!"
    else:
        return "用户不存在,请核对后再操作!"

if __name__=='__main__':
    # app.run()
    manager.run(debug=True)

manage.py

import pymongo

def get_coll():
    client = pymongo.MongoClient('localhost', 27017)
    db = client.jikexueyuan
    user = db.user_collection
   return user

class User(object):
    def __init__(self, name, datas):
        self.name = name
        self.datas = datas

def save(self):
    user = {"name": self.name, "email": self.datas}
    coll = get_coll()
    id = coll.insert(user)
    print(id)

@staticmethod
def query_users():
    users = get_coll().find()
    return users

@staticmethod
def delete(name):
    users = get_coll().find({"name": name})
    print(name)
    print(users)
    coll = get_coll()
    coll.remove({"name": name})
    return name

@staticmethod
def update(name,email):
    users = get_coll().find({"name": name})
    print(name)
    print(users)
    coll = get_coll()
    coll.find({"name": name})
    coll.update({"name":name},{"$set":{"email":email}})
    return name

作者:jianpeng.diao
版权声明:本文为博主原创文章,转载请附上博文链接!