Ejemplo n.º 1
0
def create_app(config):

    app = Flask(__name__, static_url_path='', static_folder=STATIC_PATH)
    init_app_config(app, config)
    init_logger(app)

    app.url_map.strict_slashes = False

    lm = LoginManager()
    lm.unauthorized_handler(basic_unauthorized)
    lm.init_app(app)
    lm.user_loader(load_user)
    lm.session_protection = "strong"
    # this patch needs because chrome will ignore cookies when using ip.
    app.session_interface.get_cookie_domain = lambda _app: None

    flex = FlexRestManager(db_base=Base, db_session_callback=global_session)
    flex.init_app(app)

    register_blueprints(app, BLUEPRINTS)

    @app.after_request
    def after_request(response):
        dbs = global_session(create=False)
        dbs and dbs.close()
        return response

    @app.route('/favicon.ico')
    def favicon():
        return app.send_static_file('images/favicon.ico')

    return app
Ejemplo n.º 2
0
def get_login_manager(app):
    lm = LoginManager(app)
    lm.session_protection = 'strong'
    lm.anonymous_user = AnonymousUser
    lm.login_view = '/login'
    lm.user_loader(load_user)
    lm.token_loader(load_token)
    lm.init_app(app)
    return lm
Ejemplo n.º 3
0
Archivo: models.py Proyecto: ptmono/ppf
def init_login(app):
    login_manager = LoginManager()
    login_manager.session_protection = "strong"
    login_manager.init_app(app)
    

    @login_manager.user_loader
    def load_user(user_id):
        return db.session.query(User).get(user_id)
Ejemplo n.º 4
0
def create_app(app, config):
    app.config.update(SECRET_KEY=config['key']['SECRET_KEY'], SQLALCHEMY_DATABASE_URI=config['app']['SQLALCHEMY_DATABASE_URI'],
                      DEBUG=config['app']['DEBUG'])

    login_manager = LoginManager()
    login_manager.session_protection = config['login_manager']['SESSION_PROTECTION']
    login_manager.login_view = config['login_manager']['LOGIN_VIEW']
    login_manager.init_app(app)

    return login_manager
Ejemplo n.º 5
0
def init_login(app):
    login_manager = LoginManager()
    login_manager.session_protection = 'strong'
    login_manager.login_view = 'manage.login'
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(user_id):
        from app.core.models import User
        return User.query.get(int(user_id))
Ejemplo n.º 6
0
def register_loginhooks(app):
    from flask.ext.login import LoginManager
    from flask import current_app
    import arrow
    from redisconfig import LOGON_CACHE_DATA
    from redisapp import hsetRedisKeys

    login_manager = LoginManager()
    login_manager.session_protection = "strong"
    login_manager.login_view = "userview.login"
    login_manager.init_app(app)

    from module.user.user import User as UserModule

    @login_manager.user_loader
    def load_user(id):
        user = UserModule.query.get(id)
        if user:
            if current_app.config['REDIS_CACHE']:
                now = arrow.utcnow().to('local')
                logon = {
                    'key': LOGON_CACHE_DATA.KEY.format(dayid=now.format('YYYYMMDD')),
                    'field': LOGON_CACHE_DATA.FIELD.format(user=user.id),
                    'data': now.timestamp
                }
                hsetRedisKeys(logon)

            return user
        return None

    @login_manager.token_loader
    def load_token(token):
        max_age = app.config['REMEMBER_COOKIE_DURATION'].total_seconds()
        from utils.Token import Token
        t = Token('user')
        data = t.loads(token, maxage=max_age)
        user = UserModule.query.get(data[0])
        if user and user.email == data[1] and user.password == data[2]:
            param = {
                'ip': request.remote_addr,
                'agent': request.user_agent
            }

            if current_app.config['REDIS_CACHE']:
                now = arrow.utcnow().to('local')
                logon = {
                    'key': LOGON_CACHE_DATA.KEY.format(dayid=now.format('YYYYMMDD')),
                    'field': LOGON_CACHE_DATA.FIELD.format(user=user.id),
                    'data': now.timestamp
                }
                hsetRedisKeys(logon)

            user.logger(**param)
            return user
        return None
Ejemplo n.º 7
0
def init_login(app):
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.session_protection = 'strong'
    login_manager.login_view = 'views.loginin'
    # Create user loader function

    @login_manager.user_loader
    def load_user(user_id):
        from apps.models import User
        return User.query.get(int(user_id))
Ejemplo n.º 8
0
def configure_extensions(app):
    #from simplekv.memory import DictStore
    #from flask.ext.kvsession import KVSessionExtension
    #store = DictStore()
    ## this will replace the app's session handling
    #KVSessionExtension(store, app)
    mongo.init_app(app, "FUNFUNSAY")

    # cache
    cache.init_app(app)

    # babel
    #print "create babel object"
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        # if a user is logged in, use the locale from the user settings
        if current_user.is_authenticated():
            return current_user.locale
        # otherwise try to guess the language from the user accept
        # header the browser transmits.  We support de/fr/en in this
        # example.  The best match wins.
        return request.accept_languages.best_match(['zh_CN', 'en'])

    @babel.timezoneselector
    def get_timezone():
        if current_user.is_authenticated():
            return current_user.timezone
        return app.config['BABEL_DEFAULT_TIMEZONE']

    # login.
    from flask.ext.login import LoginManager
    login_manager = LoginManager()    
    login_manager.session_protection = None #@fixme!
    login_manager.login_view = 'homesite.login'
    login_manager.refresh_view = 'homesite.reauth'
    login_manager.login_message = _("Please log in to access this page.")

    @login_manager.user_loader
    def load_user(id):
        #print "####: loaduser ", id
        return User.load_user(id)
    login_manager.setup_app(app)

    from flask.ext.markdown import Markdown
    Markdown(app, safe_mode="escape")
Ejemplo n.º 9
0
def make_app(import_name=__name__, config="homebank.settings.Configuration", debug=False):

    app = Flask(import_name)
    app.config.from_object(config)
    app.config.from_envvar("FLASK_SETTINGS", silent=True)
    app.debug = debug
    app.jinja_env.filters["currency"] = lambda x: "{:,.2f} %s".format(x).replace(",", " ").replace(".", ",") % (
        app.config.get("CURRENCY", "")
    )

    if app.debug:
        import_string("flask.ext.debugtoolbar:DebugToolbarExtension")(app)

    @app.errorhandler(404)
    def not_found(ex):
        return render_template("404.html"), 404

    for blueprint in ["__init__", "accounts", "transactions"]:
        app.register_blueprint(import_string("homebank.blueprints.%s:root" % blueprint))

    login_manager = LoginManager(app=app)
    login_manager.login_view = "index.login"
    login_manager.session_protection = "strong"

    @login_manager.user_loader
    def load_user(uid):
        if uid != app.config["PINCODE"]:
            return None
        return User()

    if not app.debug:
        handler = StreamHandler()
        if "ERROR_LOG" in app.config:
            handler = WatchedFileHandler(app.config["ERROR_LOG"])

        handler.setLevel(WARNING)
        handler.setFormatter(Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
        app.logger.addHandler(handler)

    return app
Ejemplo n.º 10
0
from flask import Flask, render_template, session
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from config import config
from flask.ext.login import LoginManager
from flask_debugtoolbar import DebugToolbarExtension
from flask.ext.mail import Mail


bootstrap = Bootstrap()
moment = Moment()
db = SQLAlchemy()
mail = Mail()
login_mgr = LoginManager()
login_mgr.session_protection = "strong"
login_mgr.login_view = "login"


def create_app(data):
    app = Flask(__name__)
    app.config.from_object(config[data])
    config[data].init_app(app)
    db.init_app(app)
    bootstrap.init_app(app)
    moment.init_app(app)
    login_mgr.init_app(app)
    mail.init_app(app)
    toolbar = DebugToolbarExtension(app)

    from main import main as main_bp
Ejemplo n.º 11
0
from celery import Celery
import phonenumbers

from config import config  # pylint: disable=relative-import
import loader  # pylint: disable=relative-import
import stylesheets  # pylint: disable=relative-import
# yapf: disable
from helpers import date_duration, sorted_sessions  # pylint: disable=relative-import
# yapf: enable

bootstrap = Bootstrap()
assets = Environment()
db = SQLAlchemy()

login_manager = LoginManager()
login_manager.session_protection = "basic"
login_manager.login_view = "auth.login"
limiter = Limiter(
    global_limits=["300 per minute"],
    key_func=lambda: request.headers.get("CF-Connecting-IP", request.
                                         remote_addr),
)

cache = Redis()

# Asset Packages
js_default_req = loader.default()
js_vendor_single_page_req = loader.vendor_single_page()
js_shared_single_page_req = loader.shared_single_page()
js_euler_app_req = loader.euler_app()
js_manager_app_req = loader.manager_app()
Ejemplo n.º 12
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.bcrypt import Bcrypt
from flask_restful import Resource, Api
import os

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

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'app.db')
app.config['SQLALCHEMY_MIGRATE_REPO'] = os.path.join(basedir, 'db_repository')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog'

db = SQLAlchemy(app)

flask_bcrypt = Bcrypt(app)
api = Api(app)

lm = LoginManager()
lm.init_app(app)
lm.session_protection = 'strong'
#lm.login_view = auth.login

from app import models, views, api
Ejemplo n.º 13
0
from flask.ext.bootstrap import Bootstrap    #Bootstrap
from flask.ext.mail import Mail              #邮件
from flask.ext.moment import Moment          #时间和日期 
from flask.ext.sqlalchemy import SQLAlchemy  #数据操作
from flask.ext.login import LoginManager     #用户登录


#初始化
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()

#初始化Flask-Login
login_manager = LoginManager()
login_manager.session_protection = 'strong' #设置安全级别为"strong",Flask-Login会记录客户端IP地址和浏览器的用户代理信息,如果发现异动就退出用户.
login_manager.login_view = 'auth.login'     #设置登录用户页面的端点.(登录路由在auth蓝本中定义,所以前面要加上蓝本的名字)


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)
Ejemplo n.º 14
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.bootstrap import Bootstrap
import os
from flask.ext.login import LoginManager
from flask.ext.openid import OpenID
from config import config

bootstrap = Bootstrap()
db = SQLAlchemy()
lm = LoginManager()
lm.session_protection = 'strong'
lm.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)
    db.init_app(app)
    lm.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')
Ejemplo n.º 15
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os

from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.bootstrap import Bootstrap
from flask.ext.login import LoginManager
from flask.ext.mail import Mail

basedir = os.path.abspath(os.path.dirname(__file__))
db = SQLAlchemy()
bootstrap = Bootstrap()
auth_manager = LoginManager()
auth_manager.session_protection = 'strong'
auth_manager.login_view = 'bp_authentication.login'
email = Mail()


class Config:
    SECRET_KEY = 'YOU WONT GUESS'
    SQLALCHEMY_COMMIT_ON_TEARDOWN = True
    TOKEN_EXPIRATION = 3600
    MAIL_SENDER = '*****@*****.**'
    DEFAULT_PAGE = 'bp_profile.profile-detail'
    UPLOAD_FOLDER = 'beattime/static/beattime/img/avatars'
    ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])


class DevConfig(Config):
    DEBUG = True
Ejemplo n.º 16
0
    def run(self):
        if not self._allowRoot:
            self._checkForRoot()
        global gcodeManager
        global userManager
        global eventManager
        global loginManager
        global debug

        from tornado.wsgi import WSGIContainer
        from tornado.httpserver import HTTPServer
        from tornado.ioloop import IOLoop
        from tornado.web import Application, FallbackHandler

        debug = self._debug

        # then initialize logging
        self._initLogging(self._debug)
        logger = logging.getLogger(__name__)

        eventManager = events.eventManager()
        gcodeManager = gcodefiles.GcodeManager()
        self.printer = Printer(gcodeManager)

        # configure timelapse
        octoprint.timelapse.configureTimelapse()

        # setup system and gcode command triggers
        events.SystemCommandTrigger(self.printer)
        events.GcodeCommandTrigger(self.printer)
        if self._debug:
            events.DebugEventListener()

        if settings.get("access_control", "enabled"):
            userManagerName = settings.get("access_control", "user_manager")
            try:
                clazz = util.getClass(userManagerName)
                userManager = clazz()
            except AttributeError as e:
                logger.exception(
                    "Could not instantiate user manager %s, will run with accessControl disabled!" % userManagerName)

        app.wsgi_app = ReverseProxied(app.wsgi_app)

        app.secret_key = settings.get('server', 'secret_key')
        if not app.secret_key:
            raise NoSecretKeyError()
        loginManager = LoginManager()
        loginManager.session_protection = "strong"
        loginManager.user_callback = load_user
        if userManager is None:
            loginManager.anonymous_user = users.DummyUser
            principals.identity_loaders.appendleft(users.dummy_identity_loader)
        loginManager.init_app(app)

        if self._host is None:
            self._host = settings.get("server", "host")
        if self._port is None:
            self._port = settings.get("server", "port")

        logger.info("Listening on http://%s:%d" % (self._host, self._port))
        app.debug = self._debug

        from octoprint.server.ajax import ajax
        from octoprint.server.api import api

        app.register_blueprint(ajax, url_prefix="/ajax")
        app.register_blueprint(api, url_prefix="/api")

        self._router = SockJSRouter(self._createSocketConnection, "/sockjs")

        self._tornado_app = Application(self._router.urls + [
            (r"/downloads/timelapse/([^/]*\.mpg)", LargeResponseHandler, {
             "path": settings.getpath("timelapse"), "as_attachment": True}),
            (r"/downloads/gcode/([^/]*\.(gco|gcode))", LargeResponseHandler, {
                "path": settings.getpath("uploads"), "as_attachment": True}),
            (r".*", FallbackHandler,
             {"fallback": WSGIContainer(app.wsgi_app)})
        ])
        self._server = HTTPServer(self._tornado_app)
        self._server.listen(self._port, address=self._host)

        eventManager.fire("Startup")
        if settings.get("serial", "autoconnect"):
            port, baudrate = (settings.get('serial', e) 
                              for e in ('port', 'baudrate'))
            connectionOptions = getConnectionOptions()
            if port in connectionOptions["ports"]:
                self.printer.connect(port, baudrate)
        try:
            IOLoop.instance().start()
        except:
            logger.fatal(
                "Now that is embarrassing... Something really really went"
                "wrong here. Please report this including the stacktrace below"
                "in OctoPrint's bugtracker. Thanks!")
            logger.exception("Stacktrace follows:")
Ejemplo n.º 17
0
def create_app(app_name, config_obj, with_api=True):
	""" Generates and configures the main shop application. All additional """
	# Launching application
	app = Flask(app_name) # So the engine would recognize the root package

	# Load Configuration
	app.config.from_object(config_obj)

	# Loading assets
	assets = Environment(app)
	assets.from_yaml('assets.yaml')
	app.assets = assets

	# Initialize Mail
	app.mail = Mail(app)

	# Initializing login manager
	login_manager = LoginManager()
	login_manager.login_view = app.config.get('LOGIN_VIEW', 'main.index')
	# login_manager.login_message = 'You need to be logged in to access this page'
	login_manager.session_protection = 'strong'
	login_manager.setup_app(app)
	app.login_manager = login_manager

	# Initializing principal manager
	app.principal = Principal(app)

	# Initializing bcrypt password encryption
	bcrypt = Bcrypt(app)
	app.bcrypt = bcrypt

	# Initializing Database
	db = SQLAlchemy(app)
	app.db = db

	# Initializing Migrate
	migrate = Migrate(app, db, "from fitted.models import *")
	app.migrate = migrate

	photos = UploadSet('photos', IMAGES)
	archives = UploadSet('archives', ARCHIVES)

	configure_uploads(app, (photos, archives))

	patch_request_class(app, 2 * 1024 * 1024) # Patches to 2MB file uploads max.

	app.photos = photos
	app.archives = archives

	# Integrate Elasticsearch

	es_config = app.config.get("ES_CONFIG", [])

	app.es = Elasticsearch(es_config)

	# Integrate sms with Twilio
	app.sms = TwilioRestClient(app.config.get("TWILIO_API_SID"), app.config.get("TWILIO_API_TOKEN"))


	# Redis store for session management
	# The process running Flask needs write access to this directory:
	# store = RedisStore(redis.StrictRedis())

	# # this will replace the app's session handling
	# KVSessionExtension(store, app)

	# configure sentry
	# if not app.config.get("DEBUG", False):
	# 	sentry = Sentry(app)

	# 	app.sentry = sentry

	# inject celery into the app
	app.celery = make_celery(app)

	# injecting mongodb support
	# app.mongo = PyMongo(app)

	# flask s3 integration
	app.s3 = FlaskS3(app)


	# Facebook & Twitter Integration
	app.facebook = oauth.remote_app('facebook',
		app_key='FACEBOOK'
	)


	oauth.init_app(app)



	# Initializing the restful API
	if with_api:
		api = restful.Api(app, prefix='/api/v1')
		app.api = api

	# Initialize Logging
	if not app.debug:
		import logging
		from logging.handlers import RotatingFileHandler
		file_handler = RotatingFileHandler("/var/log/fitted/%s.log" % app.config.get("LOGFILE_NAME", app_name), maxBytes=500*1024)
		file_handler.setLevel(logging.WARNING)
		from logging import Formatter
		file_handler.setFormatter(Formatter(
		    '%(asctime)s %(levelname)s: %(message)s '
		    '[in %(pathname)s:%(lineno)d]'
		))
		app.logger.addHandler(file_handler)

	#include an api_registry to the application
	app.api_registry = [] #a simple list holding the values to be registered

	return app
Ejemplo n.º 18
0
from restaurants import restaurant
app.register_blueprint(restaurant)

# from auths import auth
# app.register_blueprint(auth)


'''
    LOGIN MANAGER
'''
# login_manager.login_view = ''
# login_manager.login_message = ''
# login_manager.login_message_category = ''
from users.models import AnonymousUser
login_manager.anonymous_user = AnonymousUser
login_manager.session_protection = 'basic'  # Choose ' "basic" ' or ' "strong" ' or "None"

'''
    PYJADE
'''
app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')

'''
    INITIALIZE EXTENSIONS
'''
db.init_app(app)
toolbar.init_app(app)
moment.init_app(app)
bcrypt.init_app(app)
csrf.init_app(app)
login_manager.init_app(app)
Ejemplo n.º 19
0
from flask.ext.bootstrap import Bootstrap 
from flask.ext.mail import Mail 
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.pagedown import PageDown
from config import config

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.config配置对象提供的from_object()方法直接导入
	'''
	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)
Ejemplo n.º 20
0
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
from flask_mongoengine import MongoEngine
import logging
from datetime import timedelta



app = Flask(__name__)            # init app
app.config.from_object('config') # read config.py
app.permanent_session_lifetime = timedelta(seconds=app.config['SESSION_LIFE_TIME'])

login_manager = LoginManager()                #init login-manager
login_manager.init_app(app)                   # set app
login_manager.login_view = 'login'            # set login view
login_manager.session_protection = "strong"   # set level protection
login_manager.refresh_view = "accounts.reauthenticate"
login_manager.needs_refresh_message = (
    u"To protect your account, please reauthenticate to access this page."
)
login_manager.needs_refresh_message_category = "info"


db  = MongoEngine(app)           # init mongoengine
#dtb = DebugToolbarExtension(app) # init debug object

# Enable logging with file
if app.config['LOG']:
   logging.basicConfig(format = u'%(levelname)-8s [%(asctime)s] %(message)s', level = logging.DEBUG, filename = app.config['LOG']) #u'sitelog.log'
   logging.info( u'Start server' ) # add log event
Ejemplo n.º 21
0
from dev_tools import *
from middleware import *

# 避免中文传给jinja2时候报错
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

# REDIS的全局变量
# R表示实例连接,缓存的过期时间
CACHE_TIME = config["default"].REDIS_PORT

# Flask-login 模块 =======
app.secret_key = app.config['SECRET_KEY']
login_manager = LoginManager()
login_manager.session_protection = 'none'
login_manager.login_view = 'login'
# 设置当未登录用户请求一个只有登录用户才能访问的视图时,闪现的错误消息的内容,
# 默认的错误消息是:Please log in to access this page.。
login_manager.login_message = u'请先登录'
# 设置闪现的错误消息的类别
login_manager.login_message_category = "login_info"
login_manager.init_app(app)


# 如果用户名存在则构建一个新的用户类对象,并使用用户名作为ID
# 如果不存在,必须返回None
@login_manager.user_loader
def load_user(username):

    # 回调,把信息放到这里,这样所有页面current_user可以传输用户的数据了
Ejemplo n.º 22
0
# encoding=utf8
from flask import Flask
import os
from flask.ext.login import LoginManager
from config import basedir
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
lm = LoginManager(app)
lm.init_app(app)
lm.login_view = 'home'
lm.session_protection = "basic"

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

from app.controller.index import *
from app.controller.articles import *
from app.controller.diffarticle import *
from app.controller.validate import *
from app.controller.weberrors import *
from app.controller.userControl import *
from app.controller.root import *
from config import basedir, ADMINS, MAIL_SERVER, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD

if not app.debug:
    import logging
    from logging.handlers import SMTPHandler
    from logging.handlers import RotatingFileHandler

    credentials = None
Ejemplo n.º 23
0
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.pagedown import PageDown
from config import config

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

login_manager = LoginManager()
login_manager.session_protection = 'strong'  # Set security level
login_manager.login_view = 'auth.login'  # Set the endpoint login page

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)
	login_manager.init_app(app)
	pagedown.init_app(app)

	from .main import main as main_blueprint
Ejemplo n.º 24
0
import os
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask_debugtoolbar import DebugToolbarExtension
# from flask.ext.moment import Moment

from .config import config_by_name

bootstrap = Bootstrap()
db = SQLAlchemy()

# Configure authentication
login_man = LoginManager()
login_man.session_protection = "strong"
login_man.login_view = "auth.login"

toolbar = DebugToolbarExtension()

# for displaying timestamps
# moment = Moment()

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config_by_name[config_name])
    db.init_app(app)
    login_man.init_app(app)
    bootstrap.init_app(app)
    toolbar.init_app(app)
    
Ejemplo n.º 25
0
import json
from flask import Blueprint, flash, render_template, request, session, escape, abort, redirect, url_for, jsonify
from flask.ext.login import login_user, logout_user, current_user, login_required
import models

from models import User,Config,Vlan,Switch,Cluster,Event,Iso,Node
from rvs import app
from rvs.models import db
from forms import LoginForm
from forms import ReserveForm
from flask.ext.login import LoginManager

lm = LoginManager()
lm.init_app(app)
lm.login_view = "login"
lm.session_protection = "strong"

def get_handle(obj_name):
    allowed_dbs = [ "configs","users","clusters","nodes","vlans","switches","events","isos","tasks"]

    if not obj_name in allowed_dbs:
        return jsonify( {'result': False } ), 401

    db_name=obj_name[:-1].title() if obj_name != "switches" else "Switch"
    model = getattr(models,db_name)
    try:
        cols = getattr(model,"allowed_fields")
    except:
        cols = model.__table__.c._data.keys() 

    if 'id' in cols: cols.remove('id')
Ejemplo n.º 26
0
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.pagedown import PageDown

from www.config import config

bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.session_protection = "strong"  # session_protection属性可设置为None,'Basic'或'Strong',提供不同的安全等级防止用户会话被篡改。
login_manager.login_view = "main.signin"  # login_view属性设置登陆页面的端点,路由在蓝本中定义,要加上蓝本名。
pagedown = PageDown()


def create_app(config_name):
    """初始化。"""
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].inits_app(app)

    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)
Ejemplo n.º 27
0
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.sqlalchemy import SQLAlchemy
from config import config
from flask.ext.login import LoginManager

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

login_manager = LoginManager()
login_manager.session_protection = 'string' #None, basic, string
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)
    db.init_app(app)

    login_manager.init_app(app)
    # from .main import main as main_blueprint
    # app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')
Ejemplo n.º 28
0
import time, datetime
import hashlib
from thread import start_new_thread

from modules.config import UserConfig, CoreConfig
from modules.bouncer import PyIrcBouncer

from utils import Waiter, IP
from user import User

_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
app = Flask(__name__)

# init login manager
loginManager = LoginManager()
loginManager.session_protection = "strong"


app.config['SESSION_TYPE'] = 'filesystem'
app.secret_key = 'hmmseeeecret!'
loginManager.init_app(app)

# mmmh, threaded-web-applic using un-managed globals, is this a good idea?
config = None
waiter = None
enableDebug = False

if not enableDebug:
    import logging
    log = logging.getLogger('werkzeug')
    log.setLevel(logging.ERROR)
Ejemplo n.º 29
0
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.session import Session
from UserProfileConfig import config
import wtforms_json

wtforms_json.init()
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()

login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'service.service_login'


def create_app(config_name):
    app = Flask(__name__)

    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    Session(app)
    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
Ejemplo n.º 30
0
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail, Message
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from config import config
from flask.ext.login import LoginManager
from flask.ext.pagedown import PageDown


bootstrap = Bootstrap()
moment = Moment()
mail = Mail()
db = SQLAlchemy()
login_manager = LoginManager()
pagedown = PageDown()
login_manager.session_protection = 'strong' # flask-login will keep track of ip and broswer agent, will log user out if it detects a change
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)
	login_manager.init_app(app)
	pagedown.init_app(app)
Ejemplo n.º 31
0
from flask.ext.mail import Mail
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from config import config
from flask.ext.login import LoginManager
from flask_wtf import CsrfProtect

login_manager = LoginManager()
mail = Mail()
bootstrap = Bootstrap()
db = SQLAlchemy()
moment = Moment()
csrf = CsrfProtect()

login_manager.session_protection = 'basic'  #strong should be in production build
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)
    db.init_app(app)
    csrf.init_app(app)
    mail.init_app(app)
    bootstrap.init_app(app)
    moment.init_app(app)
    login_manager.init_app(app)
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')
Ejemplo n.º 32
0
from flask import Flask,render_template
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.pagedown import PageDown
from config import config

'''flask app initialization:template,database,time'''

bootstrap = Bootstrap()
moment = Moment()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.session_protection = 'basic'
login_manager.login_view = 'auth.login'
pagedown = PageDown()

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)
	moment.init_app(app)
	db.init_app(app)
	login_manager.init_app(app)
	pagedown.init_app(app)
        #regist blueprint
	from .main import main as main_blueprint
	app.register_blueprint(main_blueprint)
Ejemplo n.º 33
0
# -*- coding=utf-8 -*-
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.bootstrap import Bootstrap  # 引入Flask-Bootstrap
from flask.ext.login import LoginManager  # 引入Flask-Login
from flask.ext.moment import Moment  # 引入时间组件
from config import config

db = SQLAlchemy()  # 实例化对象
bootstrap = Bootstrap()  # 实例化对象
login_manager = LoginManager()  # 实例化对象
moment = Moment()
login_manager.session_protection = 'strong'  # 设置flask-login session等级
login_manager.login_view = 'admin.login'  # 如果未登入转跳到指定方法
login_manager.login_message = u'请登入账号再进行下一步操作!'  # 未登入提示语


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

    db.init_app(app)
    bootstrap.init_app(app)
    login_manager.init_app(app)
    moment.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .admin import admin as admin_blueprint
Ejemplo n.º 34
0
	def run(self):
		if not self._allowRoot:
			self._check_for_root()

		global app
		global babel

		global printer
		global printerProfileManager
		global fileManager
		global slicingManager
		global analysisQueue
		global userManager
		global eventManager
		global loginManager
		global pluginManager
		global appSessionManager
		global pluginLifecycleManager
		global preemptiveCache
		global debug

		from tornado.ioloop import IOLoop
		from tornado.web import Application, RequestHandler

		import sys

		debug = self._debug

		# first initialize the settings singleton and make sure it uses given configfile and basedir if available
		s = settings(init=True, basedir=self._basedir, configfile=self._configfile)

		# then monkey patch a bunch of stuff
		util.tornado.fix_ioloop_scheduling()
		util.flask.enable_additional_translations(additional_folders=[s.getBaseFolder("translations")])

		# setup app
		self._setup_app(app)

		# setup i18n
		self._setup_i18n(app)

		# then initialize logging
		self._setup_logging(self._debug, self._logConf)
		self._logger = logging.getLogger(__name__)
		def exception_logger(exc_type, exc_value, exc_tb):
			self._logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb))
		sys.excepthook = exception_logger
		self._logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)

		# start the intermediary server
		self._start_intermediary_server(s)

		# then initialize the plugin manager
		pluginManager = octoprint.plugin.plugin_manager(init=True)

		printerProfileManager = PrinterProfileManager()
		eventManager = events.eventManager()
		analysisQueue = octoprint.filemanager.analysis.AnalysisQueue()
		slicingManager = octoprint.slicing.SlicingManager(s.getBaseFolder("slicingProfiles"), printerProfileManager)
		storage_managers = dict()
		storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(s.getBaseFolder("uploads"))
		fileManager = octoprint.filemanager.FileManager(analysisQueue, slicingManager, printerProfileManager, initial_storage_managers=storage_managers)
		printer = Printer(fileManager, analysisQueue, printerProfileManager)
		appSessionManager = util.flask.AppSessionManager()
		pluginLifecycleManager = LifecycleManager(pluginManager)
		preemptiveCache = PreemptiveCache(os.path.join(s.getBaseFolder("data"), "preemptive_cache_config.yaml"))

		# ... and initialize all plugins

		def octoprint_plugin_inject_factory(name, implementation):
			"""Factory for injections for all OctoPrintPlugins"""

			if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin):
				# we only care about OctoPrintPlugins
				return None

			return dict(
				plugin_manager=pluginManager,
				printer_profile_manager=printerProfileManager,
				event_bus=eventManager,
				analysis_queue=analysisQueue,
				slicing_manager=slicingManager,
				file_manager=fileManager,
				printer=printer,
				app_session_manager=appSessionManager,
				plugin_lifecycle_manager=pluginLifecycleManager,
				data_folder=os.path.join(settings().getBaseFolder("data"), name),
				preemptive_cache=preemptiveCache
			)

		def settings_plugin_inject_factory(name, implementation):
			"""Factory for additional injections depending on plugin type"""

			if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
				# we only care about SettingsPlugins
				return None

			# SettingsPlugin instnances get a PluginSettings instance injected
			default_settings = implementation.get_settings_defaults()
			get_preprocessors, set_preprocessors = implementation.get_settings_preprocessors()
			plugin_settings = octoprint.plugin.plugin_settings(name,
			                                                   defaults=default_settings,
			                                                   get_preprocessors=get_preprocessors,
			                                                   set_preprocessors=set_preprocessors)
			return dict(settings=plugin_settings)

		def settings_plugin_config_migration_and_cleanup(name, implementation):
			"""Take care of migrating and cleaning up any old settings"""

			if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
				return

			settings_version = implementation.get_settings_version()
			settings_migrator = implementation.on_settings_migrate

			if settings_version is not None and settings_migrator is not None:
				stored_version = implementation._settings.get_int([octoprint.plugin.SettingsPlugin.config_version_key])
				if stored_version is None or stored_version < settings_version:
					settings_migrator(settings_version, stored_version)
					implementation._settings.set_int([octoprint.plugin.SettingsPlugin.config_version_key], settings_version)

			implementation.on_settings_cleanup()
			implementation._settings.save()

			implementation.on_settings_initialized()

		pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory, settings_plugin_inject_factory]
		pluginManager.initialize_implementations()

		settingsPlugins = pluginManager.get_implementations(octoprint.plugin.SettingsPlugin)
		for implementation in settingsPlugins:
			try:
				settings_plugin_config_migration_and_cleanup(implementation._identifier, implementation)
			except:
				self._logger.exception("Error while trying to migrate settings for plugin {}, ignoring it".format(implementation._identifier))

		pluginManager.implementation_post_inits=[settings_plugin_config_migration_and_cleanup]

		pluginManager.log_all_plugins()

		# initialize file manager and register it for changes in the registered plugins
		fileManager.initialize()
		pluginLifecycleManager.add_callback(["enabled", "disabled"], lambda name, plugin: fileManager.reload_plugins())

		# initialize slicing manager and register it for changes in the registered plugins
		slicingManager.initialize()
		pluginLifecycleManager.add_callback(["enabled", "disabled"], lambda name, plugin: slicingManager.reload_slicers())

		# setup jinja2
		self._setup_jinja2()

		# make sure plugin lifecycle events relevant for jinja2 are taken care of
		def template_enabled(name, plugin):
			if plugin.implementation is None or not isinstance(plugin.implementation, octoprint.plugin.TemplatePlugin):
				return
			self._register_additional_template_plugin(plugin.implementation)
		def template_disabled(name, plugin):
			if plugin.implementation is None or not isinstance(plugin.implementation, octoprint.plugin.TemplatePlugin):
				return
			self._unregister_additional_template_plugin(plugin.implementation)
		pluginLifecycleManager.add_callback("enabled", template_enabled)
		pluginLifecycleManager.add_callback("disabled", template_disabled)

		# setup assets
		self._setup_assets()

		# configure timelapse
		octoprint.timelapse.configure_timelapse()

		# setup command triggers
		events.CommandTrigger(printer)
		if self._debug:
			events.DebugEventListener()

		# setup access control
		userManagerName = s.get(["accessControl", "userManager"])
		try:
			clazz = octoprint.util.get_class(userManagerName)
			userManager = clazz()
		except AttributeError as e:
			self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName))
			userManager = octoprint.users.FilebasedUserManager()
		finally:
			userManager.enabled = s.getBoolean(["accessControl", "enabled"])

		loginManager = LoginManager()
		loginManager.session_protection = "strong"
		loginManager.user_callback = load_user
		if not userManager.enabled:
			loginManager.anonymous_user = users.DummyUser
			principals.identity_loaders.appendleft(users.dummy_identity_loader)
		loginManager.init_app(app)

		# register API blueprint
		self._setup_blueprints()

		## Tornado initialization starts here

		if self._host is None:
			self._host = s.get(["server", "host"])
		if self._port is None:
			self._port = s.getInt(["server", "port"])

		ioloop = IOLoop()
		ioloop.install()

		self._router = SockJSRouter(self._create_socket_connection, "/sockjs")

		upload_suffixes = dict(name=s.get(["server", "uploads", "nameSuffix"]), path=s.get(["server", "uploads", "pathSuffix"]))

		def mime_type_guesser(path):
			from octoprint.filemanager import get_mime_type
			return get_mime_type(path)

		download_handler_kwargs = dict(
			as_attachment=True,
			allow_client_caching=False
		)
		additional_mime_types=dict(mime_type_guesser=mime_type_guesser)
		admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))
		no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path), status_code=404))

		def joined_dict(*dicts):
			if not len(dicts):
				return dict()

			joined = dict()
			for d in dicts:
				joined.update(d)
			return joined

		server_routes = self._router.urls + [
			# various downloads
			(r"/downloads/timelapse/([^/]*\.mp[g4])", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("timelapse")), download_handler_kwargs, no_hidden_files_validator)),
			(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("uploads")), download_handler_kwargs, no_hidden_files_validator, additional_mime_types)),
			(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("logs")), download_handler_kwargs, admin_validator)),
			# camera snapshot
			(r"/downloads/camera/current", util.tornado.UrlProxyHandler, dict(url=s.get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
			# generated webassets
			(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(s.getBaseFolder("generated"), "webassets"))),
			# online indicators - text file with "online" as content and a transparent gif
			(r"/online.txt", util.tornado.StaticDataHandler, dict(data="online\n")),
			(r"/online.gif", util.tornado.StaticDataHandler, dict(data=bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")), content_type="image/gif"))
		]

		# fetch additional routes from plugins
		for name, hook in pluginManager.get_hooks("octoprint.server.http.routes").items():
			try:
				result = hook(list(server_routes))
			except:
				self._logger.exception("There was an error while retrieving additional server routes from plugin hook {name}".format(**locals()))
			else:
				if isinstance(result, (list, tuple)):
					for entry in result:
						if not isinstance(entry, tuple) or not len(entry) == 3:
							continue
						if not isinstance(entry[0], basestring):
							continue
						if not isinstance(entry[2], dict):
							continue

						route, handler, kwargs = entry
						route = r"/plugin/{name}/{route}".format(name=name, route=route if not route.startswith("/") else route[1:])

						self._logger.debug("Adding additional route {route} handled by handler {handler} and with additional arguments {kwargs!r}".format(**locals()))
						server_routes.append((route, handler, kwargs))

		server_routes.append((r".*", util.tornado.UploadStorageFallbackHandler, dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app), file_prefix="octoprint-file-upload-", file_suffix=".tmp", suffixes=upload_suffixes)))

		self._tornado_app = Application(server_routes)
		max_body_sizes = [
			("POST", r"/api/files/([^/]*)", s.getInt(["server", "uploads", "maxSize"])),
			("POST", r"/api/languages", 5 * 1024 * 1024)
		]

		# allow plugins to extend allowed maximum body sizes
		for name, hook in pluginManager.get_hooks("octoprint.server.http.bodysize").items():
			try:
				result = hook(list(max_body_sizes))
			except:
				self._logger.exception("There was an error while retrieving additional upload sizes from plugin hook {name}".format(**locals()))
			else:
				if isinstance(result, (list, tuple)):
					for entry in result:
						if not isinstance(entry, tuple) or not len(entry) == 3:
							continue
						if not entry[0] in util.tornado.UploadStorageFallbackHandler.BODY_METHODS:
							continue
						if not isinstance(entry[2], int):
							continue

						method, route, size = entry
						route = r"/plugin/{name}/{route}".format(name=name, route=route if not route.startswith("/") else route[1:])

						self._logger.debug("Adding maximum body size of {size}B for {method} requests to {route})".format(**locals()))
						max_body_sizes.append((method, route, size))

		self._stop_intermediary_server()

		# initialize and bind the server
		self._server = util.tornado.CustomHTTPServer(self._tornado_app, max_body_sizes=max_body_sizes, default_max_body_size=s.getInt(["server", "maxSize"]))
		self._server.listen(self._port, address=self._host)

		eventManager.fire(events.Events.STARTUP)

		# auto connect
		if s.getBoolean(["serial", "autoconnect"]):
			(port, baudrate) = s.get(["serial", "port"]), s.getInt(["serial", "baudrate"])
			printer_profile = printerProfileManager.get_default()
			connectionOptions = get_connection_options()
			if port in connectionOptions["ports"]:
				printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default")

		# start up watchdogs
		if s.getBoolean(["feature", "pollWatched"]):
			# use less performant polling observer if explicitely configured
			observer = PollingObserver()
		else:
			# use os default
			observer = Observer()
		observer.schedule(util.watchdog.GcodeWatchdogHandler(fileManager, printer), s.getBaseFolder("watched"))
		observer.start()

		# run our startup plugins
		octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
		                             "on_startup",
		                             args=(self._host, self._port))

		def call_on_startup(name, plugin):
			implementation = plugin.get_implementation(octoprint.plugin.StartupPlugin)
			if implementation is None:
				return
			implementation.on_startup(self._host, self._port)
		pluginLifecycleManager.add_callback("enabled", call_on_startup)

		# prepare our after startup function
		def on_after_startup():
			self._logger.info("Listening on http://%s:%d" % (self._host, self._port))

			# now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for
			# which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons
			# or service xmls or the like). While they are working though the ioloop would block. Therefore we'll
			# create a single use thread in which to perform our after-startup-tasks, start that and hand back
			# control to the ioloop
			def work():
				octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
				                             "on_after_startup")

				def call_on_after_startup(name, plugin):
					implementation = plugin.get_implementation(octoprint.plugin.StartupPlugin)
					if implementation is None:
						return
					implementation.on_after_startup()
				pluginLifecycleManager.add_callback("enabled", call_on_after_startup)

				# when we are through with that we also run our preemptive cache
				if settings().getBoolean(["devel", "cache", "preemptive"]):
					self._execute_preemptive_flask_caching(preemptiveCache)

			import threading
			threading.Thread(target=work).start()
		ioloop.add_callback(on_after_startup)

		# prepare our shutdown function
		def on_shutdown():
			# will be called on clean system exit and shutdown the watchdog observer and call the on_shutdown methods
			# on all registered ShutdownPlugins
			self._logger.info("Shutting down...")
			observer.stop()
			observer.join()
			octoprint.plugin.call_plugin(octoprint.plugin.ShutdownPlugin,
			                             "on_shutdown")

			if self._octoprint_daemon is not None:
				self._logger.info("Cleaning up daemon pidfile")
				self._octoprint_daemon.terminated()

			self._logger.info("Goodbye!")
		atexit.register(on_shutdown)

		def sigterm_handler(*args, **kwargs):
			# will stop tornado on SIGTERM, making the program exit cleanly
			def shutdown_tornado():
				ioloop.stop()
			ioloop.add_callback_from_signal(shutdown_tornado)
		signal.signal(signal.SIGTERM, sigterm_handler)

		try:
			# this is the main loop - as long as tornado is running, OctoPrint is running
			ioloop.start()
		except (KeyboardInterrupt, SystemExit):
			pass
		except:
			self._logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!")
			self._logger.exception("Stacktrace follows:")
Ejemplo n.º 35
0
from flask import Flask,render_template
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.pagedown import PageDown
from config import config

bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
pagedown = PageDown()
login_manager = LoginManager()
login_manager.session_protection = 'strong' #属性设置 none basic strong时提供不同的安全等
#strong是记录客户端ip地址和浏览器用户代理信息,发现异常即退出

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)
    login_manager.init_app(app)
    pagedown.init_app(app)
    #附加路由和自定义错误页面
Ejemplo n.º 36
0
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.mail import Mail
from flask.ext.login import LoginManager
from flask.ext.pagedown import PageDown
from config import config

bootstrap = Bootstrap()
moment = Moment()
db = SQLAlchemy()
mail = Mail()
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)
    db.init_app(app)
    moment.init_app(app)
    login_manager.init_app(app)
Ejemplo n.º 37
0
from flask.ext.login import LoginManager

# Define the WSGI application object
app = Flask(__name__)

# Configurations
app.config.from_object('config')

# LoginManager
# https://flask-login.readthedocs.org/en/latest/
# TODO: Validate next()
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = app.config["LOGIN_VIEW"]
login_manager.login_message = app.config["LOGIN_MESSAGE"]
login_manager.session_protection = app.config["SESSION_PROTECTION"]

# Database
db = MySQL(app)

# =========================================
# Flask-restful
# add prefix here or it won't work when you register blueprint
# =========================================
api = Api(app, prefix=app.config["URL_PREFIX"])

@app.before_request
def new_request():
    print("New Request")
    print("############")