Created
August 20, 2019 02:47
-
-
Save ndavison/52317885235554bfcfdd13a522aa1b5a to your computer and use it in GitHub Desktop.
Simple Flask (with Flask-Login) example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, request, jsonify, session | |
from flask_login import current_user, login_required, login_user, LoginManager, logout_user | |
app = Flask(__name__) | |
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' | |
login_manager = LoginManager() | |
login_manager.init_app(app) | |
class User(): | |
id = None | |
name = '' | |
is_anon = True | |
def __init__(self, id, is_anon): | |
self.id = id | |
self.is_anon = is_anon | |
def set_name(self, name): | |
self.name = name | |
def is_authenticated(self): | |
return not self.is_anon | |
def is_active(self): | |
return not self.is_anon | |
def is_anonymous(self): | |
return self.is_anon | |
def get_id(self): | |
if not self.id: | |
return None | |
return str(self.id).encode('utf-8') | |
@login_manager.user_loader | |
def load_user(id): | |
is_anon = True | |
if id: | |
is_anon = False | |
return User(id, is_anon) | |
@app.before_request | |
def print_session(): | |
print session | |
@app.route('/') | |
def main(): | |
if not current_user.is_authenticated: | |
user = User(None, True) | |
login_user(user) | |
return 'hello' | |
@app.route('/login') | |
def login(): | |
user = User(1, False) | |
login_user(user) | |
return jsonify(success=True), 200 | |
@app.route('/logout') | |
def logout(): | |
logout_user() | |
return jsonify(success=True), 200 | |
@app.route('/private') | |
@login_required | |
def private(): | |
return jsonify(private='abcxyz'), 200 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment