Login using python Flask with MongoDB and Blueprint



In this post, I will present how I used it, it is not necessarily the best approach
I tried to make it as simple as possible ;)

Assumption:

  • You know Flask, python and MongoDB.
  • You know how what blueprint is in Flask terminology.
  • You know how to user forms
in example_bp.py:

#your imports here

from flask import Flask, Blueprint, request, render_template, session, redirect, url_for
from wtforms import TextField,PasswordField
from flask.ext.pymongo import MongoClient
from flask.ext.wtf import Form,RecaptchaField
import sys
from wtforms.validators import DataRequired, Email
from wtforms.validators import *
from flask.ext.login import LoginManager, login_user, logout_user, current_user, login_required
from flask.ext.login import UserMixin
from functools import wraps
from datetime import datetime, timedelta
from flask.ext import admin
import json
from flask.json import jsonify



mongo_host = 'localhost'
mongo_port = 27017
example_database_name = 'expl'


example_blue_print = Blueprint('examlpe_bluep',__name__) 
login_manager = LoginManager() 
login_manager.login_view = 'example_login'
client = MongoClient(mongo_host,mongo_port) 
db = client[example_database_name]

class User(UserMixin):
  username = ""
  password = ""
  def get_id(self):
    return db.example_users.find_one({'ex_username': self.username})['_id']


#This is used instead of login_manager.init_app(app)               
#Since this is a blueprint   
@example_blue_print.record_once                                             
def on_load(state):                                                
  login_manager.init_app(state.app)  



@login_manager.user_loader
def load_user(userid):
  user_record = db.users.find_one({'_id': userid})
  user = User()
  user.username = user_rec['username']
  user.password = user_rec['password']
  return user


@example_blue_print.route('/login',methods=['POST','GET'])
def login():
  if request.method == 'POST':
    form = loginForm(request.form)
    user_record = form.validate_and_get_user_record()
    if user_record != None:
      user = User()
      user.username = user_record['username']
      user.password = user_record['password']
      login_user(user,False)
      return 'Login successful'

      
  else:
    form = loginForm()
  return render_template('login.html',form=form)



##end of example_bp.by

to run this you need another python file (below)

## let us call it flask_main_example.py


from flask import Flask, request, Blueprint, render_template
from pymongo import MongoClient
from example_bp import example_blue_print
from flask.ext.login import LoginManager

app = Flask(__name__)
#I'm not sure the if the below 2 lines are needed, but I'm lazy to find out :D
login_manager = LoginManager()
login_manager.init_app(app)
#list blueprints below
app.register_blueprint(example_blue_print)

if __name__== '__main__':
  app.run()


#end of the file

in the terminal try to run it as:
python example_bp.by

I hope guys you like it ;)

Please let me know if you have an problems with that :)


Resources:
  • Flask official website.
  • Mongo official website.
  • python official website.
  • Other websites (sorry, I do not remember them :D) 


Comments

Post a Comment

Popular Posts