Пример #1
1
def create_app():
    app = Flask(__name__)
    app.config.from_object("geomancer.app_config")
    app.session_interface = RedisSessionInterface()
    app.register_blueprint(api)
    app.register_blueprint(views)

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template("404.html"), 404

    @app.errorhandler(500)
    def server_error(e):
        return render_template("error.html"), 500

    @app.errorhandler(413)
    def file_too_large(e):
        return render_template("413.html"), 413

    @app.template_filter("string_split")
    def string_split(val, splitter):
        return val.split(splitter)

    if sentry:
        sentry.init_app(app)

    return app
Пример #2
1
def create_app(config):
    app = Flask(__name__)
    app.config.from_pyfile(config)

    CORS(app, origins=app.config["CORS_ORIGINS"], supports_credentials=True)

    from app.lib.database import db

    db.init_app(app)

    from app import views

    views.register(app)

    with app.app_context():
        db.create_all()

    from app.lib.session import SessionInterface

    app.session_interface = SessionInterface()

    from app.lib import exceptions

    exceptions.register(app)

    return app
Пример #3
1
def create_app(config_filepath="resource/config.cfg"):
    app = Flask(__name__)
    # app.config.from_object(__name__)
    # app.config.from_envvar('GRADE_SETTINGS', silent=True)

    # 기본 설정은 GradeServer_Config 객체에 정의되있고 운영 환경 또는 기본 설정을 변경을 하려면
    # 실행 환경변수인 GradeServer_SETTINGS에 변경할 설정을 담고 있는 파일 경로를 설정
    from GradeServer.GradeServer_config import GradeServerConfig

    app.config.from_object(GradeServerConfig)
    app.config.from_pyfile(config_filepath, silent=True)
    # Log
    from GradeServer.GradeServer_logger import Log

    Log.init()

    # SessionInterface 설정.
    from GradeServer.cache_session import RedisCacheSessionInterface

    app.session_interface = RedisCacheSessionInterface()

    # 데이터베이스 처리
    from GradeServer.database import DBManager

    DBManager.init(app.config["DB_URL"])
    DBManager.init_db()

    # 뷰 함수 모듈은 어플리케이션 객체 생성하고 블루프린트 등록전에
    # 뷰 함수가 있는 모듈을 임포트해야 해당 뷰 함수들을 인식할 수 있음
    from GradeServer.controller import *
    from GradeServer.GradeServer_blueprint import GradeServer

    app.register_blueprint(GradeServer)

    return app
Пример #4
1
def create_app():
    """Return an instance of the main Flask application."""
    app = Flask(package_name)

    app.config.setdefault("REDIS_URL", "redis://localhost")

    from .model import db

    db.init_app(app)

    @app.before_first_request
    def init_db():
        app.redis = StrictRedis.from_url(app.config["REDIS_URL"])

    from .error import register_error_handler, html_handler

    register_error_handler(app, html_handler)

    from .session import LazyRedisSessionInterface

    app.session_interface = LazyRedisSessionInterface()

    from .util import price_filter

    app.jinja_env.filters["price"] = price_filter

    from .views import views

    app.register_blueprint(views)

    return app
Пример #5
1
def create_app():
    app = Flask(__name__)
    app.config.from_object(config[sysType])
    app.config["DEBUG_TB_PANELS"] = ["flask_mongoengine.panels.MongoDebugPanel"]

    bootstrap.init_app(app)

    mongodb.init_app(app)

    moment.init_app(app)

    toolbar = DebugToolbarExtension(app)

    app.session_interface = MongoEngineSessionInterface(mongodb)

    app.jinja_env.filters["filter_html"] = filter_html

    from .home import home as home_blueprint

    app.register_blueprint(home_blueprint)

    from .meitu import meitu as meitu_blueprint

    app.register_blueprint(meitu_blueprint, url_prefix="/meitu")

    from .life import life as life_blueprint

    app.register_blueprint(life_blueprint, url_prefix="/life")

    from .advert import advert as advert_blueprint

    app.register_blueprint(advert_blueprint, url_prefix="/advert")

    from .think import think as think_blueprint

    app.register_blueprint(think_blueprint, url_prefix="/think")

    from .technology import tech as tech_blueprint

    app.register_blueprint(tech_blueprint, url_prefix="/tech")

    from .book import book as book_blueprint

    app.register_blueprint(book_blueprint, url_prefix="/book")

    from .shop import shop as shop_blueprint

    app.register_blueprint(shop_blueprint, url_prefix="/shop")

    from .collect import collect as collect_blueprint

    app.register_blueprint(collect_blueprint, url_prefix="/collect")

    from .message import message as message_blueprint

    app.register_blueprint(message_blueprint, url_prefix="/message")

    return app
Пример #6
1
 def load_app(self, config):
     """
     Called from the parent class, so we can provide the appropriate flask
     app for this test case.
     """
     app = Flask("test.localhost")
     app.request_class = Request
     app.config.update(config)
     app.register_blueprint(test_views)
     app.central_userdb = UserDB(app.config["MONGO_URI"], "eduid_am")
     app.session_interface = SessionFactory(app.config)
     return app
Пример #7
0
def create_app(db_interface, app_name="testapp", db_name="__test-db__"):
    app = Flask(app_name)
    app.config["SERVER_NAME"] = "localhost:5000"

    if db_interface == "pymongo":
        app.config["MONGO_DBNAME"] = db_name
        mongo = PyMongo(app)
        with app.app_context():
            app.session_interface = MongoDBSessionInterface(app, mongo.db, "sessions")
    elif db_interface == "mongoengine":
        app.config["MONGODB_DB"] = db_name
        mongo = MongoEngine(app)
        app.session_interface = MongoDBSessionInterface(app, mongo.connection[app.config["MONGODB_DB"]], "sessions")

    @app.route("/set")
    def set_session():
        session["data"] = request.args["d"]
        return "data"

    @app.route("/setpermanent")
    def set_permanent_session():
        session.permanent = True
        session["data"] = request.args["d"]
        return "data"

    @app.route("/get")
    def get_session():
        return session.get("data", "")

    @app.route("/unicode/set")
    def unicode_set():
        session["foo"] = u"Alpenerstra\xdfe"
        return "done"

    @app.route("/unicode/get")
    def unicode_get():
        return session["foo"]

    return app
Пример #8
0
    def init_app(self, app_name, **kwargs):
        app = Flask(app_name, **kwargs)
        app.config.from_object(self.app_config)
        app.config.from_envvar(self.app_envvar, silent=True)

        self._add_logger(app)
        self._bind_extensions(app)
        self._register_blueprints(app)
        self._register_hooks(app)

        app.session_interface = RedisSessionInterface()
        app.wsgi_app = ProxyFix(app.wsgi_app)
        return app
Пример #9
0
def create_app(config_filepath="resource/config.cfg"):
    locus_app = Flask(__name__)

    # 기본 설정은 'LocusConfig' 객체에 정의되있고 운영 환경 또는 기본 설정을 변경을 하려면
    # 실행 환경변수인 LOCUS_SETTING에 변경할 설정을 담고 있는 파일 경로를 설정
    from locus.locus_config import LocusConfig

    locus_app.config.from_object(LocusConfig)
    locus_app.config.from_pyfile(config_filepath, silent=True)
    print_settings(locus_app.config.iteritems())

    # 로그 초기화
    from locus.locus_logger import Log

    log_filepath = os.path.join(locus_app.root_path, locus_app.config["LOG_FILE_PATH"])
    Log.init(log_filepath=log_filepath)

    # 데이터베이스 처리
    from locus.database import DBManager

    db_filepath = os.path.join(locus_app.root_path, locus_app.config["DB_FILE_PATH"])
    db_url = locus_app.config["DB_URL"] + db_filepath
    DBManager.init(db_url, eval(locus_app.config["DB_LOG_FLAG"]))
    DBManager.init_db()

    # 뷰 함수 모듈은 어플리케이션 객체 생성하고 블루프린트 등록전에
    # 뷰 함수가 있는 모듈을 임포트해야 해당 뷰 함수들을 인식할 수 있음
    from locus.controller import *

    from locus.locus_blueprint import locus

    locus_app.register_blueprint(locus)

    # SessionInterface 설정.
    # Redis를 이용한 세션 구현은 cache_session.RedisCacheSessionInterface 임포트하고
    # app.session_interface에 RedisCacheSessionInterface를 할당
    from locus.cache_session import SimpleCacheSessionInterface

    locus_app.session_interface = SimpleCacheSessionInterface()

    # 공통으로 적용할 HTTP 404과 500 에러 핸들러를 설정
    locus_app.error_handler_spec[None][404] = not_found
    locus_app.error_handler_spec[None][500] = server_error

    # 페이징 처리를 위한 템플릿 함수
    locus_app.jinja_env.globals["url_for_other_page"] = url_for_other_page

    return locus_app
Пример #10
0
def create_app(mode="production"):
    global app
    app = Flask("application")
    app.session_interface = RedisSessionInterface()

    global app_run_args
    app_run_args = {"port": 5000, "host": "127.0.0.1"}

    if mode == "production":
        app.debug = False
    elif mode == "dev":
        app.debug = True
    else:
        logging.error("Did not recognize mode '%s'" % mode)

    import application.route
Пример #11
0
def create_app(config_file=None, config_obj=None, instance=None):
    app = Flask(__name__, static_folder="www", static_url_path="", instance_path=instance)
    if config_file is not None:
        app.config.from_pyfile(config_file)
    elif config_obj is not None:
        app.config.from_object(config_obj)
    else:
        raise TypeError("no configuration argument provided")

    app.session_interface = session.SessionInterface()
    db.init_app(app)
    db.create_all(app=app)  # pass app because of Flask-SQLAlchemy contexts
    app.register_blueprint(public)
    create_admin(app)
    security.init_app(app)

    return app
Пример #12
0
def create_app(config_filepath="resource/config.cfg"):
    photolog_app = Flask(__name__)

    # 기본 설정은 PhotologConfig 객체에 정의되있고 운영 환경 또는 기본 설정을 변경을 하려면
    # 실행 환경변수인 PHOTOLOG_SETTINGS에 변경할 설정을 담고 있는 파일 경로를 설정
    from photolog.photolog_config import PhotologConfig

    photolog_app.config.from_object(PhotologConfig)
    photolog_app.config.from_pyfile(config_filepath, silent=True)
    print_settings(photolog_app.config.iteritems())

    # 로그 초기화
    from photolog.photolog_logger import Log

    log_filepath = os.path.join(photolog_app.root_path, photolog_app.config["LOG_FILE_PATH"])
    Log.init(log_filepath=log_filepath)

    # 데이터베이스 처리
    from photolog.database import DBManager

    db_filepath = os.path.join(photolog_app.root_path, photolog_app.config["DB_FILE_PATH"])
    db_url = photolog_app.config["DB_URL"] + db_filepath
    DBManager.init(db_url, eval(photolog_app.config["DB_LOG_FLAG"]))
    DBManager.init_db()

    # 뷰 함수 모듈은 어플리케이션 객체 생성하고 블루프린트 등록전에
    # 뷰 함수가 있는 모듈을 임포트해야 해당 뷰 함수들을 인식할 수 있음
    from photolog.controller import *

    from photolog.photolog_blueprint import photolog

    photolog_app.register_blueprint(photolog)

    # SessionInterface 설정.
    # Redis를 이용한 세션 구현은 cache_session.RedisCacheSessionInterface 임포트하고
    # app.session_interface에 RedisCacheSessionInterface를 할당
    from photolog.cache_session import SimpleCacheSessionInterface

    photolog_app.session_interface = SimpleCacheSessionInterface()

    # 공통으로 적용할 HTTP 404과 500 에러 핸들러를 설정
    photolog_app.error_handler_spec[None][404] = not_found
    photolog_app.error_handler_spec[None][500] = server_error

    return photolog_app
Пример #13
0
def create_app():
    app = Flask(__name__)
    app.config.update(SECRET_KEY="secret")

    cdns = {
        "jquery": WebCDN("//ajax.googleapis.com/ajax/libs/jquery/1.11.0/"),
        "jquery-ui": WebCDN("//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/"),
    }

    Bootstrap(app)
    app.extensions["bootstrap"]["cdns"].update(cdns)

    session_opts = {"session.type": "ext:google", "session.cookie_expires": 10000, "session.auto": True}

    app.wsgi_app = SessionMiddleware(app.wsgi_app, session_opts)
    app.session_interface = BeakerSessionInterface()

    return app
Пример #14
0
def create_admin_app(config=None):
    app = Flask(__name__)
    if config:
        app.config.from_pyfile(config)

    app.url_map.strict_slashes = False

    db.init_app(app)

    from .container import container

    container.init_app(app)

    from .views.admin import accounts

    app.register_blueprint(accounts)
    app.session_interface = ItsdangerousSessionInterface()

    return app
Пример #15
0
def create_app(subdomain="", config=None):
    app = Flask(__name__)
    load_config(app, subdomain=subdomain, config=config)
    # if app.config.get('HEROKU'):
    # heroku.init_app(app)
    if app.config["ENABLE_NEO4J"]:
        init_graph(app)
    else:
        app.graph = None
    if app.config["ENABLE_SQL"]:
        db.init_app(app)
    else:
        app.db = None
    if app.config.get("LOGGING"):
        attach_loggers(app)
    app.session_interface = JSONSecureCookieSessionInterface()
    register_blueprints(app)
    attach_before_request_handlers(app)
    inject_context_processors(app)
    return app
Пример #16
0
def create_app():
    """Return an instance of the main Flask application."""
    app = Flask(package_name)

    # TODO: do some config
    app.redis = StrictRedis()

    from .error import register_error_handler, html_handler

    register_error_handler(app, html_handler)

    from .session import LazyRedisSessionInterface

    app.session_interface = LazyRedisSessionInterface()

    from .views import views

    app.register_blueprint(views)

    return app
Пример #17
0
def create_app():
    app = Flask(__name__, static_folder="../public/", static_url_path="/public")
    app.response_class = ResponseJSON
    app.config.from_pyfile(config.FLASK_CONFIG_PATH)

    # change debug output formatter to a pretty one-liner
    format = Formatter("%(levelname)6s | %(relativeCreated)6d | %(filename)s:%(lineno)d | %(message)s")
    app.logger.handlers[0].setFormatter(format)

    # resolve paths relative to this file
    app_path = path.dirname(__file__)
    app.config.update(
        {
            "RECORDINGS_PATH": path.realpath(app_path + "/../public/recordings/"),
            "PATH_USER_PROFILE_IMAGE": path.realpath(app_path + "/../public/profile_images/"),
            "PATH_ASSETS": path.realpath(app_path + "/../public/assets/"),
            "PATH_PUBLIC": path.realpath(app_path + "/../public/"),
        }
    )

    # sanity checks
    if not path.isdir(app.config["RECORDINGS_PATH"]):
        raise Exception("Recordings path does not exist: " + app.config["RECORDINGS_PATH"])

    if not path.isdir(app.config["PATH_USER_PROFILE_IMAGE"]):
        raise Exception("User profile images path does not exist: " + app.config["PATH_USER_PROFILE_IMAGE"])

    # app.json_encoder = MongoJsonEncoder

    # setup database and session storage
    # db settings come from flask.ini
    # and same engine is used for storing sessions
    mongo = MongoEngine()
    mongo.init_app(app)
    app.session_interface = MongoEngineSessionInterface(mongo)

    # toolbar = DebugToolbarExtension(app)

    return app, mongo
Пример #18
0
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
Пример #19
0
def create_app():
    from config import configs

    application = Flask(__name__)

    application.config.from_object(configs[os.environ["NOTIFY_ENVIRONMENT"]])

    init_app(application)
    statsd_client.init_app(application)
    logging.init_app(application, statsd_client)
    init_csrf(application)
    request_id.init_app(application)

    service_api_client.init_app(application)
    user_api_client.init_app(application)
    api_key_api_client.init_app(application)
    job_api_client.init_app(application)
    notification_api_client.init_app(application)
    status_api_client.init_app(application)
    invite_api_client.init_app(application)
    template_statistics_client.init_app(application)
    events_api_client.init_app(application)
    provider_client.init_app(application)
    organisations_client.init_app(application)

    login_manager.init_app(application)
    login_manager.login_view = "main.sign_in"
    login_manager.login_message_category = "default"
    login_manager.session_protection = None

    from app.main import main as main_blueprint

    application.register_blueprint(main_blueprint)

    from .status import status as status_blueprint

    application.register_blueprint(status_blueprint)

    proxy_fix.init_app(application)

    application.session_interface = ItsdangerousSessionInterface()

    application.add_template_filter(format_datetime)
    application.add_template_filter(format_datetime_24h)
    application.add_template_filter(format_datetime_normal)
    application.add_template_filter(format_datetime_short)
    application.add_template_filter(format_time)
    application.add_template_filter(syntax_highlight_json)
    application.add_template_filter(valid_phone_number)
    application.add_template_filter(linkable_name)
    application.add_template_filter(format_date)
    application.add_template_filter(format_date_normal)
    application.add_template_filter(format_date_short)
    application.add_template_filter(format_datetime_relative)
    application.add_template_filter(format_delta)
    application.add_template_filter(format_notification_status)
    application.add_template_filter(format_notification_status_as_time)
    application.add_template_filter(format_notification_status_as_field_status)
    application.add_template_filter(format_notification_status_as_url)

    application.after_request(useful_headers_after_request)
    application.after_request(save_service_after_request)
    application.before_request(load_service_before_request)

    @application.context_processor
    def _attach_current_service():
        return {"current_service": current_service}

    register_errorhandlers(application)

    setup_event_handlers()

    return application
Пример #20
0
from flask import Flask, render_template, session, redirect

import db
import api
from models.user import User
from session import PsqlSessionInterface

app = Flask(__name__, static_folder="static")
app.session_interface = PsqlSessionInterface()
app.config.from_pyfile("config/settings.py")

app.register_blueprint(api.user.page, url_prefix="/api/user")
app.register_blueprint(api.project.page, url_prefix="/api/project")


@app.route("/logout")
def logout():
    if "user_id" in session:
        del session["user_id"]
    return redirect("/")


@app.route("/")
@app.route("/<path:path>")
def index(path="/"):
    user_session = {}
    if "user_id" in session:
        user = User.get(session["user_id"])
        if user is not None:
            user_session = db.json_encode(user.to_dict())
    return render_template("index.html", user_session=user_session)
Пример #21
0
from flask import Flask
from werkzeug.datastructures import ImmutableDict

app = Flask(__name__)

from metalreal.redis_session import RedisSessionInterface

app.session_interface = RedisSessionInterface()


import metalreal.main
Пример #22
0
from flask import Flask
from api.account.session import MongoSessionInterface
import router
from stations import updater


app = Flask(__name__)
app.debug = True
app.session_interface = MongoSessionInterface()
router.route(app)
stations_updater = updater.StationsUpdater()
stations_updater.start()

app.run(host="127.0.0.1", port=5001)
Пример #23
0
from flask import Flask
from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface
from flask.ext.login import LoginManager
from flask.ext.gravatar import Gravatar

# Create the Flask app
app = Flask(__name__, static_folder="../static", template_folder="../templates")

# Config
app.config.from_object("flask_app.config.Configuration")

# secret key
app.secret_key = "A0Zr98j/3yX R~XHH!jmN]LWX/,?RT"

# Login manager
login_manager = LoginManager()
login_manager.login_view = "login"
login_manager.init_app(app)

# gravatar
gravatar = Gravatar(app, size=40, rating="g", default="retro", force_default=False, use_ssl=False, base_url=None)

# Connect to MongoLabs
db = MongoEngine(app)
app.session_interface = MongoEngineSessionInterface(db)
Пример #24
0
def create_app(config=None, debug=False):
    """
    Inicializa la aplicación Flask. Carga los siguientes módulos:
     - index: página de inicio
     - page: páginas estáticas
     - user: gestión del usuario
     - files: búsqueda y obtención de ficheros
     - status: servicio de monitorización de la aplicación

    Y además, inicializa los siguientes servicios:
     - Configuración: carga valores por defecto y modifica con el @param config
     - Web Assets: compilación y compresión de recursos estáticos
     - i18n: detección de idioma en la URL y catálogos de mensajes
     - Cache y auth: Declarados en el módulo services
     - Files: Clases para acceso a datos
    """
    app = Flask(__name__)
    app.config.from_object(defaults)
    app.debug = debug
    app.session_interface = NoSessionInterface()

    # Configuración
    if config:
        app.config.from_object(config)

    # Runtime config
    app.config["DOWNLOADER_FILES"] = {
        k: os.path.join(os.path.abspath(os.path.join(app.root_path, "../downloads")), v)
        for k, v in app.config["DOWNLOADER_FILES"].iteritems()
    }

    # Gestión centralizada de errores
    if app.config["SENTRY_DSN"]:
        sentry.init_app(app)
    logging.getLogger().setLevel(logging.DEBUG if debug else logging.INFO)

    # Configuración dependiente de la versión del código
    revision_filename_path = os.path.join(os.path.dirname(app.root_path), "revision")
    if os.path.exists(revision_filename_path):
        f = open(revision_filename_path, "r")
        data = f.read()
        f.close()
        revisions = tuple(
            tuple(i.strip() for i in line.split("#")[0].split())
            for line in data.strip().split("\n")
            if line.strip() and not line.strip().startswith("#")
        )
        revision_hash = md5(data).hexdigest()
        app.config.update(
            CACHE_KEY_PREFIX="%s%s/"
            % (app.config["CACHE_KEY_PREFIX"] if "CACHE_KEY_PREFIX" in app.config else "", revision_hash),
            REVISION_HASH=revision_hash,
            REVISION=revisions,
        )
    else:
        app.config.update(REVISION_HASH=None, REVISION=())

    # Registra valores/funciones para plantillas
    app.jinja_env.globals["u"] = u

    # Blueprints
    print "Registering blueprints."
    app.register_blueprint(index)
    register_files_converters(app)
    app.register_blueprint(news)
    app.register_blueprint(files)
    for blueprint in downloader_blueprints:
        app.register_blueprint(blueprint)

    # Registra filtros de plantillas
    register_filters(app)

    # Web Assets
    print "Web assets."
    if not os.path.isdir(app.static_folder + "/gen"):
        os.mkdir(app.static_folder + "/gen")
    assets = Environment(app)
    app.assets = assets
    assets.debug = app.debug
    assets.versions = "timestamp"

    register_filter(JsSlimmer)
    register_filter(CssSlimmer)

    assets.register(
        "css_torrents",
        Bundle("main.css", "jquery.treeview.css", filters="pyscss", output="gen/main.css", debug=False),
        "960_24_col.css",
        filters="css_slimmer",
        output="gen/torrents.css",
    )
    assets.register(
        "js_torrents",
        Bundle(
            "modernizr.js",
            "jquery.js",
            "jquery.treeview.js",
            "jquery.cookie.js",
            "jquery.colorbox-min.js",
            "torrents.js",
            "cookies.js",
            filters="rjsmin",
            output="gen/torrents.js",
        ),
    )

    print "Initializing services."
    # CSRF protection
    csrf.init_app(app)

    # Traducciones
    babel.init_app(app)

    @babel.localeselector
    def get_locale():
        return "en"

    # Cache
    cache.init_app(app)

    # Mail
    mail.init_app(app)

    print "Database accesses:"
    # Acceso a bases de datos
    filesdb.init_app(app)
    print "* files"
    torrentsdb.init_app(app, searchd)
    print "* torrents"

    pagesdb.init_app(app)
    print "* pages"
    # feedbackdb.init_app(app)
    # print "* feedback"
    configdb.init_app(app)
    print "* config"
    entitiesdb.init_app(app)
    print "* entities"

    for service_name, params in app.config["DATA_SOURCE_SHARING"].iteritems():
        eval(service_name).share_connections(**{key: eval(value) for key, value in params.iteritems()})

    configdb.register_action("flush_cache", cache.clear, _unique=True)

    print "Blacklists."
    # Blacklists
    if app.debug:
        blacklists.debug = True

    blacklist_data = torrentsdb.get_blacklists()
    blacklists.load_data(blacklist_data)
    blacklists.clone_into(blacklists_adult, lambda x: x != "misconduct")

    def refresh_blacklists():
        """
        Refresh blacklists.
        """
        blacklists.load_data(torrentsdb.get_blacklists())

    configdb.register_action("refresh_blacklists", refresh_blacklists)

    def update_downloader_properties():
        """
        Downloader updated.
        """
        local_cache["downloader_properties"] = get_downloader_properties()

    configdb.register_action("update_downloader", update_downloader_properties)
    with app.app_context():
        local_cache["downloader_properties"] = get_downloader_properties()

    # IPs españolas
    spanish_ips.load(os.path.join(os.path.dirname(app.root_path), app.config["SPANISH_IPS_FILENAME"]))

    @app.before_first_request
    def init_process():
        if not eventmanager.is_alive():
            # Fallback inicio del eventManager
            eventmanager.start()

    print "Event manager."

    # Profiler
    # profiler.init_app(app, feedbackdb)

    # Servicio de búsqueda
    eventmanager.once(searchd.init_app, hargs=(app, filesdb, entitiesdb, profiler))

    # Refresco de conexiones
    eventmanager.once(filesdb.load_servers_conn)
    eventmanager.interval(app.config["FOOCONN_UPDATE_INTERVAL"], filesdb.load_servers_conn)

    # Refresco de configuración
    eventmanager.once(configdb.pull)
    eventmanager.interval(app.config["CONFIG_UPDATE_INTERVAL"], configdb.pull)

    # Categorias
    categories_cache.init_app(app.config["TORRENTS_CATEGORIES"], app.config["SUBCATEGORIES_MIN_OCCURS"])
    categories_cache.update_subcategories(torrentsdb.get_subcategories())

    def refresh_subcategories():
        """
        Refresh subcategories.
        """
        categories_cache.update_subcategories(torrentsdb.get_subcategories())

    configdb.register_action("refresh_subcategories", refresh_subcategories)
    eventmanager.interval(app.config["CATEGORIES_REFRESH_INTERVAL"], refresh_subcategories)

    @app.before_request
    def before_request():
        g.cache_code = ""
        g.last_modified = None

        # No preprocesamos la peticiones a static
        if request.path.startswith("/static/"):
            g.must_cache = False
            return

        g.blacklisted_content = False
        init_g(current_app)

        if not g.domain:
            return multidomain.redirect_to_domain(g.domains_family[0], 301)

        # ignora peticiones sin blueprint
        if request.blueprint is None and request.path.endswith("/"):
            if "?" in request.url:
                root = request.url_root[:-1]
                path = request.path.rstrip("/")
                query = request.url
                if not isinstance(query, unicode):
                    query = query.decode("utf-8")
                query = query[query.find(u"?") :]
                return redirect(root + path + query, 301)
            return redirect(request.url.rstrip("/"), 301)

    @app.after_request
    def after_request(response):
        if request.user_agent.browser == "msie":
            response.headers["X-UA-Compatible"] = "IE-edge"
        if g.must_cache:
            response.headers["X-Cache-Control"] = "max-age=%d" % g.must_cache
        if g.cache_code:
            response.headers["X-Cache-Code"] = g.cache_code
        if g.last_modified:
            response.headers["Last-Modified"] = utils.formatdate(
                time.mktime(max(g.last_modified, current_app.config["APP_LAST_MODIFIED"]).timetuple()), False, True
            )
        return response

    # Páginas de error
    errors = {
        404: ("Page not found", "The requested address does not exists."),
        410: ("File not available", "The file you are trying to access has been removed."),
        500: ("An error happened", "We had some problems displaying this page. Maybe later we can show it to you."),
        503: ("Service unavailable", "This page is temporarily unavailable. Please try again later."),
    }

    @allerrors(app, 400, 401, 403, 404, 405, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 500, 501, 502, 503)
    def all_errors(e):
        error = e.code if hasattr(e, "code") else 500
        title, description = errors[error if error in errors else 500]

        init_g(current_app)
        if not g.domain:
            return multidomain.redirect_to_domain(g.domains_family[0], 301)

        g.title.append(title)
        return render_template("error.html", code=str(error), title=title, description=description), error

    print "App ready."
    return app
Пример #25
0
from flask import Flask, render_template, session
from flask.ext.sqlalchemy import SQLAlchemy
from flask_debugtoolbar import DebugToolbarExtension

app = Flask(__name__)

app.config.from_object("config")

db = SQLAlchemy(app)

from app.http_session import SqlAlchemySessionInterface

app.session_interface = SqlAlchemySessionInterface()
toolbar = DebugToolbarExtension(app)


@app.route("/")
def index():
    if not "test" in session:
        session["test"] = 0
    else:
        session["test"] = session["test"] + 1
    return render_template("index.html")
Пример #26
0
                return current_user.is_authenticated()
            return True

    return MethodSessionAuthentication


class InfiniteSecureCookieSessionInterface(SecureCookieSessionInterface):
    """Longer session"""

    def get_expiration_time(self, app1, session):
        session.permanent = True
        return super(InfiniteSecureCookieSessionInterface, self).get_expiration_time(app1, session)


app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(days=90)
app.session_interface = InfiniteSecureCookieSessionInterface()


class BaseResourceView(ResourceView):
    authentication_methods = [session_authentication_fabric(["POST", "UPDATE", "DELETE"])]


# models


class Role(db.Document, RoleMixin):
    name = db.StringField(max_length=80, unique=True)
    description = db.StringField(max_length=255)


class User(db.Document, UserMixin):
Пример #27
0
from mwoauth import AccessToken, ConsumerToken, RequestToken, Handshaker
from requests_oauthlib import OAuth1
import requests
from video2commons.config import consumer_key, consumer_secret, api_url

from video2commons.frontend.redisession import RedisSessionInterface
from video2commons.frontend.shared import redisconnection, check_banned
from video2commons.frontend.api import api
from video2commons.frontend.i18n import i18nblueprint, translate as _, getlanguage, is_rtl

consumer_token = ConsumerToken(consumer_key, consumer_secret)
handshaker = Handshaker(api_url, consumer_token)

app = Flask(__name__)

app.session_interface = RedisSessionInterface(redisconnection)

app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 3600

app.jinja_env.globals["_"] = _
app.jinja_env.globals["lang"] = getlanguage
app.jinja_env.tests["rtl"] = is_rtl

app.register_blueprint(api, url_prefix="/api")
app.register_blueprint(i18nblueprint, url_prefix="/i18n")


@app.errorhandler(Exception)
def all_exception_handler(e):
    """Handle an exception and show the traceback to error page."""
    try:
Пример #28
0
def create_app(config_filename="settings.py", config_dict=None):
    """Creates a Pjuu WSGI application with the passed in config_filename.

    ``config_filename`` should be a Python file as per the default. To
    create one simply copy the settings.py file and change the settings
    to suit yourself

    ``settings_dict`` can be used to override any settings inside
    ``config_filename``. This is useful for testing. See run_tests.py for an
    example

    """
    # Pylint has suggested I don't set config_dict to a empty dict, we now have
    # to check if it is None and then assign an empty dict
    if config_dict is None:  # pragma: no cover
        config_dict = {}

    # Create application
    app = Flask(__name__)

    # Load configuration from the Python file passed as config_filename
    app.config.from_pyfile(config_filename)
    # Override the settings from config_filename, even add new ones :)
    # This is useful for testing, we use it for Travis-CI, see run_tests.py
    app.config.update(config_dict)

    # You can also set an environment variable called PJUU_SETTINGS this will
    # override all other Settings applied to Pjuu so long as you define them
    app.config.from_envvar("PJUU_SETTINGS", silent=True)

    # Sentry logger
    # We now only use Sentry for logging all our in application errors
    # We do not need it if debug is True as we expect there could be errors
    # and we get full visibility.
    if not app.debug:  # pragma: no cover
        sentry.init_app(app)

    # Initialize the PyMongo client
    mongo.init_app(app)

    # This is the _MAIN_ redis client. ONLY STORE DATA HERE
    redis.init_app(app)

    # Create Flask-Mail
    mail.init_app(app)

    # Create the Redis session interface
    redis_sessions.init_app(app, "SESSION_REDIS")

    # Initialize CSRF protection
    csrf.init_app(app)

    # Set session handler to Redis
    app.session_interface = RedisSessionInterface(redis=redis_sessions)

    # Static URLs will have an mtime appended as a query string as cache buster
    @app.url_defaults
    def cache_buster(endpoint, values):
        if "static" == endpoint or ".static" == endpoint[-7:]:
            filename = values.get("filename", None)
            if filename:  # pragma: no branch
                static_folder = app.static_folder

                param_name = "h"
                while param_name in values:
                    # Doesn't need coverage. Simple stops the param_name 'h'
                    # colliding with any future param
                    param_name = "_" + param_name  # pragma: no cover

                # Get the mtime of the file
                values[param_name] = int(os.stat(os.path.join(static_folder, filename)).st_mtime)

    # Register error handlers
    from pjuu.lib.errors import register_errors

    register_errors(app)

    with app.app_context():
        # Import all Pjuu stuffs
        # Load the blueprints
        from pjuu.auth.views import auth_bp

        app.register_blueprint(auth_bp)
        from pjuu.posts.views import posts_bp

        app.register_blueprint(posts_bp)
        from pjuu.users.views import users_bp

        app.register_blueprint(users_bp)
        from pjuu.lib.dashboard import dashboard_bp

        app.register_blueprint(dashboard_bp)
        from pjuu.lib.pages import pages_bp

        app.register_blueprint(pages_bp)

    # Return a nice shiny new Pjuu WSGI application :)
    return app
Пример #29
0
view_cache = Cache(
    app,
    config={
        "CACHE_TYPE": "redis",
        "CACHE_KEY_PREFIX": cache_prefix,
        "CACHE_DEFAULT_TIMEOUT": cache_timeout,
        "CACHE_REDIS_HOST": get_env_variable("DATAVIVA_REDIS_HOST", "localhost"),
        "CACHE_REDIS_PORT": get_env_variable("DATAVIVA_REDIS_PORT", 6379),
        "CACHE_REDIS_PASSWORD": get_env_variable("DATAVIVA_REDIS_PW", None),
    },
)

# Set session store as server side (Redis)
redis_sesh = RedisSessionInterface(view_cache, "session:")
if redis_sesh.redis:
    app.session_interface = redis_sesh

# Global Latest Year Variables
from dataviva.api.stats.util import get_or_set_years

__year_range__ = get_or_set_years(view_cache, "general:data_years")

# login manager for user management
lm = LoginManager()
lm.init_app(app)

# babel configuration for lang support
babel = Babel(app)

# add a few extra template filters to jinja
app.jinja_env.globals["moment_js"] = jinja_momentjs
Пример #30
0
import imp, os, sys
import traceback
from flask import Flask, request, session, redirect, url_for, render_template, make_response, abort
from serverside_sessions import create_managed_session
from StringIO import StringIO
from werkzeug import secure_filename
import pandas

root = os.path.dirname(os.path.realpath(__file__)) + os.sep

app = Flask(__name__)
app.secret_key = "v\xfc\x9d\xfb\xa2\xc7uj\x97F\xc2\xb2\x14\xa4\xaa\xef\x8e\xedz\xe4\xc0daI"
app.debug = True
# Server-side session handeling
app.config["SESSION_PATH"] = root + "_SESSION_DATA" + os.sep
app.session_interface = create_managed_session(app)
# File uploads
app.config["UPLOAD_FOLDER"] = root + "_UPLOADS" + os.sep
app.config["MAX_CONTENT_LENGTH"] = 5 * 1024 * 1024  # 5 MB limit
ALLOWED_EXTENSIONS = set(["xml"])


def allowed_file(filename):
    return "." in filename and filename.rsplit(".", 1)[1] in ALLOWED_EXTENSIONS


class DataNotLoaded(Exception):
    pass


try: