コード例 #1
0
ファイル: factory.py プロジェクト: Lunchable/eat
def create_app(config=None, environment=None):
    app = Flask(__name__)

    # TODO: Get this from a config file
    app.config["MONGODB_SETTINGS"] = {'db': "eatdb"}
    app.config[
        "SECRET_KEY"] = "\x1a\xb1\x9d\x1d\xf2\x01\xa1X\xb8g\xed\x1c\xb3\x0f+s\xbce\xf6\x92\x83'\xf2\xbc\x96\xc6\x18\x03`\xc0\x0c("
    app.config["IV"] = '\xe7\x9d\xc7\xbd\x12l\x88\xc7\xe9D\x93!\xa2B\xed\x91'
    app.config.from_pyfile('settings.cfg', silent=True)
    app.session_interface = MongoSessionInterface(**(app.config["MONGODB_SETTINGS"]))

    with app.app_context():
        from models import db
        db.init_app(app)

        login_manager = LoginManager()

        @login_manager.user_loader
        def load_user(id):
            if id in (None, 'None'):
                return None
            try:
                from models.user import User
                return User.objects(id=id).first()
            except:
                return None

        login_manager.init_app(app)

        from views import register_routes as register_views

        register_views(app)

    return app
コード例 #2
0
ファイル: test_login.py プロジェクト: nmaekawa/flask-login
class MethodViewLoginTestCase(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.login_manager = LoginManager()
        self.login_manager.init_app(self.app)
        self.login_manager._login_disabled = False

        class SecretEndpoint(MethodView):
            decorators = [
                login_required,
                fresh_login_required,
            ]

            def options(self):
                return u''

            def get(self):
                return u''

        self.app.add_url_rule('/secret',
                              view_func=SecretEndpoint.as_view('secret'))

    def test_options_call_exempt(self):
        with self.app.test_client() as c:
            result = c.open('/secret', method='OPTIONS')
            self.assertEqual(result.status_code, 200)
コード例 #3
0
def createApp():
  app = Flask(__name__)
  app.config.from_pyfile("config.default.py")
  app.config.from_envvar("TEST_TASK_PRODUCTION", silent = True)
  db.init_app(app)


  # настройка аутентификации
  login_manager = LoginManager()
  login_manager.init_app(app)
  login_manager.login_view = "Pages.defaultPage"

  @login_manager.user_loader
  def load_user(userId):
    if userId:
      user = User.query.filter_by(id = userId).one_or_none()
      return user
    return None


  from .blueprints.Pages import app as Pages
  from .blueprints.DataAuthRequest import app as DataAuthRequest
  from .blueprints.DataUser import app as DataUser
  from .blueprints.DataShop import app as DataShop
  from .blueprints.DataDoc import app as DataDoc
  from .blueprints.DataProduct import app as DataProduct

  app.register_blueprint(Pages)
  app.register_blueprint(DataAuthRequest, url_prefix = "/data/authRequest")
  app.register_blueprint(DataUser, url_prefix = "/data/user")
  app.register_blueprint(DataShop, url_prefix = "/data/shop")
  app.register_blueprint(DataDoc, url_prefix = "/data/doc")
  app.register_blueprint(DataProduct, url_prefix = "/data/product")
  return app
コード例 #4
0
ファイル: auth.py プロジェクト: x3mSpeedy/PyRest
class Auth (object):
    """
    Class which handles auth process
    """
    def __init__(self, app):
        """Static initialization"""
        self.app = app
        self.login_manager = LoginManager ()
        self.login_manager.init_app (app)
        self.login_manager.user_loader (self.load_user)

        self.users = { }

    def login_user (self, user):
        """Login given user"""
        if user is not None:
            self.users[user.session_id] = user
            return login_user (user)
        return None

    def load_user (self, session_id):
        """Loads user by user_id or return None"""

        if session_id in self.users:
            return self.users[session_id]
        return None


    def logout_user (self):
        """Logout current user"""
        return logout_user ()
コード例 #5
0
def create_app(_config_file=os.path.join(os.getcwd(), 'settings.cfg')):
    # Create Flask app
    global app
    app = Flask("CheshireCat")

    # Load configuration file
    configspec = ConfigObj(os.path.join(os.getcwd(), 'configspec.cfg'), list_values=False)
    config = ConfigObj(_config_file, configspec=configspec)
    test = config.validate(Validator(), copy=True)
    for key in config['CORE']:
        app.config[key] = config['CORE'][key]

    # Change the session interface to be more secure and portalble than the default
    # which is provided by Werkzeug.
    # These break the engine currently. I don't know why.
    #app.session_interface = RedisSignedSessionInterface()
    #app.session_interface = ItsdangerousSessionInterface()

    # Flask-Login manages user sessions for us, but we need to set it up first, so
    # we'll do so here.
    global login_manager
    login_manager = LoginManager()
    login_manager.init_app(app)

    # Initialize CheshireCat
    # Import the views, to apply the decorators which use the global app object.
    from . import views
コード例 #6
0
ファイル: __init__.py プロジェクト: ethaniz/flask_mongoengine
def init_login(app):
    login_manager = LoginManager()
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(user_id):
        from app.models import User
        return User.objects(id=user_id).first()
コード例 #7
0
ファイル: test_login.py プロジェクト: nmaekawa/flask-login
 def test_no_user_loader_raises(self):
     login_manager = LoginManager(self.app, add_context_processor=True)
     with self.app.test_request_context():
         session['user_id'] = '2'
         with self.assertRaises(Exception) as cm:
             login_manager.reload_user()
         expected_exception_message = 'No user_loader has been installed'
         self.assertTrue(
             str(cm.exception).startswith(expected_exception_message))
コード例 #8
0
class ApplicationCore(object):

    def __init__(self, app):
        self.initialize_login(app)

    def initialize_login(self, app):
        self.login_manager = LoginManager()
        self.login_manager.init_app(app)
        self.login_manager.login_view = 'login'
コード例 #9
0
ファイル: core.py プロジェクト: wang1219/first
def configure_flask_login(app):
    login_manager = LoginManager()
    login_manager.login_view = 'default.login'

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

    login_manager.init_app(app)
コード例 #10
0
 def setUp(self):
     self.app = app.test_client()  # creates a test client
     self.app.testing = True
     #library = Library('Детскя библиотека №28')
     app.secret_key = 'strong SecReT Key 123123123!'
     #app.config['SESSION_TYPE'] = 'filesystem'  # http://stackoverflow.com/a/26080974
     login_manager = LoginManager()
     login_manager.init_app(app)
     login_manager.login_view = 'login'
コード例 #11
0
ファイル: __init__.py プロジェクト: kelliedlynch/novella-web
def configure_extensions(app):
    login_manager = LoginManager()
    login_manager.init_app(app)

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

    db.init_app(app)
    bcrypt.init_app(app)
コード例 #12
0
ファイル: init.py プロジェクト: Patrickctyyx/flask-site
def get_login_manager():
    global _login_manager

    if not _login_manager:
        from flask_login import LoginManager

        _login_manager = LoginManager()
        _login_manager.init_app(current_app)

    return _login_manager
コード例 #13
0
ファイル: test_login.py プロジェクト: nmaekawa/flask-login
    def test_static_loads_anonymous(self):
        app = Flask(__name__)
        app.static_url_path = '/static'
        app.secret_key = 'this is a temp key'
        lm = LoginManager()
        lm.init_app(app)

        with app.test_client() as c:
            c.get('/static/favicon.ico')
            self.assertTrue(current_user.is_anonymous)
コード例 #14
0
def test_get_locale_anonymous_user(app):
    """Test anonymous user locale selection by default."""
    app.secret_key = 'secret key'
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'login'
    InvenioI18N(app)

    with app.test_request_context():
        assert 'en' == get_locale()
コード例 #15
0
ファイル: webapp.py プロジェクト: hejin1026/extend104-web
def config_login_mgr(app):
    login_mgr = LoginManager()
    login_mgr.login_view = 'user.login'
    login_mgr.login_message = u'请先登录系统.'
    
    @login_mgr.user_loader
    def load_user(id):
        return User.query.get(id)

    login_mgr.init_app(app)
コード例 #16
0
def init_login_system(app):
    app.session_interface = SQLAlchemySessionInterface(app.config)
    login_manager = LoginManager()
    login_manager.init_app(app)

    @login_manager.unauthorized_handler
    def unauthorized():
        raise errors.NotAuthorized()

    login_manager.user_callback = load_user
コード例 #17
0
ファイル: __init__.py プロジェクト: sapetnioc/cati_manager
def create_app(test_config=None):
    # Some submodules are used in an environement without thirdparty module installed.
    # Therefore flask cannot be used at module level.
    from flask import Flask
    from flask_login import LoginManager

    from cati_portal.http.authentication import User

    logging.config.dictConfig({
        'version': 1,
        'formatters': {'default': {
            'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
        }},
        'handlers': {'wsgi': {
            'class': 'logging.handlers.WatchedFileHandler',
            'formatter': 'default',
            'filename': '/cati_portal/log/cati_portal.log',
        }},
        'root': {
            'level': 'INFO',
            'handlers': ['wsgi']
        }
    })
    # create and configure the app
    app = Flask(__name__, instance_path='/cati_portal/flask_instance', instance_relative_config=True)
    secret_key_file = osp.join(os.environ.get('CATI_PORTAL_DIR', '/cati_portal'), 'pgp', 'secret.key')
    app.secret_key = open(secret_key_file, 'rb').read()

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_json('config.json')
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

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

    login_manager.user_loader(partial(User.get, bypass_access_rights=True))

    app.jinja_env.add_extension('jinja2.ext.do')

    from . import db
    db.init_app(app)

    from .http import authentication
    app.register_blueprint(authentication.bp)

    from .http import home
    app.register_blueprint(home.bp)

    from .http import settings
    app.register_blueprint(settings.bp)

    return app
コード例 #18
0
ファイル: app.py プロジェクト: Alex961120/louplus-python
def register_extensions(app):
    db.init_app(app)
    Migrate(app, db)
    login_manager = LoginManager()
    login_manager.init_app(app)

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

    login_manager.login_view = 'front.login'
コード例 #19
0
ファイル: test_login.py プロジェクト: nmaekawa/flask-login
    def test_static_loads_without_accessing_session(self):
        app = Flask(__name__)
        app.static_url_path = '/static'
        app.secret_key = 'this is a temp key'
        lm = LoginManager()
        lm.init_app(app)

        with app.test_client() as c:
            with listen_to(user_accessed) as listener:
                c.get('/static/favicon.ico')
                listener.assert_heard_none(app)
コード例 #20
0
ファイル: utils.py プロジェクト: EricSchles/Flask-Foundation
class UserManager(Blueprint):

    def __init__(self, *args, **kwargs):
        self._login_manager = None
        self._principal = None
        self.app = None
        super(UserManager, self).__init__(*args, **kwargs)

    def register(self, app, *args, **kwargs):
        " Activate loginmanager and principal. "

        if not self._login_manager or self.app != app:
            self._login_manager = LoginManager()
            self._login_manager.user_callback = self.user_loader
            self._login_manager.init_app(app)
            self._login_manager.login_view = app.config.get('AUTH_LOGIN_VIEW', 'code.index')
            self._login_manager.login_message = u'You need to be signed in for this page.'

        self.app = app

        if not self._principal:
            self._principal = Principal(app)
            identity_loaded.connect(self.identity_loaded)

        super(UserManager, self).register(app, *args, **kwargs)

    @staticmethod
    def user_loader(pk):
        return User.query.options(db.joinedload(User.roles)).get(pk)

    @staticmethod
    def login_required(fn):
        return login_required(fn)

    def logout(self):
        identity_changed.send(self.app, identity=AnonymousIdentity())
        return logout_user()

    def login(self, user):
        identity_changed.send(self.app, identity=Identity(user.id))
        return login_user(user)

    @staticmethod
    def identity_loaded(sender, identity):
        identity.user = current_user

        # Add the UserNeed to the identity
        if current_user.is_authenticated():
            identity.provides.add(UserNeed(current_user.id))

            # Assuming the User model has a list of roles, update the
            # identity with the roles that the user provides
            for role in current_user.roles:
                identity.provides.add(RoleNeed(role.name))
コード例 #21
0
ファイル: test_login.py プロジェクト: nmaekawa/flask-login
    def test_login_url_generation_with_view(self):
        app = Flask(__name__)
        login_manager = LoginManager()
        login_manager.init_app(app)

        @app.route('/login')
        def login():
            return ''

        with app.test_request_context():
            self.assertEqual('/login?next=%2Fprotected',
                             login_url('login', '/protected'))
コード例 #22
0
ファイル: create_app.py プロジェクト: ajabo/formspree
def configure_login(app):
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'register'

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

    @app.before_request
    def before_request():
        g.user = current_user
コード例 #23
0
ファイル: login_view_ut.py プロジェクト: vollov/login-demo
    def setUp(self):
        login_test.app.config['TESTING'] = True
        login_test.app.config["REMEMBER_COOKIE_DURATION"] = timedelta(days=14)
        
        self.app = login_test.app.test_client()
        self.app.secret_key = configuration.get('auth', 'secret_key')
        login_serializer = URLSafeTimedSerializer(self.app.secret_key)
        login_manager = LoginManager()

        
        login_manager.login_view = "/login"
        #Setup the login manager.
        login_manager.setup_app(self.app)
コード例 #24
0
ファイル: __init__.py プロジェクト: huoyingdk/open_dnsdb
def init_login_manager():
    login_manager = LoginManager()
    login_manager.session_protection = 'strong'
    login_manager.login_view = 'auth.login'

    from dnsdb_common.dal.models.user import User, AnonymousUser
    login_manager.anonymous_user = AnonymousUser

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

    return login_manager
コード例 #25
0
ファイル: __init__.py プロジェクト: Bonifacio2/pyweb
def init_login():
    login_manager = LoginManager()
    login_manager.init_app(app)
    user_service = UserService(db)
    user_service.initialize_users()

    # Create user loader function
    @login_manager.user_loader
    def load_user(user_id):
        if (user_id):
        	return User(user_id)
        else:
        	return None
コード例 #26
0
ファイル: __init__.py プロジェクト: LeeTZ/SoPaper
def get_app():
    """load API modules and return the WSGI application"""
    global get_app, _app, login_manager
    _app = Flask(__name__)
    _app.config.from_object(DefaultConfig())
    _app.secret_key = 'WTF is this!!'       # Should have this to work

    login_manager = LoginManager()
    login_manager.init_app(_app)

    import_all_modules(__file__, __name__)
    get_app = lambda: _app
    return _app
コード例 #27
0
ファイル: __init__.py プロジェクト: vinx13/sjtuface-web
def init_login(app):
    login_manager = LoginManager()
    login_manager.init_app(app)

    # Create user loader function
    @login_manager.user_loader
    def load_user(user_id):
        from .core.models import User
        return db.session.query(User).get(user_id)

    @login_manager.unauthorized_handler
    def unauthorized():
        return redirect(url_for("sjtuface.login"))
コード例 #28
0
ファイル: app.py プロジェクト: hezhenpan/jobplus6-3
def register_extensions(app):
    # 数据库初始化
    db.init_app(app)

    # 创建登录组件
    login_manager = LoginManager()
    login_manager.init_app(app)

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

    login_manager.login_view = 'front.login'
コード例 #29
0
ファイル: create_app.py プロジェクト: fiatjaf/formspree
def configure_login(app):
    login_manager = LoginManager()
    login_manager.init_app(app)

    @login_manager.unauthorized_handler
    def unauthorized():
        if request_wants_json() or request.path.startswith("/api-int/"):
            return jsonify({"error": "User not logged."}), 401
        return redirect(url_for("login"))

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))
コード例 #30
0
ファイル: web.py プロジェクト: syncloud/files
def create_web_app(data_dir):
    config = BrowserConfig(data_dir)

    logger.init(logging.INFO, False, join(config.get_browser_log()))

    browser = Browser(config)

    app = Flask(__name__)
    app.config['SECRET_KEY'] = config.get_web_secret_key()
    login_manager = LoginManager()
    login_manager.init_app(app)


    html_prefix = ''
    rest_prefix = '/rest'


    @login_manager.unauthorized_handler
    def _callback():
        if request.is_xhr:
            return 'Unauthorised', 401
        else:
            return redirect(html_prefix + '/login.html')


    @app.route(html_prefix + '/<path:filename>')
    @nocache
    def static_file(filename):
        return send_from_directory(config.www_root(), filename)


    @login_manager.user_loader
    def load_user(email):
        return FlaskUser(User(email))


    @app.route(rest_prefix + "/login", methods=["GET", "POST"])
    def login():

        if 'name' in request.form and 'password' in request.form:
            try:
                authenticate(request.form['name'], request.form['password'])
                user_flask = FlaskUser(User(request.form['name']))
                login_user(user_flask, remember=False)
                # next_url = request.get('next_url', '/')
                return redirect("/")
            except Exception, e:
                traceback.print_exc(file=sys.stdout)
                return jsonify(message=e.message), 400

        return jsonify(message='missing name or password'), 400
コード例 #31
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from config import Config

app = Flask(__name__)
app.config.from_object(Config)

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

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

from app import routes, models
コード例 #32
0
ファイル: __init__.py プロジェクト: ibuckhold/W18-D3-OrderUp
from flask import Flask
from .config import Configuration
from .routes import orders
from .models import db
from flask_login import LoginManager
from .models import db, Employee
from .routes import session

app = Flask(__name__)
app.config.from_object(Configuration)
app.register_blueprint(orders.bp)
app.register_blueprint(session.bp)

db.init_app(app)

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


@login.user_loader
def load_user(id):
    return Employee.query.get(int(id))
コード例 #33
0
ファイル: __init__.py プロジェクト: SHREYANKKK/SpareMate
from flask_login import LoginManager, login_required, login_user, logout_user
from flask_migrate import Migrate
from flask_msearch import Search

import os

basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.secret_key = 'eeeopopdopeppokakospkoapkaopap'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///final_db.db'
db = SQLAlchemy(app)
app.config['UPLOADED_PHOTOS_DEST'] = os.path.join(basedir, 'static/images')
photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'customerLogin'
login_manager.needs_refresh_message_category = 'danger'
login_manager.login_message = u"Please login first"
db = SQLAlchemy(app)
brcypt = Bcrypt(app)

search = Search()
search.init_app(app)
migrate = Migrate(app, db)
with app.app_context():
    if db.engine.url.drivername == "sqlite":
        migrate.init_app(app, db, render_as_batch=True)
    else:
        migrate.init_app(app, db)
コード例 #34
0
"""
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from config import Config
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail

app = Flask(__name__)
bootstrap = Bootstrap(app)
app.config.from_object(Config)
app.config[
    'JSONIFY_MIMETYPE'] = "application/json;charset=utf-8"  #指定浏览器渲染的文件类型,和解码格式;
app.config['JSON_AS_ASCII'] = False
db = SQLAlchemy(app)

bcrypt = Bcrypt(app)

login = LoginManager(app)
login.login_view = 'login'
login.login_message = '你需要登录才能访问此页面。'
login.login_message_category = 'info'

mail = Mail(app)

from app.routes import *

# 添加蓝图
from .admin.view import admin_blueprint
app.register_blueprint(admin_blueprint, url_prefix='/admin')
コード例 #35
0
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_babel import Babel, lazy_gettext as _l
from config import Config
from elasticsearch import Elasticsearch
from redis import Redis
import rq

db = SQLAlchemy()
migrate = Migrate()
login = LoginManager()
login.login_view = 'auth.login'
login.login_message = _l('Please log in to access this page.')
mail = Mail()
bootstrap = Bootstrap()
moment = Moment()
babel = Babel()


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)
コード例 #36
0
ファイル: __init__.py プロジェクト: AshishBadgujar/Flask-Blog
from flask import Flask
from flask_bcrypt import Bcrypt
from flask_login import LoginManager

app=Flask(__name__)

app.config['SECRET_KEY']='b3b0409d3946ce228b90650845a54f64'

bcrypt=Bcrypt(app)
login_manager=LoginManager(app)

from flask_blog import routes

コード例 #37
0
ファイル: app.py プロジェクト: mrseph34/Final-Project-2021
mail= Mail(app)

app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = '******'
app.config['MAIL_PASSWORD'] = '******'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)

def resetPassword(email,tempPass):
    msg = Message('Hello', sender = '*****@*****.**', recipients = [email])
    msg.body = "Hello Hoots user, your password has been set to the following temporary password please login and change as you please. __"+tempPass+"__"
    mail.send(msg)

login_manager = LoginManager(app)
login_manager.login_view = "login"

class User(UserMixin):
    def __init__(self,email):
         self.email = email
         self.authenticated = False
    def is_active(self):
         return self.is_active()
    def is_anonymous(self):
         return False
    def is_authenticated(self):
         return self.authenticated
    def is_active(self):
         return True
    def get_id(self):
コード例 #38
0
ファイル: app.py プロジェクト: kadr/simbir_soft
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

from flask_redis import FlaskRedis

from config import Config

app = Flask(__name__)

app.config.from_object(Config)
redis: FlaskRedis = FlaskRedis(app)
db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'user.login'
コード例 #39
0
ファイル: __init__.py プロジェクト: miyarChen/exercise
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from config import config
from flask_login import LoginManager
from flask_pagedown import PageDown

bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
pagedown = PageDown()

login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.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)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    pagedown.init_app(app)

    login_manager.init_app(app)
コード例 #40
0
import os
from flask import Flask
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect

from config import config

csrf = CSRFProtect()
db = SQLAlchemy()
config = config[os.getenv("APP_CONFIG", "default")]
login_manager = LoginManager()
moment = Moment()


def create_app():
    app = Flask(__name__)

    config.init_app(app)

    csrf.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.session_protection = "strong"
    login_manager.login_view = "auth.login"
    Migrate(app, db)
    moment.init_app(app)

    if not app.debug and not app.testing:
コード例 #41
0
#!/usr/bin/env python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_mail import Mail

app = Flask(__name__)
app.config.from_object(__name__ + '.config.ConfigClass')

login_manager = LoginManager()
login_manager.init_app(app)

db = SQLAlchemy(app)
mail = Mail(app)

from app import views
コード例 #42
0
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView


#######################
#### Configuration ####
#######################


# Create the instances of the Flask extensions (flask-sqlalchemy, flask-login, etc.) in
# the global scope, but without any arguments passed in.  These instances are not attached
# to the application at this point.
db = SQLAlchemy()
bcrypt = Bcrypt()
mail = Mail()
login = LoginManager()
login.login_view = "users.login"


######################################
#### Application Factory Function ####
######################################
 
def create_app(config_filename=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_pyfile(config_filename)
    initialize_extensions(app)
    register_blueprints(app)
    return app

##########################
コード例 #43
0
sys.path.insert(0,'./crud')
from flask import Flask, render_template,request,redirect,url_for,send_file,Response
from flask_login import LoginManager, login_required, login_user, logout_user, current_user
import json
import uuid
import os
import registration
import read,insert,delete,update
from flask import jsonify
import re 
from models import User, Filedetails
from configuration.config import SECRET_KEY
from audio_converter import video_to_audio
import speech_to_text
#Initialising flask login manager
login_manager = LoginManager()
#Initialising Flask app
app=Flask(__name__,static_url_path='')

#################################### Flask Authorisation Initialisation ##################################


login_manager.init_app(app)
login_manager.login_view = "onboardingpage"
@login_manager.user_loader
def user_loader(id):
        user=registration.user_loader(id)
        return user
@login_manager.unauthorized_handler
def unauthorized_handler():
    return redirect(url_for('onboarding_page_with_notification',notification='Please login to gain access.'),code=302)
コード例 #44
0
ファイル: todoapp.py プロジェクト: Arnav-Tracxn/R-nav
from datetime import datetime
from flask import Flask,session, request, flash, url_for, redirect, render_template, abort ,g
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_login import login_user , logout_user , current_user , login_required
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
app.config.from_pyfile('todoapp.cfg')
db = SQLAlchemy(app)

login_manager = LoginManager()
login_manager.init_app(app)

login_manager.login_view = 'login'

class User(db.Model):
    __tablename__ = "users"
    id = db.Column('user_id',db.Integer , primary_key=True)
    username = db.Column('username', db.String(20), unique=True , index=True)
    password = db.Column('password' , db.String(250))
    email = db.Column('email',db.String(50),unique=True , index=True)
    registered_on = db.Column('registered_on' , db.DateTime)
    todos = db.relationship('Todo' , backref='user',lazy='dynamic')

    def __init__(self , username ,password , email):
        self.username = username
        self.set_password(password)
        self.email = email
        self.registered_on = datetime.utcnow()
コード例 #45
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from easyhealth_app.config import Config
from flask_bcrypt import Bcrypt
import os

app = Flask(__name__)
app.config.from_object(Config)
app.secret_key = os.urandom(24)

db = SQLAlchemy()
bcrypt = Bcrypt(app)
login_manager = LoginManager()
login_manager.session_protection = "strong"
login_manager.login_view = "patients.login"

from .models import User


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


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

    db.init_app(app)
    login_manager.init_app(app)
コード例 #46
0
ファイル: __init__.py プロジェクト: gtcooke94/flask_tutorial
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)

# This forces unlogged users to to login page if they try to view a page that
# we only want logged in users to see. We specificy these pages with the
# @login_required decorated imported from flask_login
login.login_view = "login"

from app import routes, models, errors

# python -m smtpd -n -c DebuggingServer localhost:8025
# Above command will run a fake email server that accepts emails, but instead
# of sending them will print them to the console
# See .flask_env for how we would setup a gmail account email server
if not app.debug:
    if app.config["MAIL_SERVER"]:
        auth = None
        if app.config["MAIL_USERNAME"] or app.config["MAIL_PASSWORD"]:
            auth = (app.config["MAIL_USERNAME"], app.config["MAIL_PASSWORD"])
コード例 #47
0
import os
from flask_login import LoginManager
from datetime import datetime
from flask import Flask, render_template
import views
from user import get_user
from database import Database
from employee import Employee
from jobtitle import Jobtitle
from level import Level
from service import Service

lm = LoginManager()


@lm.user_loader
def load_user(user_id):
    return get_user(user_id)


def create_app():
    app = Flask(__name__)
    app.config.from_object("settings")

    app.add_url_rule("/", view_func=views.home_page)
    app.add_url_rule("/login",
                     view_func=views.login_page,
                     methods=["GET", "POST"])
    app.add_url_rule("/logout", view_func=views.logout_page)

    app.add_url_rule("/employees",
コード例 #48
0
from flask_login import (LoginManager, UserMixin, login_user, login_required,
                         logout_user, current_user)
from datetime import datetime
import json

from app import app, db
from parks_db import Exh_art_park, Exhibition, Park, Artwork, Artist, Org, exh_org
from forms import (Form_artist, Form_exhibition, Form_artwork, Form_park,
                   Form_org, Form_user, Form_signup, Form_search,
                   Form_import_file, Form_import_data)
from users import User
from model_import import import_csv, read_csv_heads, export_csv
from add_models import add_exhibition

# Flask-login settings
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.session_protection = 'strong'
login_manager.login_view = 'login'


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


@app.template_filter('date_format')
def date_format(value, format='%m/%d/%Y'):
    if value is not None:
        return value.strftime(format)
コード例 #49
0
ファイル: app.py プロジェクト: haozhi88/next-project
import os
import config
from flask import Flask
from flask_jwt_extended import JWTManager
from models.base_model import db
from flask_login import LoginManager
from models.user import User

login_manager = LoginManager()

web_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                       'instagram_web')

app = Flask('NEXTAGRAM', root_path=web_dir)
login_manager.init_app(app)
login_manager.login_view = 'sessions.new'
login_manager.login_message = 'Please login before proceeding...'
login_manager.login_message_category = "warning"

jwt = JWTManager(app)

if os.getenv('FLASK_ENV') == 'production':
    app.config.from_object("config.ProductionConfig")
else:
    app.config.from_object("config.DevelopmentConfig")


@app.before_request
def before_request():
    db.connect()
コード例 #50
0
from application.campaigns import models
from application.campaigns import views
from application.npcs import models
from application.npcs import views

from application.auth import models
from application.auth import views

from application.auth.models import Account
from os import urandom

app.config["SECRET_KEY"] = urandom(32)

from flask_login import LoginManager

login_manager = LoginManager()
login_manager.init_app(app)

login_manager.login_view = "auth_login"
login_manager.login_message = "Please login to use this functionality."


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


try:
    db.create_all()
except:
    pass
コード例 #51
0
ファイル: __init__.py プロジェクト: altaher991/tesWebCopy
load_dotenv('.env')

# Flask instance
app = Flask(__name__)
bc = Bcrypt(app)

# Configs
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DB_URI')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['CSRF_ENABLED'] = True
app.config['USER_ENABLE_EMAIL'] = False

# Database instance
db = SQLAlchemy(app)
login_manager = LoginManager(app)
ma = Marshmallow(app)
mail = Mail(app)

login_manager.login_view = 'users.login'
login_manager.login_message = ''

# import models
from app.courses.models import ClassCode, Course, ClassCourses
from app.users.models import User, Student
from app.schools.models import School
from app.quiz.models import Quiz

# blueprints
from app.courses.routes import courses
from app.pages.routes import pages
コード例 #52
0
ファイル: __init__.py プロジェクト: ssgwy/learnweb
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager    #引用login
from flask_mail import Mail             #发送邮件的引用
from gonghui.config import Config

db = SQLAlchemy()
migrate = Migrate()
login_manager = LoginManager()          #login关联
login_manager.login_view = 'login'      #强制登录的重定向设置
mail = Mail()             #关联发送邮件

from gonghui.route import index,login,logout,manageruser,register,password_reset_request,\
password_reset,account_add,account_query,condolence,condolence_add,test,page_not_found,member_manager,\
    membership_list,membership_roster,buju,accounts

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)    
    db.init_app(app)
    migrate.init_app(app,db)
    login_manager.init_app(app)          #login与app关联
    mail.init_app(app)                #login与app关联  
    app.add_url_rule('/index','index',index)
    app.add_url_rule('/','index',index)
    app.add_url_rule('/login','login',login,methods=['GET','POST'])
    app.add_url_rule('/logout','logout',logout)
    app.add_url_rule('/manageruser','manageruser',manageruser)    
    app.add_url_rule('/register','register',register,methods=['GET','POST'])
    app.add_url_rule('/password_reset_request','password_reset_request',password_reset_request,methods=['GET','POST'])
コード例 #53
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager

app = Flask(__name__)

app.config[
    'SECRET_KEY'] = '8aba241acf4a2a43e0b86caf03a04103ace610462282754aadb29a29b7cd0e04'
#app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'

db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
loginManager = LoginManager(app)
loginManager.login_view = "login"
loginManager.login_message_category = "info"
from FlaskApplication import routes
コード例 #54
0
import os
from flask import Flask
from .config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__,
            static_folder=os.path.join(basedir, "web_app", "static"),
            template_folder=os.path.join(basedir, "web_app", "templates"))

app.config.from_object(Config())
db = SQLAlchemy(app)
login = LoginManager(app)

from .web_app import main, import_cwl, create_job, job_exec, users, browse


def setup_db():
    global app
    global db
    if app.config['ENABLE_USERS']:
        from .users.db import User
    from .exec.db import Exec
    db.init_app(app)
    db.create_all()
    db.session.commit()
    if app.config['ENABLE_USERS']:
        from .users.manage import get_users, interactively_add_user
コード例 #55
0
ファイル: __init__.py プロジェクト: maxUser/flask_blog
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
from flaskblog.config import Config

# Extensions
db = SQLAlchemy()
bcrypt = Bcrypt()
login_manager = LoginManager()
login_manager.login_view = 'users.login'
login_manager.login_message_category = 'info'
mail = Mail()


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

    db.init_app(app)
    bcrypt.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)

    from flaskblog.users.routes import users
    from flaskblog.posts.routes import posts
    from flaskblog.main.routes import main
    app.register_blueprint(users)
    app.register_blueprint(posts)
    app.register_blueprint(main)
コード例 #56
0
ファイル: extensions.py プロジェクト: ammoam/eNMS
from flask_assets import Environment
from flask_httpauth import HTTPBasicAuth
from flask_login import LoginManager
from flask_wtf.csrf import CSRFProtect

assets = Environment()
auth = HTTPBasicAuth()
csrf = CSRFProtect()
login_manager = LoginManager()
login_manager.session_protection = "strong"
コード例 #57
0
from flask_login import LoginManager

app = Flask(__name__)
app.config['SECRET_KEY'] = '7f90408af1b0e368ac19c775e5e892ef'

# Value to switch between development and production
ENV = 'dev'

if ENV == 'dev':
    app.debug = True
    # development database
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@ssw1rd@localhost/budget'
else:
    # deployment database
    app.debug = False
    app.config['SQLALCHEMY_DATABASE_URI'] = ''

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Create database instance
db = SQLAlchemy(app)
# Create bcrypt instance
bcrypt = Bcrypt(app)
# Create loginmanager instance
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'

from budgetapp import routes
コード例 #58
0
from flask import redirect, url_for
from flask_login import LoginManager, current_user
from metabrainz.model.user import User
from functools import wraps

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


@login_manager.user_loader
def load_user(user_id):
    return User.get(id=user_id)


def login_forbidden(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if current_user.is_anonymous() is False:
            return redirect(url_for('index.home'))
        return f(*args, **kwargs)

    return decorated
コード例 #59
0
ファイル: __init__.py プロジェクト: ChengleiYuan/ccnubt
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import redis

db = SQLAlchemy(use_native_unicode='utf8')
login_manager = LoginManager()
login_manager.login_view = "auth.login"
store = redis.StrictRedis()
コード例 #60
0
ファイル: room.py プロジェクト: SketchMaster2001/room-server
from elasticsearch import Elasticsearch
from flask import Flask, session, request
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_migrate import Migrate
from werkzeug import exceptions

import config

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = config.db_url
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SECRET_KEY"] = config.secret_key

login = LoginManager()

es = Elasticsearch(config.elasticsearch_url)

# Ensure DB tables are created.
# Importing models must occur after the DB is instantiated.
# It must not initialize around an app so that we can create
# models automatically within a test context.
db = SQLAlchemy()
import models

# Ensure the DB is able to determine migration needs.
migrate = Migrate(app, db, compare_type=True)
with app.test_request_context():
    db.init_app(app)
    db.create_all()