flask mongoengine的使用(一)查询


from flask_mongoengine import MongoEngine

db = MongoEngine()



class ConfigureEnvModel(db.Document):
    id = db.StringField(required=True, max_length=50, unique=True, primary_key=True)
    name = db.StringField(required=False, max_length=50)

    meta = {
            "collection": "configure_env",
            "index": [{
                'fields': ['id'],
                'unique': True,
                }]
            }

class ConfigureDisconfModel(db.Document):
    id = db.StringField(required=True, max_length=50, unique=True, primary_key=True)
    env = db.StringField(required=False, max_length=50)
    name = db.StringField(required=False, max_length=50)
    username = db.StringField(required=False, max_length=50)
    password = db.StringField(required=False, max_length=50)
    url = db.StringField(required=False, max_length=50)

    meta = {
            "collection": "configure_disconf",
            "index": [{
                'fields': ['id'],
                'unique': True,
                }]
            }


class ConfigureNginxModel(db.Document):
    id = db.StringField(required=True, max_length=50, unique=True, primary_key=True)
    env = db.StringField(required=False, max_length=50)
    name = db.StringField(required=False, max_length=50)
    url = db.StringField(required=False, max_length=50)

    meta = {
            "collection": "configure_nginx",
            "index": [{
                'fields': ['id'],
                'unique': True,
                }]
            }





import logging

from flask_restful import reqparse, Api, Resource, fields

from uop.configure import configure_blueprint
from uop.models import ConfigureEnvModel 
from uop.models import ConfigureNginxModel 
from uop.models import ConfigureDisconfModel 

configure_api = Api(configure_blueprint)


class ConfigureEnv(Resource):

    @classmethod
    def get(cls):
        # NOTE: 所有结果查询
        ret = ConfigureEnvModel.objects.all()
        #ret = ConfigureEnvModel.objects()
        envs = []
        for env in ret: 
            envs.append(dict(id=env.id, 
                             name=env.name))
        res = {
                'code': 200,
                'result': {
                    'res': envs,
                    'msg': u'请求成功'
                    }
                }
        return res

class Configure(Resource):

    @classmethod
    def get(cls):
        parser = reqparse.RequestParser()
        parser.add_argument('env', type=str)
        parser.add_argument('category', type=str)
        args = parser.parse_args()
        category = parser.parse_args()
        env = args.env if args.env else 'dev'
        category = args.category if args.category else 'nginx'
        logging.info("[UOP] Get configs, env:%s, category: %s", env, category)
        envs = []
        if category == 'nginx':
            # NOTE: 条件查询 下面2条语句效果等价
            ret = ConfigureNginxModel.objects.filter(env=env)
            # ret = ConfigureNginxModel.objects(env=env)
            for env in ret: 
                envs.append(dict(id=env.id, 
                                 name=env.name,
                                 url=env.url))
        else: # disconf
            ret = ConfigureDisconfModel.objects.filter(env=env)
            for env in ret: 
                envs.append(dict(id=env.id, 
                                 name=env.name,
                                 username=env.username,
                                 password=env.password,
                                 url=env.url))
        res = {
                'code': 200,
                'result': {
                    'res': envs,
                    'msg': u'请求成功'
                    }
                }
        return res

    @classmethod
    def post(cls):
        parser = reqparse.RequestParser()
        parser.add_argument('env', type=str)
        parser.add_argument('category', type=str)
        parser.add_argument('url', type=str)
        parser.add_argument('name', type=str)
        parser.add_argument('username', type=str)
        parser.add_argument('password', type=str)
        args = parser.parse_args()
        env = args.env if args.env else 'dev'
        url = args.url if args.url else 'dev'
        name = args.name if args.name else ''
        username = args.username if args.username else 'dev'
        password = args.password if args.password else 'dev'
        category = args.category if args.category else 'nginx'
        logging.info("[UOP] Create configs, env:%s, category: %s", env, category)
        import uuid
        id = str(uuid.uuid1())
        if category == 'nginx':
            # NOTE: 建立一个document
            ret = ConfigureNginxModel(env=env,
                                     url=url,
                                     name=name,
                                     id=id).save()
        else:
            ret = ConfigureDisconfModel(env=env,
                                     url=url,
                                     name=name,
                                     username=username,
                                     password=password,
                                     id=id).save()
        res = {
                'code': 200,
                'result': {
                    'res': id,
                    'msg': u'请求成功'
                    }
                }
        return res

    @classmethod
    def put(cls):
        parser = reqparse.RequestParser()
        parser.add_argument('env', type=str)
        parser.add_argument('category', type=str)
        parser.add_argument('url', type=str)
        parser.add_argument('name', type=str)
        parser.add_argument('username', type=str)
        parser.add_argument('password', type=str)
        parser.add_argument('id', type=str)
        args = parser.parse_args()
        category = parser.parse_args()
        env = args.env if args.env else 'dev'
        id = args.id if args.id else ''
        url = args.url if args.url else ''
        name = args.name if args.name else ''
        category = args.category if args.category else 'nginx'
        username = args.username if args.username else ''
        password = args.password if args.password else ''
        logging.info("[UOP] Modify configs, env:%s, category: %s", env, category)

        if category == 'nginx':
            ret = ConfigureNginxModel.objects(id=id)
            #NOTE: ret = ConfigureNginxModel.objects.filter(id=id)
            ret.update(name=name,url=url)
        else:
            ret = ConfigureDisconfModel.objects(id=id)
            ret.update(name=name,url=url,username=username,password=password)

        res = {
                'code': 200,
                'result': {
                    'msg': u'请求成功'
                    }
                }
        return res

    @classmethod
    def delete(cls):
        parser = reqparse.RequestParser()
        parser.add_argument('env', type=str)
        parser.add_argument('category', type=str)
        parser.add_argument('id', type=str)
        args = parser.parse_args()
        category = parser.parse_args()
        env = args.env if args.env else 'dev'
        category = args.category if args.category else 'nginx'
        id = args.id if args.id else -1 
        logging.info("[UOP] Delete configs, env:%s, category: %s, id: %s", env, category, id)


        if category == 'nginx':
            # NOTE:  查询一个document
            # ConfigureNginxModel.objects.filter(id=id).delete() 等价于 ConfigureNginxModel.objects.delete()
            ret = ConfigureNginxModel.objects.filter(id=id)
        else:
            ret = ConfigureDisconfModel.objects.filter(id=id)
        if len(ret):
            ret.delete()
        else:
            logging.info("[UOP] Do not found the item, id:%s", id)

        res = {
                'code': 200,
                'result': {
                    'msg': u'请求成功'
                    }
                }
        return res


configure_api.add_resource(ConfigureEnv, '/env')
configure_api.add_resource(Configure, '/')


扩展阅读

flask-mongoengire 的文档比较缺乏,这里主要看mongoengine 的文档。

https://pypi.python.org/pypi/flask-mongoengine

2.5. Querying the database
http://docs.mongoengine.org/guide/querying.html?highlight=modify
简介:

查询:
The query may be filtered by calling the [QuerySet
](http://docs.mongoengine.org/apireference.html#mongoengine.queryset.QuerySet) object with field lookup keyword arguments. The keys in the keyword arguments correspond to fields on the [Document
](http://docs.mongoengine.org/apireference.html#mongoengine.Document) you are querying:
# This will return a QuerySet that will only iterate over users whose# 'country' field is set to 'uk'uk_users = User.objects(country='uk')

2.3. Defining documents
https://mongoengine-odm.readthedocs.io/guide/defining-documents.html#defining-a-document-s-schema

简介:

mongo engine 的文档。 



如何定义一个schema.


MongoEngine allows you to define schemata for documents as this helps to reduce coding errors, and allows for utility methods to be defined on fields which may be present.

To define a schema for a document, create a class that inherits from Document. Fields are specified by adding field objects as class attributes to the document class:



from mongoengine import *
import datetime

class Page(Document):
    title = StringField(max_length=200, required=True)
    date_modified = DateTimeField(default=datetime.datetime.now)






 Document collections

Document classes that inherit directly from Document will have their own collection in the database. The name of the collection is by default the name of the class, converted to lowercase (so in the example above, the collection would be called page). If you need to change the name of the collection (e.g. to use MongoEngine with an existing database), then create a class dictionary attribute called meta on your document, and set collection to the name of the collection that you want your document class to use:

class Page(Document):
    title = StringField(max_length=200, required=True)
    meta = {'collection': 'cmsPage'}





查询:

MongoEngine 也提供用原生的mongo语句来查询。 

Raw queries

It is possible to provide a raw PyMongo query as a query parameter, which will be integrated directly into the query. This is done using the __raw__ keyword argument:

Page.objects(__raw__={'tags': 'coding'})



修改:

However, this doesn’t map well to the syntax so you can also use a capital S instead

Post.objects(comments__by="joe").update(inc__comments__S__votes=1)


你可能感兴趣的:(flask mongoengine的使用(一)查询)