Mind Juice

J U S T · A · S A F E T Y · N E T
  • DL
    • Introduction
    • Neural Network
  • Back-End
    • Flask
      • Flask Basics
      • Login & Logout
      • Broadcasting
      • Relationships
      • All App Files
      • The Memoirs Project
    • Django
      • Django Basics
      • Coding Entrepreneurs
    • Dev. Tech
      • Infrastructure
      • HTTP & REST
      • GitHub
    • Database
      • Relational Databases
    • Linux
      • Ubuntu
      • Command Line
  • Python
    • Setup Python
    • Python Basics
    • Python Collection
      • Lists
      • Dictionaries
      • Tuples
      • Sets
      • Game Practice
    • Object-Oriented Python
    • DB in Python
    • Better Python
    • Comprehension
    • Dates & Times
    • Regular Expressions
    • Type Hinting
    • Files I/O
    • Python Testing
  • JavaScript
    • JavaScript Basics
    • ES2015
    • jQuery
    • DOM Scripting
    • Callback Functions
    • Array Iteration
    • OOP
    • Regular Expressions
    • Pseudocode
    • Closures
    • Local Storage
    • AJAX & JSON
    • Async. Programming
    • Mobile Web Apps
    • React
  • Front-End
    • HTML
    • CSS & Sass
      • CSS
      • Flexbox
      • CSS Variables
      • CSS Grid
      • CSS Best Practices
      • CSS to Sass
      • Sass
    • Bootstrap 5
    • Chrome DevTools
    • Front End Optimizing
      • Gulp
      • FE Optimization Workflow
      • CHECKLIST
    • Web Accessibility
    • SEO & Digital Marketing
  • Design
    • Foundations
    • Branding
    • Typography
    • UX
      • Design Thinking
      • Wireframing
      • Dev. Collaboration
      • Feedback
    • Freelance
    • Multimedia

DB Connection & Login Manager

  • Mind Juice
    • Register, Login & Logout
  • DB Connection & Login Manager

DB Connection & Login Manager

Aug 07 2016- POSTED BY projecth Comments Off on DB Connection & Login Manager

Part of setting up the database is handling connecting and disconnecting from our database responsibly. To do that, we use the before_request and after_request decorators.

The g object that Flask gives us helps us make different things global. We’ll use it to make our database connection and our current user available everywhere. Having a global database will make it a lot easier for us if we decide to build our app with a lot of different modules.

Flask Login is used to find the current user, or any user we’re looking for. To help with this process, we need to create a function that will return an instance of our user model; load_user(userID) that uses the login user_loader decorator.

[app.py]

from flask import Flask, g
from flask.ext.login import LoginManager

import models

DEBUG = True
PORT = 8000
HOST = '0.0.0.0'


app = Flask(__name__)
app.secret_key = 'jnkla@sdioa!sdjoo^paud&1293*hoads.ln10'


login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

@login_manager.user_loader
def load_user(userID):
    try:
        models.User.get(models.User.id == userID)
    except models.DoesNotExist:
        return None


@app.before_request
def before_request():
    """Connect to the database before each request"""
    g.db = models.DATABASE
    g.db.connect()
    

@app.after_request
def after_request(response):
    """Close the database connection after each request"""
    g.db.close()
    return response


if __name__ == '__main__':
    models.initialize()
    models.User.create_user(
        username='basharghadanfar',
        email='10.tens@gmail.com',
        password='123456',
        admin=True
        )
    app.run(debug=DEBUG, port=PORT, host=HOST)

secret_key
Used whenever we need to use sessions for our users.

login_manager = LoginManager()
Creates an instance of LoginManager.

login_manager.init_app(app)
Sets up the login_manager for our app.

login_manager.view = ‘login’
Naming the login view – which we don’t have yet – to which we will redirect the users in case they’re not logged in.

@login_manager.user_loader
def load_user(userID):
The function that the login_manager will use whenever it needs to lookup a user.

models.User.id
Returns the primary key, which had been automatically retrieved and stored on the record / model instance.

models.DoesNotExist
This is an exception that comes from PeeWee – which we’ve imported – and is used when failing to return a record with certain values.

g.db.close()
Closes the global database.

models.User.create_user( … )
We used the create_user classmethod to create an admin/superuser instead of CRUD’s .create, because we will always want a user with an encrypted password.


If we were to run:

>>> python app.py

it would initialize our models by connecting to the database, then create the User model, close the connection, then create a superuser for us – in case a superuser doesn’t exist already, and finally run the app.

  • Previous
  • Next
All rights reserved Mind Juice 2020.
Proudly powered by WordPress | Theme: Flatter by SpiceThemes