Flask+MongoDB

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介: 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 MongoClient
app = 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)



640.png

相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
相关文章
|
2月前
|
JSON 前端开发 API
使用Python和Flask构建简易Web API
使用Python和Flask构建简易Web API
130 3
|
2月前
|
开发框架 前端开发 JavaScript
利用Python和Flask构建轻量级Web应用的实战指南
利用Python和Flask构建轻量级Web应用的实战指南
113 2
|
2月前
|
JSON API 数据格式
如何使用Python和Flask构建一个简单的RESTful API。Flask是一个轻量级的Web框架
本文介绍了如何使用Python和Flask构建一个简单的RESTful API。Flask是一个轻量级的Web框架,适合小型项目和微服务。文章从环境准备、创建基本Flask应用、定义资源和路由、请求和响应处理、错误处理等方面进行了详细说明,并提供了示例代码。通过这些步骤,读者可以快速上手构建自己的RESTful API。
161 2
|
2月前
|
JSON API 数据格式
构建RESTful APIs:使用Python和Flask
构建RESTful APIs:使用Python和Flask
42 1
|
2月前
|
JSON API 数据格式
使用Python和Flask构建简单的Web API
使用Python和Flask构建简单的Web API
|
3月前
|
JSON API 数据格式
构建RESTful APIs:使用Python和Flask
【10月更文挑战第12天】本文介绍了如何使用Python和Flask构建一个简单的RESTful API。首先概述了API的重要性及RESTful API的基本概念,接着详细讲解了Flask框架的特性和安装方法。通过创建一个基本的Flask应用,定义了处理“图书”资源的GET、POST、PUT和DELETE方法的路由,展示了如何处理请求和响应,以及如何进行错误处理。最后,提供了运行和测试API的方法,总结了Flask在构建RESTful API方面的优势。
45 1
|
3月前
|
JSON API 数据格式
构建RESTful APIs:使用Python和Flask
【10月更文挑战第10天】本文介绍了如何使用Python和Flask构建一个简单的RESTful API。Flask是一个轻量级的Web应用框架,适合小型项目和微服务。文章从环境准备、创建基本Flask应用、定义资源和路由、请求和响应处理、错误处理等方面进行了详细说明,并提供了代码示例。通过这些步骤,读者可以快速掌握使用Flask构建RESTful API的方法。
62 1
|
3月前
|
数据库 开发者 Python
使用Python和Flask构建Web应用
【10月更文挑战第2天】使用Python和Flask构建Web应用
36 2
|
3月前
|
API 数据库 开发者
Flask:Python的轻量级Web框架
Flask:Python的轻量级Web框架
63 2