• flask操作mongo两种方式--常规


    #manage.py
    #coding=utf-8
    #Flask-Script是一个可以在flask应用外部编写脚本的扩展
    #常用功能:
    #运行一个开发的服务器
    #python shell中操作数据库看
    #命令行任务
    #from flask_script import Manager
    #执行语句 python manage.py save
    
    from flask_script import Manager
    from app import app, db
    from models import Users
    
    manager = Manager(app)
    
    @manager.command
    def hello():
        print "hello world"
    
    @manager.command
    def save():
        user = Users("dadao", "dadao@123.com")
        user.save()
    
    
    @manager.command
    def query_users():
        users = Users.query_users()
        for u in users:
            print u
    
    
    if __name__ == "__main__":
        manager.run()
    
    
    
    #models.py
    #coding=-utf-8
    
    import pymongo
    
    def get_conn():
        client = pymongo.MongoClient("127.0.0.1", 27017)
        db = client.users
        users = db.users
        return users
    
    class Users(object):
        
        def __init__(self, name, email):
            self.name = name
            self.email = email
            
        def save(self):
            user = {"name": self.name, "email":self.email}
            conn = get_conn()
            id = conn.insert(user)
            print id
        
        @staticmethod
        def query_users():
            conn = get_conn()
            users = conn.find()
            return users
      
    
    #app.py
    #coding=utf-8
    
    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route("/")
    def main():
        return "hello world"
    
    if __name__ == "__main__":
        app.run(debug=True)
  • 相关阅读:
    BZOJ1954 Pku3764 The xor-longest Path
    BZOJ3697 采药人的路径
    BZOJ1468 Tree
    BZOJ2326 [HNOI2011]数学作业
    BZOJ2809 [Apio2012]dispatching
    BZOJ1334 [Baltic2008]Elect
    BZOJ2882 工艺
    BZOJ3791 作业
    BZOJ1224 [HNOI2002]彩票
    [noip2013]花匠
  • 原文地址:https://www.cnblogs.com/themost/p/8939626.html
Copyright © 2020-2023  润新知