Beispiel #1
0
def register(app):
    app.add_url_rule("/api/auth_token", view_func=AuthToken.as_view("auth_token"))
    app.add_url_rule("/api/logout", view_func=Logout.as_view("logout"))

    app.secret_key = app.config.get("SECRET_KEY")
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.user_loader(__user_loader)
Beispiel #2
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(flask_config)
    app.secret_key = os.urandom(24)

    app.register_blueprint(users_app, url_prefix='/users')
    app.register_blueprint(projects_app, url_prefix='/projects')

    login_manager = LoginManager()
    login_manager.init_app(app)

    def flask_login_user_loader(user_id):
        return g.db.query(User).filter(User.id == user_id).first()
    login_manager.user_loader(flask_login_user_loader)

    return app
Beispiel #3
0
def get_app(config_obj='gfzreport.web.config_example.BaseConfig', data_path=None,
            db_path=None, **custom_config_settings):
    '''
    initializes the app and setups the blueprint on it
    :param config: string, A valid argument for `app.config.from_object`.
    Specifying other paths allows us to run tests with a given external python file
    :param data_path: the data source path. The directory should have a 'source' subdirectory
    where any folder not starting with "_" will be interpreted as a report and accessible
    though an endpoint url. If None, the environment variable 'DATA_PATH' must be set, otherwise
    an Exception is raised
    :param db_path: the path for the Users database. It must denote a directory where the db
    will be retrieved or created. If the file 'users.txt' is also present inside the directory,
    it will be used to set/update/delete database users. If this argument is missing (None), and
    the environment variable DB_PATH is set, the latter will be used.
    If this argument is None or does not point to any existing directory, no database will be
    created
    '''
    if data_path is None:
        if 'DATA_PATH' not in os.environ or not os.environ['DATA_PATH']:
            raise ValueError(("You need to set the environment variable DATA_PATH "
                              "pointing to a valid folder where source and build files will "
                              "be processed"))
        data_path = os.environ['DATA_PATH']

    if not os.path.isdir(data_path):
        raise ValueError("Not a directory: DATA_PATH='%s'\n"
                         "Please change environment variable 'DATA_PATH'" % str(data_path))

    app = Flask(__name__)
    app.secret_key = os.urandom(24)

    # Note: supply absolute module path. Apache complains that a config is elsewhere defined
    # in the python path otherwise:
    app.config.from_object(config_obj)
    # cutom configs (for testing purposes:
    for key, val in custom_config_settings.items():
        app.config[key] = val

    app.config['REPORT_BASENAMES'] = {}  # will be populatedwhen querying pages

    app.config['DATA_PATH'] = data_path
    app.config['BUILD_PATH'] = os.path.abspath(os.path.join(app.config['DATA_PATH'], "build"))
    app.config['SOURCE_PATH'] = os.path.abspath(os.path.join(app.config['DATA_PATH'], "source"))

    # we should look at ini file or whatever
    if db_path is None and 'DB_PATH' in os.environ:
        db_path = os.environ['DB_PATH']
    app.config['DB_PATH'] = db_path
    initdb(app)
    initdbusers(app)

    # Flask-Login Login Manager
    login_manager = LoginManager()
    # Tell the login manager where to redirect users to display the login page
    # login_manager.login_view = "/login/"
    # Setup the login manager.
    login_manager.setup_app(app)
    # https://github.com/maxcountryman/flask-login/blob/master/docs/index.rst#session-protection:
    login_manager.session_protection = "strong"

    @login_manager.user_loader
    def load_user(user_id):
        with session(app) as sess:
            return sess.query(User).filter(User.id == int(user_id)).first()

    from gfzreport.web.app.views import mainpage
    app.register_blueprint(mainpage)

    return app
Beispiel #4
0
from flask_login.login_manager import LoginManager
from flask_login import login_user, logout_user, login_required, current_user
from flask.blueprints import Blueprint
from flask import request, render_template, flash, redirect, url_for
from werkzeug.security import generate_password_hash, check_password_hash
from .db import User, engine
from .form import LoginForm, SignUpForm, ChangePasswordForm

login_manager = LoginManager()
login_manager.login_view = 'auth.login'

bp = Blueprint("auth", __name__, url_prefix="/auth")


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))


@bp.route("/login", methods=("GET", "POST"))
def login():
    login_form = LoginForm()
    if login_form.validate_on_submit():
        email = request.form.get("email")
        password = request.form.get("password")
        remember_me = True if request.form.get("remember_me") else False

        user = User.query.filter_by(email=email).first()
        if not user:
            flash("bad login")
            return render_template("auth/login.html", form=login_form)
Beispiel #5
0
from flask_login.login_manager import LoginManager
from board_base import db_exception, app, db
from flask_login.utils import login_user, logout_user, current_user, login_required, login_fresh
from mylogger import logger
from db.user import User
from werkzeug.security import check_password_hash
from werkzeug.utils import redirect



auth_api = Blueprint("auth_api", __name__, url_prefix='/api')



#Flask-Login 모듈
login_manager = LoginManager()  # 로그인/로그아웃 관련 세션을 관리해주는 flask-login 모듈 객체 생성
login_manager.init_app(app)     # flask객체와 연동

#인증되지 않은 사용자가 @login_required 페이지 접속을 시도할 시 redirect할 페이지 설정
login_manager.login_view = 'auth_view.login'    
login_manager.login_message = "로그인이 필요합니다."

@login_manager.user_loader      # 세션에 저장된 ID에 해당하는 user객체를 반환하는 callback 메소드, 유효하지 않은 ID일 경우 None을 반환한다.
@db_exception
def load_user(id):
        logger.info("load_user(), session:"+str(session))

        cursor = db.get_conn().cursor()
        cursor.callproc('get_user_by_id', (id,))  # argument 1개일 때도 ,하나 붙여줘야 제대로 인식함.
        r = cursor.fetchall()
        cursor.close()
Beispiel #6
0
from flask import Flask, request, current_app
from app.config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login.login_manager import LoginManager
from app.log import logging_module
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_babel import Babel, lazy_gettext as _l

login = LoginManager()
login.login_view = 'login'
login.login_message = _l('Please log in to access this page.')

db = SQLAlchemy()
migrate = Migrate()
# 邮件
mail = Mail()
# css框架Bootstrap
bootstrap = Bootstrap()
# 日期和时间处理
moment = Moment()
# 语言翻译
babel = Babel()


def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(Config)
Beispiel #7
0
from flask import Flask
from app.config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login.login_manager import LoginManager
from app.log import logging_module
from flask_mail import Mail
from flask_bootstrap import Bootstrap

app = Flask(__name__)
app.config.from_object(Config)
# app.secret_key = 'afjah3ur38thgh'

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

# 日志
app.logger = logging_module.getLogger('log/log.log', 'mylog')

db = SQLAlchemy(app)
migrate = Migrate(app, db)

# 邮件
mail = Mail(app)

# css框架Bootstrap
bootstrap = Bootstrap(app)

Beispiel #8
0
from flask import request
from flask_login import login_user, login_required
from flask import redirect
from flask_login import logout_user
from flask import url_for
from flask_login import UserMixin
from werkzeug.security import check_password_hash
from web_content.src.blogYY.blogYY_login_service import search_user_by_username
from web_content.src.blogYY.blogYY_login_service import search_user_by_uuid_str

# use login manager to manage session
# 维护用户的会话,关键就在于这个LoginManager对象
# 必须实现load_user callback函数,用于reload user object
# 当密码验证通过后,使用login_user函数来登录用户,
# 这时用户在会话中的状态就是登录状态了
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'blogYY_page_user_login'
login_manager.init_app(app)


class User(UserMixin):
    def __init__(self, uuid_str: str):
        self.uuid_str = uuid_str
        self.username = search_user_by_uuid_str(uuid_str)['username']

    def get_id(self):
        return self.uuid_str


# 这个callback函数用于reload User object,根据session中存储的user id
Beispiel #9
0
import os

from flask import Flask
from flask_login.login_manager import LoginManager
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ['SECRET_KEY']
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
login_manager = LoginManager(app)
db = SQLAlchemy(app)

import recipe_hub.views
Beispiel #10
0
# -*- encoding: utf-8 -*-

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_socketio import SocketIO
from flask_login.login_manager import LoginManager

app = Flask(__name__)

app.config.from_object('app.configuration')

lm = LoginManager(app)
db = SQLAlchemy(app)  # flask-sqlalchemy

socketio = SocketIO(app, message_queue=app.config['REDIS_URI'])

from app import views, models

lm.login_view = 'login'
Beispiel #11
0
from flask_login.login_manager import LoginManager
from flask_principal import Principal, Permission, RoleNeed
from flask_restful import Api

from itemCatalog.models import User
from itemCatalog.rest.api import CategoryAPI, ItemAPI

# What does this file do?
#  - creates and configures the extensions the app uses

principals = Principal()
admin_permission = Permission(RoleNeed('admin'))
default_user_permission = Permission(RoleNeed('user'))

login_manager = LoginManager()
login_manager.login_view = "login"
login_manager.login_message = "Please, login to access this page"
login_manager.login_message_category = "info"
login_manager.session_protection = "strong"


@login_manager.user_loader
def load_user(userId):
    return User.query.get(userId)


rest_api = Api()

rest_api.add_resource(CategoryAPI, '/api/category/',
                      '/api/category/<int:category_id>/')
Beispiel #12
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login.login_manager import LoginManager
from flask_mail import Mail
from config import Config

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
lm = LoginManager(app)
lm.session_protection = 'strong'
lm.login_view = '/login'
mail = Mail(app)
mail.init_app(app)
from routes import *



if __name__ == '__main__':
    remove_captcha()
    app.run(host='0.0.0.0', port=8080)
Beispiel #13
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os
from flask_login.login_manager import LoginManager
#from flask_openid import OpenID
from config import basedir, ADMINS, MAIL_SERVER, MAIL_PORT
from config import MAIL_PASSWORD, MAIL_USERNAME

app = Flask(__name__)

app.config.from_object('config')
db = SQLAlchemy(app)

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

#oid = OpenID(app, os.path.join(basedir, 'tmp'))

if not app.debug:
    import logging
    """
    from logging.handlers import SMTPHandler
    
    credentials = None
    if MAIL_USERNAME or MAIL_PASSWORD:
    
        credentials = (MAIL_USERNAME, MAIL_PASSWORD)
    
    mail_handler = SMTPHandler((MAIL_SERVER, MAIL_PORT), 
                               'noreply@'+MAIL_SERVER, ADMINS, 
Beispiel #14
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_moment import Moment
from flask_login.login_manager import LoginManager
from flask_mail import Mail
from app.config import config
from flask_wtf.csrf import CSRFProtect
import os

mail = Mail()
database = SQLAlchemy()
moment = Moment()
bcrypt = Bcrypt()
csrf = CSRFProtect()
login_manager = LoginManager()
login_manager.login_view = "users.login"
login_manager.login_message = "You must be signed in to view that page!"
login_manager.login_message_category = "danger"
login_manager.refresh_view = login_manager.login_view
login_manager.needs_refresh_message = "To protect your account, please re-authenticate to access this page!"
login_manager.needs_refresh_message_category = "danger"


def create_app():
    app = Flask(__name__)
    app.config.from_object(config[os.environ.get("APP_SETTINGS")])

    with app.app_context():
        database.init_app(app)
        bcrypt.init_app(app)
Beispiel #15
0
from flask_login.login_manager import LoginManager
from flask_login import login_user, logout_user, login_required
from flask import Flask, redirect, url_for, render_template
from flask_graphql import GraphQLView
from flask_sqlalchemy import SQLAlchemy
from flask_dance.contrib.google import make_google_blueprint, google
from oauthlib.oauth2 import TokenExpiredError
from flask_cors import CORS

flask_app = Flask(__name__)
config_module = import_module(os.environ.get('CONFIG_MODULE',
                                             'backend.config'))
ConfigObject = getattr(config_module, 'ConfigObject')
flask_app.config.from_object(ConfigObject())
flask_app.debug = True
login_manager = LoginManager()
login_manager.init_app(flask_app)

db = SQLAlchemy(flask_app)

CORS(flask_app)


def init_app(app):
    from backend.schema import schema
    from backend.models import User

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)
Beispiel #16
0
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login.login_manager import LoginManager
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_babel import Babel, lazy_gettext as _l

microblogapp = Flask(__name__)
microblogapp.config.from_object(Config)
db = SQLAlchemy(microblogapp)
migrate = Migrate(microblogapp, db)
login = LoginManager(microblogapp)
login.login_view = 'login'  #view function that handles login and is redirected to whenever the request is unauthenticated
login.login_message = _l('Please login to access this page')
mail = Mail(microblogapp)
bootstrap = Bootstrap(microblogapp)
moment = Moment(microblogapp)
babel = Babel(microblogapp)

if not microblogapp.debug:
    #mail configuration
    if microblogapp.config['MAIL_SERVER']:
        auth = None
        if microblogapp.config['MAIL_USERNAME'] or microblogapp.config[
                'MAIL_PASSWORD']:
            auth = (microblogapp.config['MAIL_USERNAME'],
                    microblogapp.config['MAIL_PASSWORD'])
Beispiel #17
0
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from flask_wtf import CSRFProtect
from flask_login.login_manager import LoginManager
from csdb.modle.ldap_user import LdapUser

bootstrap = Bootstrap()
db = SQLAlchemy()
csrf = CSRFProtect()

#login
login_manager = LoginManager()
login_manager.login_view = 'login.login'
login_manager.login_message = '你必须登陆后才能访问该页面'
login_manager.login_message_category = "info"


@login_manager.user_loader
def load_user(userid):
    return LdapUser.get_user(userid)
Beispiel #18
0
from crypto.library.hash import generate_hash
from flask.blueprints import Blueprint
from flask.globals import request, current_app
from flask.helpers import url_for, flash, make_response
from flask_login.login_manager import LoginManager
from flask_login.utils import login_user, current_user, logout_user, login_required
from werkzeug.security import check_password_hash
from werkzeug.utils import redirect
from mylogger import logger
from db.user import User
from recruit_base import app, try_except, dao

auth_api = Blueprint("auth_api", __name__, url_prefix='/api')

#Flask-Loing 모듈
login_manager = LoginManager()
login_manager.init_app(app)

login_manager.login_view = 'auth_view.login_form'
login_manager.login_message = "로그인이 필요합니다."


@login_manager.user_loader
@try_except
def load_user(email):
    logger.info("load_user(%s)" % (email))
    cursor = dao.get_conn().cursor()
    cursor.execute("select * from recruit_user where user_email like '%s'" %
                   (email))
    result = cursor.fetchone()
Beispiel #19
0
# -*- coding: utf-8 -*-

import json

from bson.objectid import ObjectId
from flask.json import JSONEncoder as encoder

from flask_login.login_manager import LoginManager
from flask_pymongo import PyMongo

lm = LoginManager()

mongo = PyMongo()


class MongoJSONEncoder(encoder):
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)
        return encoder.default(self, o)


class LoyalityJSONDecoder(json.JSONDecoder):
    def decode(self, s, **kwargs):
        result = super(LoyalityJSONDecoder, self).decode(s)
        return self._decode(result)

    def _decode(self, o):
        if isinstance(o, str) or isinstance(o, unicode):
            try:
                return int(o)
Beispiel #20
0
from flask import Flask
from flask_login.login_manager import LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config

db = SQLAlchemy()
migrate = Migrate()
login = LoginManager()


def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)

    from spp.start import bp as starter_bp
    app.register_blueprint(starter_bp)

    return app
Beispiel #21
0
def init(**kwargs):
    for k, v in kwargs.items():
        setattr(Config, k, v)

    app = Flask(__name__)
    db.init_db()
    sms = AliyunSms(app)
    Config.sms = sms
    Config.app = app

    app.add_template_global(str, 'str')
    app.secret_key = Config.secret_key
    app.wsgi_app = ProxyFix(app.wsgi_app)

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

    if app.debug:
        stream_handle = logging.StreamHandler()
        stream_handle.setFormatter(logging.Formatter(Config.logging_fmt))
        stream_handle.setLevel(logging.INFO)
        app.logger.addHandler(stream_handle)

    file_handle = logging.FileHandler(Config.logging_path)
    file_handle.setFormatter(logging.Formatter(Config.logging_fmt))
    file_handle.setLevel(logging.WARNING)

    app.logger.addHandler(file_handle)

    @login_manager.user_loader
    def load_user(user_id):
        return db.User.query.filter_by(id=int(user_id)).first()

    @app.errorhandler(404)
    @monitor
    def not_found(error):
        Dangerous.add()
        return render_template("404.html"), 404

    @app.errorhandler(400)
    @monitor
    def not_found(error):
        Dangerous.add()

        return "贪玩", 400

    @app.before_request
    def load_current_user():
        g.user = current_user

    @app.teardown_request
    def remove_db_session(exception):
        db.db_session.remove()

    @app.route('/image/<imagep>')
    def get_image(imagep):
        try:
            path = str(Config.path / "sharh-static" / "static" / "images" / imagep)
            with open(path, 'rb') as image:
                return Response(image.read(), content_type="image/{}".format("png" if ".png" in imagep else
                                                                             "jpeg" if ".jpg" in imagep else
                                                                             "gif" if ".gif" in imagep else
                                                                             ""))
        except Exception as e:
            logging.log(logging.WARNING, e)
            return Response(render_template('404.html'))

    from rx_sharh.service.view import attendance
    from rx_sharh.service.view import group
    from rx_sharh.service.view import authentication
    from rx_sharh.service.view import schedule
    from rx_sharh.service.view import profile
    from rx_sharh.service.view import index

    app.register_blueprint(attendance.mod)
    app.register_blueprint(group.mod)
    app.register_blueprint(authentication.mod)
    app.register_blueprint(schedule.mod)
    app.register_blueprint(profile.mod)
Beispiel #22
0
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, session
from flask_bootstrap import Bootstrap
from flask_login.login_manager import LoginManager
from config import config
from random import randint
from flask_mail import Mail

db = SQLAlchemy()
bootstrap = Bootstrap()
login_manager = LoginManager()
mail = Mail()

from app.models import User, AnonymousUser

login_manager.session_protection = 'strong'
login_manager.login_view = 'page.page_login'
login_manager.anonymous_user = AnonymousUser


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    db.init_app(app)
    bootstrap.init_app(app)
    mail.init_app(app)

    from app.main import page as page_blueprint
    app.register_blueprint(page_blueprint)

    # @app.before_request
Beispiel #23
0
from flask.app import Flask
from flask_bootstrap import Bootstrap
from flask_login.login_manager import LoginManager
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy

from app.pyweb.common import log_common
from app.pyweb.common.log_common import LogCommon
from config import config

bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.session_protection = 'Strong'
login_manager.login_view = 'auth.login'


def create_app(config_name):
    app = Flask(__name__)
    print(__name__)
    app.config.from_object(config[config_name])
    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    # 初始化db
    db.init_app(app)

    login_manager.init_app(app)
Beispiel #24
0
from flask_login import login_manager, current_user
from flask_login.login_manager import LoginManager
from passlib.apps import custom_app_context as pwd_context
from datetime import timedelta
from flask_login.utils import login_required
from classes import UserList, User
from system_requirements_checker import SystemRequirementsChecker

app = Flask(__name__)
app.register_blueprint(link1)
app.register_blueprint(link2)
app.register_blueprint(link3)
app.register_blueprint(link4)
app.register_blueprint(link5)
app.secret_key = 'gallifrey'
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'link1.home_page'
login_manager.fresh_view = 'link1.home_page'


@login_manager.user_loader
def load_user(user_id):
    return User("zzz", "zzz", "zzz").get_user(user_id)


@login_manager.unauthorized_handler
def unauthorized():
    flash("Unauthorized Access. Please Sign In or Sign Up!")
    return redirect(url_for('link1.home_page'))
Beispiel #25
0
from flask import Flask, logging
from flask_pymongo import PyMongo
from flask_login.login_manager import LoginManager
from flask_restful import Api
from setting import Config

app = Flask(__name__,
            static_folder='view/static',
            template_folder='view/templates')
app.config.from_object(Config)
logger = logging.create_logger(app)
mongo = PyMongo(app)
login_manager = LoginManager()
login_manager.login_view = '/login'
login_manager.login_message = '请先登录。'
login_manager.session_protection = 'strong'
login_manager.init_app(app)
api = Api(app)
Beispiel #26
0
from server.services.mail_conf import *
# get_clients, get_cats, get_mail_comf, save_mail_conf, block_mail_conf, get_mail, otp_send_process

from server.services import logger
from server.constants import *

app = Flask(__name__)
app.secret_key = SEC_KEY
app.SESSION_COOKIE_SECURE = True

if IS_DEVELOPMENT:
    app.config["debug"] = True
else:
    app.config["debug"] = False

loginmanager = LoginManager()
loginmanager.init_app(app)
loginmanager.login_view = "/login"

ROOT_PATH = os.path.join(os.path.split(__file__)[0], "..")
CSS_PATH = os.path.join(ROOT_PATH, "static", "css")
JS_PATH = os.path.join(ROOT_PATH, "static", "js")
IMAGES_PATH = os.path.join(ROOT_PATH, "static", "images")
FONT_PATH = os.path.join(ROOT_PATH, "static", "font")
DOCS_PATH = os.path.join(ROOT_PATH, "templates", "docs")

unauthtemplates = ["/login/login.html"]

TEMPLATE_PATH = [("/", "/login/login.html"),
                 ("/infolist/login", "/login/login.html"),
                 ("/infolist/index", "/home/index.html"),
Beispiel #27
0
from flask import Flask, render_template
from flask_login.login_manager import LoginManager

from models import Session, User, Post
from views import auth_app

app = Flask(__name__)
app.config.update(
    DEBUG=True,
    SECRET_KEY="topsecretkey1231231240dsdf",
)
app.register_blueprint(auth_app, url_prefix="/auth")

login_manager = LoginManager()
login_manager.init_app(app)


@login_manager.user_loader
def load_user(user_id):
    return Session.query(User).filter_by(id=user_id).one_or_none()


@app.route("/", endpoint="index")
def index():
    return render_template("index.html")


@app.teardown_request
def remove_session(*args):
    Session.remove()
Beispiel #28
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from config import config
from flask_login.login_manager import LoginManager

bootstrap = Bootstrap()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'page.login'


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    with app.app_context():
        db.init_app(app)

    from app.main import page as page_blueprint
    app.register_blueprint(page_blueprint)

    login_manager.init_app(app)

    from app.models import User

    @login_manager.user_loader
    def load_user(id):
Beispiel #29
0
        would automatically have a __tablename__ value of 'my_model'
        :return:
        """
        return to_snake_case(cls.__name__)

    def __init__(self, **kwargs):
        for attr_name, attr_value in kwargs.items():
            setattr(self, attr_name, attr_value)

    def __repr__(self: DeclarativeMeta):
        column_names = (c.name for c in self.__mapper__.columns)
        kwargs = ', '.join(f'{n}={getattr(self, n)!r}' for n in column_names)
        return f'{self.__class__.__name__}({kwargs})'

    def as_dict(self: DeclarativeMeta):
        column_names = (c.name for c in self.__mapper__.columns)
        return {n: getattr(self, n) for n in column_names}

    @property
    def session(self):
        instance_state = inspect(self)
        return instance_state.session or db.session


db = SQLAlchemy(model_class=ModelBase)
debug_toolbar = DebugToolbarExtension()
jsglue = JSGlue()
mail = Mail()
csrf = CSRFProtect()
login_manager = LoginManager()
Beispiel #30
0
from flask import Flask
from flask_bcrypt import Bcrypt
from flask_login.login_manager import LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

# DETACHED EXTENSIONS
db = SQLAlchemy()
# Authentication manager and System setup
login_manager = LoginManager()
login_manager.login_view = 'users.login'
# password encryption
bcrypt = Bcrypt()


def create_app(config_file=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_pyfile(config_file)
    initialize_extensions(app)
    register_blueprints(app)

    return app


def initialize_extensions(app):
    # bind extensions to the flask app
    db.init_app(app)
    Migrate(app, db)
    login_manager.init_app(app)
    bcrypt.init_app(app)