Flask+MongoDB

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

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

try:
users = db.users
    print("Connected to collection :)")
except:
    print("Could not connect to collection :(")

Finding a document

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

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

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

try:
users.drop()
    print("cleared users collection.")
except:
    print("Could not clear users collection.")

Iterating a collection

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

from flask import Flask
from flask import render_template
from flask import request
from pymongo import MongoClientapp = Flask(__name__)

Then setup our database:

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

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

With index.html containing

<!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

@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

<!--login.html--><!doctype html>
{% if user %}
<h1>Hello {{ user.name }}!</h1>
{% else %}
<h1>User does not exist.</h1>
{% endif %}
<!--error.html--><!doctype html>
{% if error %}
<h1>Error: {{ error }}</h1>
{% else %}
<h1>404.</h1>
{% endif %}

The directory layout of our files is

/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

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)

本文分享自微信公众号 - Python乱炖(Cooking_python),作者:我被狗咬了

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2018-10-29

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • JupyterNotebook‘s Magic

    上个星期在看代码的时候,一个意外让我了解到了jupyternotebook上的黑魔法。是这样子的:

    我被狗咬了
  • Python封装

    函数本身其实就相当于一个集装箱,她负责把我们之前写的那些代码装进去,她在打包的时候会在箱子的上下各开两个透气的口子,上面的口子叫参数,下面的口子叫返回值~~~~...

    我被狗咬了
  • 五分钟叫你学会操作MongoDB增删改查

    此篇是相信大家对SQL语句有一定的基础下去看能看懂点,没有SQL基础的也么有问题,直接背住就可以了!(毕竟SQL语句也是背的,MongoDB肯定也是要记熟的)

    我被狗咬了
  • 政府对于云计算技术的引入会更谨慎一些

    有数据显示,我国在"十五"、"十一五"期间对于政务信息化建设方面总投资已超过600亿元,其中中央投资300多亿元。"十二五"以来,随着国家对于信息安全日趋重视,...

    静一
  • .Net Core + NGINX跳转登录时端口丢失

    使用.Net Core + NGINX部署到服务器的时候,如果端口不是使用默认的80端口,在跳转到登录页面时,URL中的端口丢失。

    Mr. Wei
  • 聊聊 Python 面试最常被问到的几种设计模式(上)

    在很多人的印象里,Python 作为一款动态编程语言,在日常开发中也很少涉及到设计模式

    AirPython
  • 独家 | 揭秘出行巨头Uber的机器学习平台与团队

    李根 发自 凹非寺 量子位 报道 | 公众号 QbitAI ? 科技巨头加注人工智能仿佛是场竞赛。 前不久,Uber正式推出机器学习平台Michelangel...

    量子位
  • iOS百度地图问题总结(四)

    下面这两个方法(void)mapView:(BMKMapView *)mapView didAddAnnotationViews:(NSArray *)view...

    hrscy
  • YII2框架中使用RBAC对模块,控制器,方法的权限控制及规则的使用示例

    本文实例讲述了YII2框架中使用RBAC对模块,控制器,方法的权限控制及规则的使用。分享给大家供大家参考,具体如下:

    砸漏
  • 证书签发机构StartCom也被曝签发假证书

    位于以色列埃拉特的证书颁发机构StartCom 之前已经被大部分浏览器取消信任,但前几天被曝光签发了假的证书,包括最高信任级别的 EV 证书。 StartCom...

    FB客服

扫码关注云+社区

领取腾讯云代金券