简体   繁体   English

如何在 Flask 中使用 MongoDB?

[英]How can I use MongoDB with Flask?

好的,所以我已经安装了 Flask,我想知道如何将 MongoDB 数据库与我即将开始构建的 Flask 应用程序连接和使用。

You can use any of these three libraries 您可以使用这三个库中的任何一个

I personally use flask mongoengine and every things work fine 我个人使用烧瓶mongoengine,每件事情都很好

I personally find the PyMongo library simple and easy to use. 我个人觉得PyMongo库简单易用。

You first need to import MongoClient and create a connection: 首先需要导入MongoClient并创建连接:

from pymongo import MongoClient
client = MongoClient()

Then get your db instance and collection (table): 然后获取您的数据库实例和集合(表):

db = client.my_database
collection = db.my_collection

You can then manipulate your data by working with JSON documents that hold your data. 然后,您可以通过使用保存数据的JSON文档来处理数据。 There is a complete example on their website. 他们的网站上有一个完整的例子。

Take a look at this tutorial on how to use PyMongo. 看一下教程,了解如何使用PyMongo。

Maybe you don't have to use special libraries for Flask to connect to MongoDB. 也许您不必使用Flask的特殊库来连接MongoDB。

Just treat Flask application as a normal Python program, and connect to MongoDB via normal Python libraries like PyMongo . 只需将Flask应用程序视为普通的Python程序,并通过普通的Python库(如PyMongo)连接到MongoDB。

Here 's an example by someone else. 以下是其他人的例子。 A Flask app connecting to MongoDB via PyMongo. 通过PyMongo连接到MongoDB的Flask应用程序。

Here is the simple example of MongoDB with Flask 以下是使用Flask的MongoDB的简单示例

  import pymongo
  import json
  client = pymongo.MongoClient("localhost", 27017)
  collection_USER = client[simple]
  Define_Collection_for_USER_FILE = collection_USER['USER']
  Define_Collection_for_USER_FILE.remove({})
  Define_Collection_for_USER_FILE.insert(json.loads(filename))

There are multiple ways of using MongoDB with Flask - Flask_pymongo & flask_mongoengine are two python modules that can be used to for easy integration with mongoDB.在 Flask 中使用 MongoDB 有多种方式 - Flask_pymongo 和 flask_mongoengine 是两个 Python 模块,可用于轻松与 mongoDB 集成。 both uses pymongo as the base libraries so the methods nd class available pymongo can be easily inherited while using any of the module (flask_pymongo and flask_mongoengine).两者都使用 pymongo 作为基础库,因此在使用任何模块(flask_pymongo 和 flask_mongoengine)时,可以轻松继承 pymongo 可用的方法和类。 I Found Using mongoengine Creating the Models are easier.我发现使用 mongoengine 创建模型更容易。 I am providing the solution using flask_mongoengine.我正在使用flask_mongoengine 提供解决方案。

using python 3.6 + and flask 1.1.1 + ( Tested with Python 3.7+ also )使用 python 3.6 + 和 flask 1.1.1 + (也用 Python 3.7+ 测试)

Using flask_mongoengine使用flask_mongoengine

configuration-file.cfg配置文件.cfg

MONGODB_SETTINGS = {
    'DB': 'Your_DB_Name',
    'host': 'localhost',
    'port': 27017,
}

App.py file应用程序.py文件

app.config['SECRET_KEY'] = SECRET_KEY
db = MongoEngine()

app.config.from_pyfile('settings.cfg')

with app.app_context():
   db.init_app(app)
   try:
       db_client = db.connection['flask_webapp_db']
   except ConnectionFailure as e:
       sys.stderr.write("Could not connect to MongoDB: %s" % e)
       sys.exit(1)

........
@app.route('/')
def signup():
signup_form = get_signup_form(User)
if signup_form.validate_on_submit():
    try:
        user = db_client.User
        user.save(signup_form.data)
        print('user registered')
        return redirect('/')
    except WriteError as WE:
        print(WE)
return render_template('signup.html', form=signup_form)

create you User model in models file which should look like as below - this file is something which defines your tables ( known as Document in Mongodb )在模型文件中创建你的用户模型,它应该如下所示 - 这个文件是定义你的表的东西(在 Mongodb 中称为 Document

models.py模型.py

from mongoengine.document import Document
from mongoengine.fields import DateTimeField, StringField, EmailField


class User(Document):
    username = StringField(min_length=4, required=True, unique=True)
    password = StringField(min_length=8, required=True)

    meta = {'db_alias': 'flask_webapp_db'}    # your db name where you want to create the table(Dcoument) User is your Document(Table) name
    def save(self, force_insert=False, validate=True, clean=True,
         write_concern=None, cascade=None, cascade_kwargs=None,
         _refs=None, save_condition=None, signal_kwargs=None, **kwargs):
        pass

I'm using Flask-Pymongo: 我正在使用Flask-Pymongo:

from pymongo import MongoClient

app = Flask(__name__)


app.config['MONGO_DBNAME'] = 'reports' # name of database on mongo
app.config["MONGO_URI"] = "mongodb://127.0.0.1:27017/reports"
mongo = PyMongo(app)

It's working! 它的工作原理!

There are a few steps that you have to follow. 您必须遵循几个步骤。 Since flask is a lighter framework you will need to install different packages to use according to your need. 由于烧瓶是较轻的框架,您需要根据需要安装不同的包装。

So, since you will use Mongodb to work in your project you will have to install Pymongo . 因此,由于您将使用Mongodb在您的项目中工作,您将必须安装Pymongo

pip install Pymongo

After that, you will need to set up your DB in MongoDB: 之后,您需要在MongoDB中设置数据库:

  • So, in Mongodb create a database and then after your database is created within it create a collection or just add it from your function. 因此,在Mongodb中创建一个数据库,然后在其中创建数据库后创建一个集合或只是从您的函数中添加它。

Database name: MyDaTaBaSe . 数据库名称: MyDaTaBaSe

After it is done setup your work environment: 完成后,设置您的工作环境:

import os
from flask import Flask, render_template, redirect, request, url_for, session
from flask_pymongo import PyMongo #<<< THIS IS THE GUY YOU WILL NEED TO CONNECT WITH Mongodb



app = Flask(__name__)

#App configuration -- table name and the link
app.secret_key = 'any random string'
app.config['MONG_DBNAME'] = 'MyDaTaBaSe'
app.config['MONGO_URI'] = 'mongodb+srv://<YOUR_USERNAME_HERE>:<YOUR_PASSWORD_HERE>@myfirstcluster-uyvei.mongodb.net/MyDaTaBaSe?retryWrites=true'


mongo = PyMongo(app)

@app.route(/)
def index():
    return render_template('index.hml')

Therefore, the main guys are the app.config['MONG_DBNAME'] = 'MyDaTaBaSe' that you will need to tell which database you want to use and the app.config['MONGO_URI'] that you will need to set up your connection and link in which you will need to place your username and your password as well as the name of the database at the end. 因此,主要人员是app.config['MONG_DBNAME'] = 'MyDaTaBaSe' ,您需要告诉您要使用哪个数据库以及设置连接所需的app.config['MONGO_URI']和链接,您需要在其中放置您的用户名和密码以及数据库的名称。

So, this is the basics to connect with Mongodb. 所以,这是与Mongodb连接的基础知识。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM