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)
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
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()
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()
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)
from flask import Flask, request 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 app = Flask(__name__) app.config.from_object(Config) # app.secret_key = 'afjah3ur38thgh' login = LoginManager(app) login.login_view = 'login' login.login_message = _l('Please log in to access this page.') # 日志 app.logger = logging_module.getLogger('log/log.log', 'mylog') db = SQLAlchemy(app) migrate = Migrate(app, db) # 邮件 mail = Mail(app) # css框架Bootstrap bootstrap = Bootstrap(app)
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)
# -*- 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)
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
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'])
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"),
# -*- 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'
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