前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Flask+MongoDB

Flask+MongoDB

作者头像
我被狗咬了
发布2019-09-23 10:40:20
7020
发布2019-09-23 10:40:20
举报
文章被收录于专栏:Python乱炖Python乱炖

About MongoDB

MongoDB is Object-Oriented, simple, dynamic and scalable NoSQL database. It is based on the NoSQL document store model, in which data objects are stored as separate documents inside a collection instead of storing the data into columns and rows of a traditional relational database.

Setting Up

For this tutorial we will need to setup MongoDB locally on your machine. Click here to find an installation for your OS.

Familarity with Flask is helpful, but not essential.

Layout

  • MongoDB Installation
  • MongoDB Basics
  • Using MongoDB with Python3
  • Using MongoDB with Flask

Basics

Features

  • Persistent storage
  • Documents stored in BSON (binary JSON)
    • Mongo essentially uses JSON
  • JSON objects can be stored directly into a Mongo Database
  • Libraries with many popular languages (Python, Go, Javascript, etc.)

Concepts

Term

Meaning

document

database record, BSON object

Collections

A Collection of documents or BSON objects

Queries

Look up Cursors

Cursors

Basically an index of a collection (Makes MongoDB really fast since it doesn't load the entire collection)

Using MongoDB with Python

There are many libraries for working with MongoDB in python. For our use, we will use pymongo.

Accessing a database
代码语言:javascript
复制
from pymongo import MongoClient
try:
    print("Connecting to Database...")
client = MongoClient()
db = client.HackBU    
    print("Connected to db :)") 
except:
    print("Could not connect to db :(")

If you installed MongoDB properly and have a Mongo server running, this should print out Connected to db :).

Accessing a collection
代码语言:javascript
复制
try:
users = db.users
    print("Connected to collection :)")
except:
    print("Could not connect to collection :(")
Finding a document
代码语言:javascript
复制
username = input("What is your username? Enter: ")user = users.find_one({'username' : username})
if user is not None:
    print("Hello " + str(user['name']) + "!")
else:
    print("Could not find " + username + ".")
Inserting a document
代码语言:javascript
复制
username = input("Username: ")
name = input("Name: ")new_user = {'username' : username, 'name' : name}user = users.find_one({'username' : username})
if user is not None:
    print("User already exists!")    
    return
 try:
users.insert_one(new_user).inserted_id
    print("Account created.")
 except:
    print("Could not insert user.")
Deleting a document
代码语言:javascript
复制
username = input("What is your username? Enter: ")user = users.find_one({'username' : username})if user is None:    print("User does not exist")else:
users.delete_one(user)
user = users.find_one({'username' : username})    if user is None:        print("User deleted.")    else:        print("Could not delete user.")
Deleting a collection
代码语言:javascript
复制
try:
users.drop()
    print("cleared users collection.")
except:
    print("Could not clear users collection.")
Iterating a collection
代码语言:javascript
复制
try:
cursor = users.find({})
    for doc in cursor:
        print(doc)
except:
    print("Could not show users collection.")

Using MongoDB with Flask

Now we can take our previous code and use it with a flask app!

First import some libraries and create our Flask app

代码语言:javascript
复制
from flask import Flask
from flask import render_template
from flask import request
from pymongo import MongoClientapp = Flask(__name__)

Then setup our database:

代码语言:javascript
复制
try:    print("Connecting to Database...")
client = MongoClient()
db = client.HackBU
    print("Connected to db :)")
except:
    print("Could not connect to db :(")users = db.users

Next let's create our index route

代码语言:javascript
复制
@app.route("/")def index():
    return render_template('index.html')

With index.html containing

代码语言:javascript
复制
<!doctype html>
Create account:<br>
<form action="/create">
User Name:<br><input type="text" name="username">
<br>
Name:<br><input type="text" name="name">
<br>
<button>Create</button>
</form><br><br>Login account:
<br>
<form action="/login">
User Name:<br><input type="text" name="username">
<br>
<button>Login</button>
</form>

Next we can create our login route and create route

代码语言:javascript
复制
@app.route('/login', methods=['GET'])def login():
username = request.args.get('username', '')
user = users.find_one({'username' : username})
    if user is None:
            return render_template('error.html', error="User does not exist.")    print("User: " + str(user))    return render_template('login.html', user=user)@app.route('/create', methods=['GET'])def create():
username = request.args.get('username', '')
name = request.args.get('name', '')
new_user = {  'username' : username, 'name' : name}
user = users.find_one({'username' : username})    
    if user is not None:
            return render_template('error.html', error="User already exists!")    try:
users.insert_one(new_user)        print("Account created.")        return render_template('login.html', user=new_user)    except:        return render_template('error.html', error="Could not insert user.")

Inside of login and create routes we use login.html and error.html

代码语言:javascript
复制
<!--login.html--><!doctype html>
{% if user %}
<h1>Hello {{ user.name }}!</h1>
{% else %}
<h1>User does not exist.</h1>
{% endif %}
代码语言:javascript
复制
<!--error.html--><!doctype html>
{% if error %}
<h1>Error: {{ error }}</h1>
{% else %}
<h1>404.</h1>
{% endif %}

The directory layout of our files is

代码语言:javascript
复制
/app.py
/templates
/index.html
/login.html
/error.html

And then to run FLASK_APP=app.py flask run from the project directory.

And that's it! We now have a working flask app that can be used to create and login to accounts. Using Flask you can also setup sessions to keep a user logged in, along with some hashing libraries such as bcrypt to safely store users passwords.

Conclusion

MongoDB is a very powerful document database that may be used with a variety of languages. Python is one such language, and as shown above it is very easy to get a simple app up and running. By using Flask with pymongo, one can setup a simple app to create accounts and login.

CODE:

app.py

代码语言:javascript
复制
from flask import Flask
from flask import render_template
from flask import request
from pymongo import MongoClient

app = Flask(__name__)
# app.run(port=5000)

try:
    print("Connecting to Database...")
    client = MongoClient()
    db = client.YUQing
    print("Connected to db :)")
except:
    print("Could not connect to db :(")

users = db.users

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

@app.route('/create', methods=['GET'])
def create():
    username = request.args.get('username', '')
    name = request.args.get('name', '')
    new_user = {
        'username' : username,
        'name' : name
    }
    user = users.find_one({'username' : username})

    if user is not None:
        return render_template('error.html', error="User already exists!")

    try:    
        users.insert_one(new_user)
        print("Account created.")
        return render_template('login.html', user=new_user)
    except:
        return render_template('error.html', error="Could not insert user.")


@app.route('/createuser',methods=['POST'])
def create_user():
    # pass
    username = request.form.get('username')
    password = request.form.get('password')
    new_user={
        "username":username,
        "password":password
    }
    user = users.find_one({"username":username})

    if user is not None:
        return render_template('error.html',error='User has been created!')
    else:
        try:
            users.insert_one(new_user)
            print("created!")
            return render_template('login.html',user=new_user)
        except:
            return render_template('error.html',error='Some error is happened,you can not created this user,please try it again')

    # print("post,username:%s password:%s"%(username,password))

    # return "post,username:%s password:%s"%(username,password)


@app.route('/login', methods=['GET'])
def login():
    username = request.args.get('username', '')
    user = users.find_one({'username' : username})
    if user is None:
        return render_template('error.html', error="User does not exist.")
    print("User: " + str(user))
    return render_template('login.html', user=user)
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-10-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python乱炖 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • About MongoDB
  • Features
  • Concepts
  • Using MongoDB with Python
    • Accessing a database
      • Accessing a collection
        • Finding a document
          • Inserting a document
            • Deleting a document
              • Deleting a collection
                • Iterating a collection
                • Using MongoDB with Flask
                • Conclusion
                相关产品与服务
                数据库
                云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档