Пример #1
0
    def __init__(self) -> None:
        #
        # Flask App
        #
        app = MultiStaticFlask("koseki")
        app.wsgi_app = ReverseProxied(app.wsgi_app)
        app.config.from_object(KosekiConfig())
        app.config.from_pyfile(os.path.join("..", "koseki.cfg"))
        self.app: Flask = app

        #
        # Theme
        #
        static_folders: list[str] = []
        install_theme(app, "koseki", static_folders)

        theme: str = app.config["THEME"]
        if theme is not None and len(theme.strip()) > 0 and theme != "koseki":
            install_theme(app, theme, static_folders)

        app.static_folder = static_folders

        #
        # Storage
        #
        if app.config["DB_TYPE"].lower() == "sqlite":
            self.storage = Storage("sqlite:///%s" %
                                   app.config["DB_SQLITE_PATH"])
        elif app.config["DB_TYPE"].lower() == "mysql":
            self.storage = Storage("mysql://%s:%s@%s/%s" % (
                app.config["DB_USER"],
                app.config["DB_PASSWORD"],
                app.config["DB_HOST"],
                app.config["DB_DATABASE"],
            ))
        else:
            raise ValueError(
                "DB_TYPE is unsupported. Please choose between sqlite/mysql.")
        # Return connections to db pool after closure
        self.app.teardown_appcontext(self.storage.close)

        # Misc Utilities
        self.auth = KosekiAuth(self.storage)
        self.mail = KosekiMailer(self.app)
        self.util = KosekiUtil(app, self.auth, self.storage, self.mail)
        self.scheduler = KosekiScheduler(app, self.storage, self.mail,
                                         self.util)
        self.plugins = KosekiPluginManager(self.app, self.storage, self.auth,
                                           self.util, self.scheduler)
Пример #2
0
def create_app(module_name):
    from flask import Flask
    from flask_multistatic import MultiStaticFlask
    from flask_cors import CORS, cross_origin

    # 서버내 폴더위치지정 외, 타 폴더지정시 스테틱폴더옵션을 사용한다.
    # js,css등은 서버내 폴더내 위치시켜 /static/js등으로 지정할 수 있다.
    app = MultiStaticFlask(module_name)

    # MultistaticFlask
    # app.static_folder=setting.static_folder
    app.static_folder=static_folder

    # cross origin 
    CORS(app)

    return app
Пример #3
0
from functools import wraps  # noqa: E402
from sqlalchemy.exc import SQLAlchemyError  # noqa: E402

from flask_multistatic import MultiStaticFlask  # noqa: E402

if os.environ.get('PAGURE_PERFREPO'):
    import pagure.perfrepo as perfrepo  # noqa: E402
else:
    perfrepo = None

import pagure.exceptions  # noqa: E402

logging.basicConfig()

# Create the application.
APP = MultiStaticFlask('pagure')

if perfrepo:
    # Do this as early as possible.
    # We want the perfrepo before_request to be the very first thing to be run,
    # so that we can properly setup the stats before the request.
    APP.before_request(perfrepo.reset_stats)

APP.jinja_env.trim_blocks = True
APP.jinja_env.lstrip_blocks = True

# set up FAS
APP.config.from_object('pagure.default_config')

if 'PAGURE_CONFIG' in os.environ:
    APP.config.from_envvar('PAGURE_CONFIG')
Пример #4
0
from utils.web import verify_sessionId, analysis_sessionId, tpl_adminlogin_required, get_redirect_url
from hlm import UserAppManager, UserSSOManager, UserMsgManager, UserProfileManager
from views import FrontBlueprint, ApiBlueprint
from flask import request, g, jsonify
from flask_pluginkit import PluginManager
from flask_multistatic import MultiStaticFlask as Flask
reload(sys)
sys.setdefaultencoding('utf-8')

__author__ = 'staugur'
__email__ = '*****@*****.**'
__doc__ = '统一认证与单点登录系统'
__date__ = '2018-01-09'

# 初始化定义application
app = Flask(__name__)
app.config.update(SECRET_KEY=os.urandom(24),
                  MAX_CONTENT_LENGTH=4 * 1024 * 1024)

# 初始化接口管理器
api = DO({
    "userapp": UserAppManager(),
    "usersso": UserSSOManager(),
    "usermsg": UserMsgManager(),
    "userprofile": UserProfileManager(),
})

# 初始化插件管理器(自动扫描并加载运行)
plugin = PluginManager(app)

# 注册视图包中蓝图
Пример #5
0
                    format="%(asctime)s %(levelname)s %(message)s")

menu = MenuSwitch()
dev_mode = setting.dev_mode
# , static_folder='static'
# static_url_path='/static')
# 서버내 폴더위치지정 외, 타 폴더지정시 스테틱폴더옵션을 사용한다.
# js,css등은 서버내 폴더내 위치시켜 /static/js등으로 지정할 수 있다.

# app = Flask(__name__ , static_folder='D:\\내사진\\Album 2017')
# app = Flask(__name__, static_folder='static')
# app = Flask(__name__, static_url_path='/app/static/html')
# app.config['STATIC_FOLDER'] = 'D:\\내사진\\Album 2017'
# app.config['STATIC_FOLDER'] = 'static'

app = MultiStaticFlask(__name__)

# MultistaticFlask
app.static_folder = setting.static_folder

# cross origin
CORS(app)


@app.route('/')
def init():
    # print(menu.menu_3().keys)
    resp = [key for key, value in menu.menu_3().items()]
    # return render_template('index.html',list=resp)
    print("WED Initial")
Пример #6
0
def create_app(config=None):
    """ Create the flask application. """
    app = MultiStaticFlask(__name__)
    app.config = pagure_config

    if config:
        app.config.update(config)

    if app.config.get('SESSION_TYPE', None) is not None:
        import flask_session
        flask_session.Session(app)

    logging.basicConfig()
    logging.config.dictConfig(app.config.get('LOGGING') or {'version': 1})

    app.jinja_env.trim_blocks = True
    app.jinja_env.lstrip_blocks = True

    if perfrepo:
        # Do this as early as possible.
        # We want the perfrepo before_request to be the very first thing
        # to be run, so that we can properly setup the stats before the
        # request.
        app.before_request(perfrepo.reset_stats)

    if pagure_config.get('THEME_TEMPLATE_FOLDER', False):
        # Jinja can be told to look for templates in different folders
        # That's what we do here
        template_folder = pagure_config['THEME_TEMPLATE_FOLDER']
        if template_folder[0] != '/':
            template_folder = os.path.join(app.root_path, app.template_folder,
                                           template_folder)
        import jinja2
        # Jinja looks for the template in the order of the folders specified
        templ_loaders = [
            jinja2.FileSystemLoader(template_folder),
            app.jinja_loader,
        ]
        app.jinja_loader = jinja2.ChoiceLoader(templ_loaders)

    if pagure_config.get('THEME_STATIC_FOLDER', False):
        static_folder = pagure_config['THEME_STATIC_FOLDER']
        if static_folder[0] != '/':
            static_folder = os.path.join(app.root_path, 'static',
                                         static_folder)
        # Unlike templates, to serve static files from multiples folders we
        # need flask-multistatic
        app.static_folder = [
            static_folder,
            os.path.join(app.root_path, 'static'),
        ]

    auth = pagure_config.get('PAGURE_AUTH', None)
    if auth in ['fas', 'openid']:
        # Only import and set flask_fas_openid if it is needed
        from pagure.ui.fas_login import FAS
        FAS.init_app(app)
    elif auth == 'oidc':
        # Only import and set flask_fas_openid if it is needed
        from pagure.ui.oidc_login import oidc, fas_user_from_oidc
        oidc.init_app(app)
        app.before_request(fas_user_from_oidc)

    # Report error by email
    if not app.debug and not pagure_config.get('DEBUG', False):
        app.logger.addHandler(
            pagure.mail_logging.get_mail_handler(
                smtp_server=pagure_config.get('SMTP_SERVER', '127.0.0.1'),
                mail_admin=pagure_config.get('MAIL_ADMIN',
                                             pagure_config['EMAIL_ERROR']),
                from_email=pagure_config.get('FROM_EMAIL',
                                             '*****@*****.**')))

    # Support proxy
    app.wsgi_app = pagure.proxy.ReverseProxied(app.wsgi_app)

    # Back port 'equalto' to older version of jinja2
    app.jinja_env.tests.setdefault('equalto',
                                   lambda value, other: value == other)

    # Import the application

    from pagure.api import API  # noqa: E402
    app.register_blueprint(API)

    from pagure.ui import UI_NS  # noqa: E402
    app.register_blueprint(UI_NS)

    from pagure.internal import PV  # noqa: E402
    app.register_blueprint(PV)

    app.before_request(set_request)
    app.teardown_request(end_request)

    # Only import the login controller if the app is set up for local login
    if pagure_config.get('PAGURE_AUTH', None) == 'local':
        import pagure.ui.login as login
        app.before_request(login._check_session_cookie)
        app.after_request(login._send_session_cookie)

    if perfrepo:
        # Do this at the very end, so that this after_request comes last.
        app.after_request(perfrepo.print_stats)

    app.add_url_rule('/login/', view_func=auth_login, methods=['GET', 'POST'])
    app.add_url_rule('/logout/', view_func=auth_logout)

    return app
Пример #7
0
import flask
import pygit2
import werkzeug
from functools import wraps
from sqlalchemy.exc import SQLAlchemyError

from pygments import highlight
from pygments.lexers.text import DiffLexer
from pygments.formatters import HtmlFormatter

from flask_multistatic import MultiStaticFlask

from werkzeug.routing import BaseConverter

# Create the application.
APP = MultiStaticFlask(__name__)
APP.jinja_env.trim_blocks = True
APP.jinja_env.lstrip_blocks = True

# set up FAS
APP.config.from_object('pagure.default_config')

if 'PAGURE_CONFIG' in os.environ:
    APP.config.from_envvar('PAGURE_CONFIG')


if APP.config.get('THEME_TEMPLATE_FOLDER', False):
    # Jinja can be told to look for templates in different folders
    # That's what we do here
    template_folder = APP.config['THEME_TEMPLATE_FOLDER']
    if template_folder[0] != '/':
Пример #8
0
import os
import requests
from dotenv import load_dotenv
from flask import send_file, jsonify
from flask_multistatic import MultiStaticFlask
from livereload import Server

# load .env variables

load_dotenv(os.path.join(os.path.dirname(__file__), '.env'))

# app configuration

app = MultiStaticFlask(__name__, static_path='')

app.static_folder = [
    os.path.join(app.root_path, 'node_modules'),
    os.path.join(app.root_path, 'assets')
]

if os.environ['PYTHON_ENV'] == 'production':
    app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False

# requests configuration

session = requests.Session()
session.headers.update(
    {'Authorization': 'Client-ID %s' % os.environ['IMGUR_CLIENT_ID']})
url = 'https://api.imgur.com/3/gallery/search/top/0/'

# routes
Пример #9
0
def create_app(test_config=None):
    # create and configure the app
    app = MultiStaticFlask(__name__, instance_relative_config=True)
    babel = Babel(app)
    CORS(app, supports_credentials=True)

    # Add custom static location
    if custom_id:
        app.static_folder = [
            os.path.join(app.root_path.replace('webApp', ''),
                         'custom/' + custom_id[0] + '/webApp/static/'),
            os.path.join(app.root_path, 'static')
        ]
    else:
        app.static_folder = [
            os.path.join(app.root_path, 'static'),
            os.path.join(app.root_path, 'static')
        ]

    app.config.from_mapping(
        SECRET_KEY='§§SECRET§§',
        CONFIG_FILE=os.path.join(app.instance_path, 'config.ini'),
        CONFIG_FOLDER=os.path.join(app.instance_path, 'config/'),
        UPLOAD_FOLDER=os.path.join(app.instance_path, 'upload/'),
        PER_PAGE=16,
        BABEL_TRANSLATION_DIRECTORIES=os.path.join(app.static_folder[0],
                                                   'babel/translations/')
        if os.path.isdir(app.static_folder[0] + 'babel/translations') else
        os.path.join(app.static_folder[1], 'babel/translations/'),
        # array key is the babel language code
        # index 0 is the label
        # index 1 is the locale language code in the config.ini
        # index 2 is the localeocr language code in the config.ini (tesseract)
        LANGUAGES={
            'fr': ['Français', 'fr_FR', 'fra'],
            'en': ['English', 'en_EN', 'eng']
        },
    )

    app.register_blueprint(ws.bp)
    app.register_blueprint(pdf.bp)
    app.register_blueprint(auth.bp)
    app.register_blueprint(user.bp)
    app.register_blueprint(supplier.bp)
    app.register_blueprint(dashboard.bp)
    app.register_blueprint(splitter.bp)
    app.add_url_rule('/', endpoint='index')

    # Add custom templates location
    if custom_id:
        array_location = [custom_id[1] + '/webApp', 'webApp']
    else:
        array_location = ['webApp']

    templates_locations = jinja2.ChoiceLoader([
        app.jinja_loader,
        jinja2.FileSystemLoader(array_location),
    ])
    app.jinja_loader = templates_locations

    db.init_app(app)

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    @app.route('/')
    def index():
        return redirect(url_for('pdf.index', time='TODAY', status='NEW'))

    @babel.localeselector
    def get_locale():
        if 'lang' not in session:
            session['lang'] = request.accept_languages.best_match(
                app.config['LANGUAGES'].keys())

        return session['lang']

    return app
Пример #10
0
from flask import Flask
from flask_multistatic import MultiStaticFlask
# app = Flask(__name__, static_folder="build/static", template_folder="build")
app = MultiStaticFlask(
    __name__,
    static_folder=["build/admin_panel/static", "build/user_blog/static"],
    template_folder="build")
from app import routes