Python Web 7--python Call MongoDB optimization, using Mongoengine

Source: Internet
Author: User
Tags mongodb

Preface:

In the previous article we elaborated on how to use Pymongo in Python to manipulate the MongoDB database, but directly to the database operation code written in the script, it is obvious that the application of the code coupling is too strong, and not conducive to the optimization of code management, General applications are designed using the MVC framework, and in order to better maintain the MVC structure, we need to extract the database Operations section as model, which requires the help of Mongoengine, an object-document mapper that can manipulate MongoDB databases (ODM, Object Document Mapper).


First, install Mongoengine:

The installation process is actually very simple, using the PIP plug-in to install, using the instructions in the Doc window to install:

Pip Install Mongoengine
Because the web framework we choose is flask, we need to install the mongoengine that is applicable to flask, Flask_mongoengine, with the following instructions:

Pip Install Flask_mongoengine


second, the use of operations:

1. Introduction of:

Introduce the content of the flask_mongoengine at the same time, the DateTime also introduced together, so that the time to save the data can also be stored in the timestamp:

From flask_mongoengine Import * from
datetime import datetime

2. Connecting to the database:

The connection database is divided into two types:

Connect Local Database: For example, the name of the local database is LocalDB, you can use: Connect (' LocalDB ')

Database on the machine that connects the specified IP: Connect (' LocalDB ', host= ' IP address ', username= ' database username ', passworld= ' password ')

3. Declare the data storage structure:

Declaring a class that inherits from Mongoengine.document, declaring some attributes in a class, is equivalent to creating a data structure to hold data, that is, data that is stored in a database in a form similar to a data structure, typically storing such classes in a script as the Model module for the application, such as creating a mode ls.py script:

From flask import Flask
Import datetime
flask_mongoengine import mongoengine

app = Flask (__name__)   #创建一个Flask应用
db = Mongoengine (APP)   #实例化数据库

class Post (db. Document):
    author = db. Stringfield (max_length=50)
    title = db. Stringfield (max_length=120, required=true)
    tags = db. ListField (db. Stringfield (max_length=30)) Time
    = db. Datetimefield (Default=datetime.datetime.now ())
    content = db. Stringfield ()
This declares a class that inherits from the document class and has five properties, in which you can actually introduce the required parameter when declaring each property, and when Required=true indicates that the object that created the class must be assigned a value.


4. Save data:

According to the code above, when you create an object using the Post class, you have to at least assign an initial value to the Title property, as follows, we implement inserting the data into the database:

From models import Post #引入Post类

post = post (title= "test") #创建Post对象
post.author = "LSH"         #对象属性赋值
Post.save ()                     #将数据存入数据库中
In addition to storing data in a database, sometimes we also need to query the data in the database or modify the data in the database, that is, query and update operations, in the mongoengine of this two operation implementation mode:
query:Posts = Post.objects.all () #返回所有的文档对象列表

Posts = post.objects (title= "test") #返回符合查询条件的对象列表

Update:post.title= "Test1" #修改对象属性

Post.update () #更新

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.