marshmallow-mongoengine icon indicating copy to clipboard operation
marshmallow-mongoengine copied to clipboard

Flask-Restful integration with pymongo

Open mpgalaxy opened this issue 5 years ago • 3 comments

Hi, how can I integrate marshmallow-monoengine in my flask-restful REST Api using pymongo (MongoClient) with auth-db as database connection ? How do I load data in this scenario ? Could you provide me with an example, please ? I followed your tutorial, but when it comes to actual mondoDB connections there seems to be no documentation on it.

mpgalaxy avatar Mar 07 '19 14:03 mpgalaxy

你可以试试用MonggoEngine, 它提供ORM的操作语句,使数据库查询更加方便。 工厂模式下这样连接 init.py

from flask_mongoengine import MongoEngine
db = MongoEngine()

app.py

def create_app(config_name):
    app = Flask(config_name)
    app.config.from_object(config[config_name])
    db.register_connection(
        db='your db',
        alias="name",
        port=PORT,
        username=NAME,
        password=PWD
    )

ZHAISHENKING avatar Mar 07 '19 15:03 ZHAISHENKING

@ZHAISHENKING : Would this also be possible with a custom class element ? For every request to my endpoints I create a db-connection object, which I delete afterwards when the request is finished, thus no connections (even if something breaks communication) stay open, no memory leaks... :) This is my class:

class DBConnection():
   def __init__(self):
       self.mongo_url = 'mongodb://localhost:27017/admin'
       self.client = MongoClient(self.mongo_url,
                                 username= 'admin',
                                 password= 'secretpw')
       self.client.db = self.client.get_database("testdb")
       self.collection = self.client.db["test"] 
...

In my GET routine I do a

db_connection = DBConnection()
for item in db_connection.collection.find(filter).sort("name"):
                ...
db_connection.clean()
del db_connection
return data 

mpgalaxy avatar Mar 08 '19 07:03 mpgalaxy

抱歉,没有这么使用过。 这个连接方法与MongoEngine没有关系,更像是pymongo的连接方法

ZHAISHENKING avatar Mar 08 '19 10:03 ZHAISHENKING