예제 #1
0
def build(c):
    app = create_app()
    HTMLMIN(app)
    app.config['MINIFY_PAGE'] = True
    app.config['FREEZER_RELATIVE_URLS']=True
    app.config['FREEZER_REMOVE_EXTRA_FILES']=True
    app.config['FREEZER_DESTINATION']="../docs"
    app.config['FREEZER_STATIC_IGNORE']=['js/*','css/*','.webassets-cache/*']
    freezer = Freezer(app)
    freezer.freeze()
예제 #2
0
def create_app():
    """ Create the Flask application """

    app = Flask(__name__, static_url_path='/static')
    app.config.from_object('config')

    # page performance tweeks
    app.config['MINIFY_PAGE'] = True
    COMPRESS.init_app(app)
    HTMLMIN(app)

    # db init
    mongo = PyMongo(app)
    app.mongo = mongo

    # register blueprint modules
    app.register_blueprint(update.BP)
    app.register_blueprint(sources.BP)
    app.register_blueprint(search.BP)

    @app.route("/")
    def home():
        result = database.find_all({
            "date": {
                '$gte': datetime.now() - timedelta(hours=48)
            }
        })
        return render_template('pages/home.html', entries=result)

    @app.errorhandler(500)
    def internal_error(error):
        app.logger.error('internal error %s', error)
        return render_template(
            "message.html", msg="Something went wrong!"), 500

    @app.errorhandler(404)
    def page_not_found(page):
        app.logger.info('page not found %s', page)
        return render_template(
            "message.html", msg="I think you are lost!"), 404

    @app.template_filter('strftime')
    def _jinja2_filter_datetime(date):
        date = dateutil.parser.parse(str(date))
        native = date.replace(tzinfo=None)
        new_format = '%a %d %b %X %Y'
        return native.strftime(new_format)

    return app
예제 #3
0
def create_app():
    app = Flask(__name__,
                static_url_path='/static',
                static_folder='static',
                instance_relative_config=False)

    app.url_map.converters['regex'] = RegexConverter

    # Remove strict slash from Werkzeug
    app.url_map.strict_slashes = False

    # Configurações
    app.config.from_object(rq_dashboard.default_settings)
    app.config.from_object(rq_scheduler_dashboard.default_settings)
    app.config.from_object('webapp.config.default')  # Configuração basica
    app.config.from_envvar('OPAC_CONFIG',
                           silent=True)  # configuração do ambiente
    app.logger.root.setLevel(app.config.get("LOG_LEVEL"))

    configure_apm_agent(app)

    # Sentry:
    if app.config['USE_SENTRY']:
        dsn = app.config['SENTRY_DSN']
        sentry.init_app(app, dsn=dsn, logging=True, level=logging.ERROR)

    # login
    login_manager.session_protection = 'strong'
    login_manager.login_view = 'admin.login_view'
    login_manager.init_app(app)

    # Minificando o HTML
    if app.config['MINIFY_PAGE']:
        HTMLMIN(app)
        logger.info('HTML minification has been activated.')

    # Registrando os filtros
    app.jinja_env.filters['trans_alpha2'] = custom_filters.trans_alpha2
    app.jinja_env.filters['datetimefilter'] = custom_filters.datetimefilter

    # i18n
    babel.init_app(app)
    # Debug Toolbar
    if app.config['DEBUG']:
        # Toolbar
        from flask_debugtoolbar import DebugToolbarExtension
        toolbar = DebugToolbarExtension()
        toolbar.init_app(app)
    # Mongo
    dbmongo.init_app(app)
    # SQLAlchemy
    dbsql.init_app(app)
    # Emails
    mail.init_app(app)
    # Cache:
    if app.config['CACHE_ENABLED']:
        cache.init_app(app, config=app.config)
    else:
        app.config['CACHE_TYPE'] = 'null'
        cache.init_app(app, config=app.config)

    # Interface do admin
    from .models import User, File, Image
    # from .admin import views
    from webapp.admin import views

    admin = flask_admin.Admin(app,
                              'OPAC admin',
                              index_view=views.AdminIndexView(),
                              template_mode='bootstrap3',
                              base_template="admin/opac_base.html")

    admin.add_view(
        views.CollectionAdminView(Collection,
                                  category=lazy_gettext('Catálogo'),
                                  name=lazy_gettext('Coleção')))
    admin.add_view(
        views.JournalAdminView(Journal,
                               category=lazy_gettext('Catálogo'),
                               name=lazy_gettext('Periódico')))
    admin.add_view(
        views.IssueAdminView(Issue,
                             category=lazy_gettext('Catálogo'),
                             name=lazy_gettext('Número')))
    admin.add_view(
        views.ArticleAdminView(Article,
                               category=lazy_gettext('Catálogo'),
                               name=lazy_gettext('Artigo')))
    admin.add_view(
        views.SponsorAdminView(Sponsor,
                               category=lazy_gettext('Catálogo'),
                               name=lazy_gettext('Financiador')))
    admin.add_view(
        views.PressReleaseAdminView(PressRelease,
                                    category=lazy_gettext('Catálogo'),
                                    name=lazy_gettext('Press Release')))
    admin.add_view(views.NewsAdminView(News, name=lazy_gettext('Notícias')))
    admin.add_view(
        views.FileAdminView(File,
                            dbsql.session,
                            category=lazy_gettext('Ativos')))
    admin.add_view(
        views.ImageAdminView(Image,
                             dbsql.session,
                             category=lazy_gettext('Ativos')))
    admin.add_view(views.PagesAdminView(Pages, name=lazy_gettext('Páginas')))
    admin.add_view(
        views.AuditLogEntryAdminView(AuditLogEntry,
                                     category=lazy_gettext('Gestão'),
                                     name=lazy_gettext('Auditoria: Páginas')))
    admin.add_view(
        views.UserAdminView(User,
                            dbsql.session,
                            category=lazy_gettext('Gestão'),
                            name=lazy_gettext('Usuário')))

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

    # Setup RQ Dashboard e Scheduler: - mover para um modulo proprio
    def check_user_logged_in_or_redirect():
        if not current_user.is_authenticated:
            flash(u'Please log in to access this page.')
            return redirect(
                url_for('admin.login_view', next=request.path or '/'))

    rq_scheduler_dashboard.blueprint.before_request(
        check_user_logged_in_or_redirect)
    rq_dashboard.blueprint.before_request(check_user_logged_in_or_redirect)
    app.register_blueprint(rq_scheduler_dashboard.blueprint,
                           url_prefix='/admin/scheduler')
    app.register_blueprint(rq_dashboard.blueprint, url_prefix='/admin/workers')

    # FIM do setup RQ Dashboard e Scheduler: - mover para um modulo proprio

    app.wsgi_app = ProxyFix(app.wsgi_app)

    return app
예제 #4
0
#pymysql.install_as_MySQLdb()


class MiniJSONEncoder(JSONEncoder):
    """Minify JSON output."""
    item_separator = ','
    key_separator = ':'


cache = Cache(config={'CACHE_TYPE': 'simple', 'CACHE_THRESHOLD': 1000})
nav = Nav()
mail = Mail()
db = SQLAlchemy()
csrf = CsrfProtect()
compress = Compress()
htmlmin = HTMLMIN()
basedir = os.path.abspath(os.path.dirname(__file__))

# Set up Flask-Login
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'frontend.login'


def create_app(configfile=None):
    app = Flask(__name__)
    AppConfig(app)
    Bootstrap(app)
    sql_dir = os.path.join(basedir, 'tmp/')
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(
        sql_dir, 'user-login.sqlite')
예제 #5
0
def create_app(app_name=None):
    # Configuration settings
    import config
    if not app_name:
        app_name = config.APP_NAME

    # Only enable password related functionality in server mode.
    if config.SERVER_MODE is True:
        # Some times we need to access these config params where application
        # context is not available (we can't use current_app.config in those
        # cases even with current_app.app_context())
        # So update these params in config itself.
        # And also these updated config values will picked up by application
        # since we are updating config before the application instance is
        # created.

        config.SECURITY_RECOVERABLE = True
        config.SECURITY_CHANGEABLE = True
        # Now we'll open change password page in alertify dialog
        # we don't want it to redirect to main page after password
        # change operation so we will open the same password change page again.
        config.SECURITY_POST_CHANGE_VIEW = 'browser.change_password'

    """Create the Flask application, startup logging and dynamically load
    additional modules (blueprints) that are found in this directory."""
    app = PgAdmin(__name__, static_url_path='/static')
    # Removes unwanted whitespace from render_template function
    app.jinja_env.trim_blocks = True
    app.config.from_object(config)
    app.config.update(dict(PROPAGATE_EXCEPTIONS=True))

    ##########################################################################
    # Setup logging and log the application startup
    ##########################################################################

    # Add SQL level logging, and set the base logging level
    logging.addLevelName(25, 'SQL')
    app.logger.setLevel(logging.DEBUG)
    app.logger.handlers = []

    # We also need to update the handler on the webserver in order to see
    # request. Setting the level prevents werkzeug from setting up it's own
    # stream handler thus ensuring all the logging goes through the pgAdmin
    # logger.
    logger = logging.getLogger('werkzeug')
    logger.setLevel(logging.INFO)

    # Set SQLITE_PATH to TEST_SQLITE_PATH while running test cases
    if (
        'PGADMIN_TESTING_MODE' in os.environ and
        os.environ['PGADMIN_TESTING_MODE'] == '1'
    ):
        config.SQLITE_PATH = config.TEST_SQLITE_PATH

    # Ensure the various working directories exist
    from pgadmin.setup import create_app_data_directory, db_upgrade
    create_app_data_directory(config)

    # File logging
    fh = logging.FileHandler(config.LOG_FILE, encoding='utf-8')
    fh.setLevel(config.FILE_LOG_LEVEL)
    fh.setFormatter(logging.Formatter(config.FILE_LOG_FORMAT))
    app.logger.addHandler(fh)
    logger.addHandler(fh)

    # Console logging
    ch = logging.StreamHandler()
    ch.setLevel(config.CONSOLE_LOG_LEVEL)
    ch.setFormatter(logging.Formatter(config.CONSOLE_LOG_FORMAT))
    app.logger.addHandler(ch)
    logger.addHandler(ch)

    # Log the startup
    app.logger.info('########################################################')
    app.logger.info('Starting %s v%s...', config.APP_NAME, config.APP_VERSION)
    app.logger.info('########################################################')
    app.logger.debug("Python syspath: %s", sys.path)

    ##########################################################################
    # Setup i18n
    ##########################################################################

    # Initialise i18n
    babel = Babel(app)

    app.logger.debug('Available translations: %s' % babel.list_translations())

    @babel.localeselector
    def get_locale():
        """Get the language for the user."""
        language = 'en'
        if config.SERVER_MODE is False:
            # Get the user language preference from the miscellaneous module
            if current_user.is_authenticated:
                user_id = current_user.id
            else:
                user = user_datastore.get_user(config.DESKTOP_USER)
                if user is not None:
                    user_id = user.id
            user_language = Preferences.raw_value(
                'miscellaneous', 'user_language', None, user_id
            )
            if user_language is not None:
                language = user_language
        else:
            # If language is available in get request then return the same
            # otherwise check the session or cookie
            data = request.form
            if 'language' in data:
                language = data['language'] or language
                setattr(session, 'PGADMIN_LANGUAGE', language)
            elif hasattr(session, 'PGADMIN_LANGUAGE'):
                language = getattr(session, 'PGADMIN_LANGUAGE', language)
            elif hasattr(request.cookies, 'PGADMIN_LANGUAGE'):
                language = getattr(
                    request.cookies, 'PGADMIN_LANGUAGE', language
                )

        return language

    ##########################################################################
    # Setup authentication
    ##########################################################################

    app.config['SQLALCHEMY_DATABASE_URI'] = u'sqlite:///{0}?timeout={1}' \
        .format(config.SQLITE_PATH.replace(u'\\', u'/'),
                getattr(config, 'SQLITE_TIMEOUT', 500)
                )

    # Create database connection object and mailer
    db.init_app(app)

    ##########################################################################
    # Upgrade the schema (if required)
    ##########################################################################
    with app.app_context():
        # Run migration for the first time i.e. create database
        from config import SQLITE_PATH
        if not os.path.exists(SQLITE_PATH):
            db_upgrade(app)
        else:
            version = Version.query.filter_by(name='ConfigDB').first()
            schema_version = version.value

            # Run migration if current schema version is greater than the
            # schema version stored in version table
            if CURRENT_SCHEMA_VERSION >= schema_version:
                db_upgrade(app)

            # Update schema version to the latest
            if CURRENT_SCHEMA_VERSION > schema_version:
                version = Version.query.filter_by(name='ConfigDB').first()
                version.value = CURRENT_SCHEMA_VERSION
                db.session.commit()

    Mail(app)

    import pgadmin.utils.paths as paths
    paths.init_app(app)

    # Setup Flask-Security
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(None, user_datastore)

    ##########################################################################
    # Setup security
    ##########################################################################
    with app.app_context():
        config.CSRF_SESSION_KEY = Keys.query.filter_by(
            name='CSRF_SESSION_KEY').first().value
        config.SECRET_KEY = Keys.query.filter_by(
            name='SECRET_KEY').first().value
        config.SECURITY_PASSWORD_SALT = Keys.query.filter_by(
            name='SECURITY_PASSWORD_SALT').first().value

    # Update the app.config with proper security keyes for signing CSRF data,
    # signing cookies, and the SALT for hashing the passwords.
    app.config.update(dict({
        'CSRF_SESSION_KEY': config.CSRF_SESSION_KEY,
        'SECRET_KEY': config.SECRET_KEY,
        'SECURITY_PASSWORD_SALT': config.SECURITY_PASSWORD_SALT,
        'SESSION_COOKIE_DOMAIN': config.SESSION_COOKIE_DOMAIN
    }))

    security.init_app(app, user_datastore)

    # register custom unauthorised handler.
    app.login_manager.unauthorized_handler(pga_unauthorised)

    # Set the permanent session lifetime to the specified value in config file.
    app.permanent_session_lifetime = timedelta(
        days=config.SESSION_EXPIRATION_TIME)

    app.session_interface = create_session_interface(
        app, config.SESSION_SKIP_PATHS
    )

    # Make the Session more secure against XSS & CSRF when running in web mode
    if config.SERVER_MODE:
        paranoid = Paranoid(app)
        paranoid.redirect_view = 'browser.index'

    ##########################################################################
    # Load all available server drivers
    ##########################################################################
    driver.init_app(app)

    ##########################################################################
    # Register language to the preferences after login
    ##########################################################################
    @user_logged_in.connect_via(app)
    def register_language(sender, user):
        # After logged in, set the language in the preferences if we get from
        # the login page
        data = request.form
        if 'language' in data:
            language = data['language']

            # Set the user language preference
            misc_preference = Preferences.module('miscellaneous')
            user_languages = misc_preference.preference(
                'user_language'
            )

            if user_languages and language:
                language = user_languages.set(language)

    ##########################################################################
    # Register any local servers we can discover
    ##########################################################################
    @user_logged_in.connect_via(app)
    def on_user_logged_in(sender, user):
        # Keep hold of the user ID
        user_id = user.id

        # Get the first server group for the user
        servergroup_id = 1
        servergroups = ServerGroup.query.filter_by(
            user_id=user_id
        ).order_by("id")

        if servergroups.count() > 0:
            servergroup = servergroups.first()
            servergroup_id = servergroup.id

        '''Add a server to the config database'''

        def add_server(user_id, servergroup_id, name, superuser, port,
                       discovery_id, comment):
            # Create a server object if needed, and store it.
            servers = Server.query.filter_by(
                user_id=user_id,
                discovery_id=svr_discovery_id
            ).order_by("id")

            if servers.count() > 0:
                return

            svr = Server(user_id=user_id,
                         servergroup_id=servergroup_id,
                         name=name,
                         host='localhost',
                         port=port,
                         maintenance_db='postgres',
                         username=superuser,
                         ssl_mode='prefer',
                         comment=svr_comment,
                         discovery_id=discovery_id)

            db.session.add(svr)
            db.session.commit()

        # Figure out what servers are present
        if winreg is not None:
            arch_keys = set()
            proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()

            try:
                proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower()
            except Exception as e:
                proc_arch64 = None

            if proc_arch == 'x86' and not proc_arch64:
                arch_keys.add(0)
            elif proc_arch == 'x86' or proc_arch == 'amd64':
                arch_keys.add(winreg.KEY_WOW64_32KEY)
                arch_keys.add(winreg.KEY_WOW64_64KEY)

            for arch_key in arch_keys:
                for server_type in ('PostgreSQL', 'EnterpriseDB'):
                    try:
                        root_key = winreg.OpenKey(
                            winreg.HKEY_LOCAL_MACHINE,
                            "SOFTWARE\\" + server_type + "\Services", 0,
                            winreg.KEY_READ | arch_key
                        )
                        for i in xrange(0, winreg.QueryInfoKey(root_key)[0]):
                            inst_id = winreg.EnumKey(root_key, i)
                            inst_key = winreg.OpenKey(root_key, inst_id)

                            svr_name = winreg.QueryValueEx(
                                inst_key, 'Display Name'
                            )[0]
                            svr_superuser = winreg.QueryValueEx(
                                inst_key, 'Database Superuser'
                            )[0]
                            svr_port = winreg.QueryValueEx(inst_key, 'Port')[0]
                            svr_discovery_id = inst_id
                            svr_comment = gettext(
                                "Auto-detected %s installation with the data "
                                "directory at %s" % (
                                    winreg.QueryValueEx(
                                        inst_key, 'Display Name'
                                    )[0],
                                    winreg.QueryValueEx(
                                        inst_key, 'Data Directory'
                                    )[0]
                                )
                            )

                            add_server(
                                user_id, servergroup_id, svr_name,
                                svr_superuser, svr_port,
                                svr_discovery_id, svr_comment
                            )

                            inst_key.Close()
                    except Exception as e:
                        pass
        else:
            # We use the postgres-winreg.ini file on non-Windows
            try:
                from configparser import ConfigParser
            except ImportError:
                from ConfigParser import ConfigParser  # Python 2

            registry = ConfigParser()

        try:
            registry.read('/etc/postgres-reg.ini')
            sections = registry.sections()

            # Loop the sections, and get the data from any that are PG or PPAS
            for section in sections:
                if (
                    section.startswith('PostgreSQL/') or
                    section.startswith('EnterpriseDB/')
                ):
                    svr_name = registry.get(section, 'Description')
                    svr_superuser = registry.get(section, 'Superuser')

                    # getint function throws exception if value is blank.
                    # Ex: Port=
                    # In such case we should handle the exception and continue
                    # to read the next section of the config file.
                    try:
                        svr_port = registry.getint(section, 'Port')
                    except ValueError:
                        continue

                    svr_discovery_id = section
                    description = registry.get(section, 'Description')
                    data_directory = registry.get(section, 'DataDirectory')
                    if hasattr(str, 'decode'):
                        description = description.decode('utf-8')
                        data_directory = data_directory.decode('utf-8')
                    svr_comment = gettext(u"Auto-detected %s installation "
                                          u"with the data directory at %s" % (
                                              description,
                                              data_directory
                                          )
                                          )
                    add_server(user_id, servergroup_id, svr_name,
                               svr_superuser, svr_port, svr_discovery_id,
                               svr_comment)

        except Exception as e:
            pass

    @user_logged_in.connect_via(app)
    @user_logged_out.connect_via(app)
    def force_session_write(app, user):
        session.force_write = True

    @user_logged_out.connect_via(app)
    def clear_current_user_connections(app, user):
        from config import PG_DEFAULT_DRIVER
        from pgadmin.utils.driver import get_driver
        _driver = get_driver(PG_DEFAULT_DRIVER)
        _driver.gc_own()

    ##########################################################################
    # Load plugin modules
    ##########################################################################
    for module in app.find_submodules('pgadmin'):
        app.logger.info('Registering blueprint module: %s' % module)
        app.register_blueprint(module)

    ##########################################################################
    # Handle the desktop login
    ##########################################################################

    @app.before_request
    def before_request():
        """Login the default user if running in desktop mode"""

        # Check the auth key is valid, if it's set, and we're not in server
        # mode, and it's not a help file request.
        if not config.SERVER_MODE and app.PGADMIN_KEY != '':
            if (
                ('key' not in request.args or
                 request.args['key'] != app.PGADMIN_KEY) and
                request.cookies.get('PGADMIN_KEY') != app.PGADMIN_KEY and
                request.endpoint != 'help.static'
            ):
                abort(401)

        if not config.SERVER_MODE and not current_user.is_authenticated:
            user = user_datastore.get_user(config.DESKTOP_USER)
            # Throw an error if we failed to find the desktop user, to give
            # the sysadmin a hint. We'll continue to try to login anyway as
            # that'll through a nice 500 error for us.
            if user is None:
                app.logger.error(
                    'The desktop user %s was not found in the configuration '
                    'database.'
                    % config.DESKTOP_USER
                )
                abort(401)
            login_user(user)

    @app.after_request
    def after_request(response):
        if 'key' in request.args:
            domain = dict()
            if config.COOKIE_DEFAULT_DOMAIN and \
                    config.COOKIE_DEFAULT_DOMAIN != 'localhost':
                domain['domain'] = config.COOKIE_DEFAULT_DOMAIN
            response.set_cookie('PGADMIN_KEY', value=request.args['key'],
                                path=config.COOKIE_DEFAULT_PATH,
                                **domain)

        return response

    ##########################################################################
    # Cache busting
    ##########################################################################

    # Version number to be added to all static file url requests
    # This is used by url_for function when generating urls
    # This will solve caching issues when application is upgrading
    # This is called - Cache Busting
    @app.url_defaults
    def add_internal_version(endpoint, values):
        extensions = config.APP_VERSION_EXTN

        # Add the internal version only if it is set
        if config.APP_VERSION_PARAM is not None and \
           config.APP_VERSION_PARAM != '':
            # If there is a filename, add the version
            if 'filename' in values \
               and values['filename'].endswith(extensions):
                values[config.APP_VERSION_PARAM] = config.APP_VERSION_INT
            else:
                # Sometimes there may be direct endpoint for some files
                # There will be only one rule for such endpoints
                urls = [url for url in app.url_map.iter_rules(endpoint)]
                if len(urls) == 1 and urls[0].rule.endswith(extensions):
                    values[config.APP_VERSION_PARAM] = \
                        config.APP_VERSION_INT

    # Strip away internal version param before sending further to app as it was
    # required for cache busting only
    @app.url_value_preprocessor
    def strip_version_number(endpoint, values):
        if values and config.APP_VERSION_PARAM in values:
            values.pop(config.APP_VERSION_PARAM)

    ##########################################################################
    # Minify output
    ##########################################################################
    # HTMLMIN doesn't work with Python 2.6.
    if not config.DEBUG and sys.version_info >= (2, 7):
        from flask_htmlmin import HTMLMIN
        HTMLMIN(app)

    @app.context_processor
    def inject_blueprint():
        """Inject a reference to the current blueprint, if any."""
        return {
            'current_app': current_app,
            'current_blueprint': current_blueprint
        }

    ##########################################################################
    # All done!
    ##########################################################################

    return app
예제 #6
0
def client():
    app.config['TESTING'] = True
    app.config['MINIFY_PAGE'] = True
    HTMLMIN(app=app)
    client = app.test_client()
    yield client
예제 #7
0

# NEW DEV SETTINGSdeactivate
# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root@localhost/mill"
# app.config['SECURITY_PASSWORD_SALT'] = 'aijldbvaihwrbviqu3b4u8o'
# app.config['SECURITY_POST_LOGIN_VIEW'] = '/admin'
# app.config['SECURITY_TRACKABLE'] = True
# app.config['DEBUG'] = True


# OLD DEV SETTINGS
# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://localhost:5432/mill"
# app.config['SECURITY_PASSWORD_SALT'] = 'aijldbvaihwrbviqu3b4u8o'
# app.config['SECURITY_POST_LOGIN_VIEW'] = '/admin'
# app.config['SECURITY_TRACKABLE'] = True


# app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = 'username'

app.secret_key = "super secret key"
db = SQLAlchemy(app)
HTMLMIN(app)



# python3 -m venv venv
# source venv/bin/activate
# pip install Flask Flask-SQLAlchemy Flask-Migrate Flask-Script Flask-Security psycopg2 bcrypt pymysql raven[flask]
from flask_compress import Compress
from flask_executor import Executor
from flask_htmlmin import HTMLMIN
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_redis import FlaskRedis
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask_sqlalchemy_caching import CachingQuery
from sqlalchemy.orm import Session as SqlSession

cache = Cache()
compress = Compress()
db = SQLAlchemy(query_class=CachingQuery)
executor = Executor()
htmlmin = HTMLMIN(remove_empty_space=True)
migrate = Migrate()
redis_client = FlaskRedis()
sess = Session()

web_assets = Environment()
login_manager = LoginManager()

logging.basicConfig(level=logging.WARNING)


def get_or_create(session: SqlSession, model: Any, **kwargs: Any) -> Any:
    """Create model if not existing."""
    instance = model.query.filter_by(**kwargs).first()

    if instance:
예제 #9
0
def create_app(environment=None):

    app = Flask(__name__)
    app.config.from_object('config')
    app.config['ENVIRONMENT'] = environment

    # Wraps app in useful helpers.
    QRcode(app)
    HTMLMIN(app)

    # Initialize's database and user datastores.
    db.init_app(app)
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    Security(app, user_datastore)

    # Sets up administration page.
    admin = Admin(app,
                  'KaminariMerch Admin',
                  index_view=OrderView(Order, db.session, url='/admin'),
                  template_mode='bootstrap3')

    # Registers pages to the administration page.
    admin.add_link(MenuLink(name='Home', endpoint='store_page'))
    admin.add_view(
        ProductView(session=db.session,
                    name='Products',
                    endpoint='products',
                    model=Product))
    admin.add_view(
        UserView(session=db.session,
                 name='Users',
                 endpoint='users',
                 model=User))

    # Passes the login form to templates.
    @app.context_processor
    def login_context():
        return {
            'url_for_security': url_for_security,
            'login_user_form': LoginForm(),
        }

    @app.route('/')
    @app.route('/index')
    def store_page():
        """
        The main store page that includes all the active products for purchase.
        This is where users add items to their cart.
        """

        products = Product.query.all()

        if 'cart' not in session:
            session['cart'] = []

        for item in products:
            if not item.active:
                products.remove(item)

        return render_template('index.html',
                               products=products,
                               cart=session['cart'],
                               in_cart=in_cart)

    @app.route('/cart')
    def shopping_cart():
        """
        The user cart page, allows removal of items as well as finalizing
        an order before payment.
        """

        total = 0

        if 'cart' in session:
            products = Product.query.filter(Product.id.in_(
                session['cart'])).all()
            for product in products:
                total += product.price
        else:
            products = []

        return render_template('cart.html', cart=products, total=total)

    @app.route('/add_to_cart', methods=['POST'])
    @login_required
    def add_to_cart():
        """
        API endpoint that adds an item to the request session using
        a provided Product ID.
        """

        product = Product.query.get(request.form['id'])

        if not any(str(product.id) in d for d in session['cart']):
            add_product_to_cart(product)

        return jsonify({'success': True})

    @app.route('/remove_from_cart', methods=['POST'])
    @login_required
    def remove_from_cart():
        """
        API endpoint that removes an item from the request session using a
        provided Product ID.
        """

        product = Product.query.get(request.form['id'])

        if any(str(product.id) in d for d in session['cart']):
            remove_product_from_cart(product)

        return jsonify({'success': True})

    @app.route('/check_payment', methods=['POST'])
    @login_required
    def check_payment():
        """
        Manual payment checking API endpoint for orders.
        TODO: Authorization.
        """

        order = Order.query.get(request.form['id'])
        return jsonify({'paid': order.check_paid()})

    @app.route('/settings', methods=['GET', 'POST'])
    @login_required
    def user_settings():
        """
        User settings page where users manage their information as well as
        delete their account.
        """

        password_form = PasswordResetForm()
        delete_account_form = DeleteAccountForm()

        # Verifys that the password was correct and changes it to a new one.
        if password_form.submit_password.data and password_form.validate():
            if verify_password(password_form.old_password.data,
                               current_user.password):
                current_user.password = hash_password(
                    password_form.new_password.data)
                db.session.commit()
                return redirect(url_for('store_page'))

        # Verifies that the password was correct and then deletes the account.
        if delete_account_form.submit_delete_account.data and delete_account_form.validate(
        ):
            if verify_password(delete_account_form.password.data,
                               current_user.password):
                db.session.delete(current_user)
                db.session.commit()
                return redirect(url_for('store_page'))

        return render_template('user_settings.html',
                               password_form=password_form,
                               delete_account_form=delete_account_form)

    @app.route('/checkout')
    def checkout():
        """
        Here validate users checkouts before attempting to create an order. If the
        order was successful then we redirect the user to it.
        """

        products = Product.query.filter(Product.id.in_(session['cart'])).all()
        order = current_user.create_order(products)

        # Checks to make sure the order actually was created. It's possible for this
        # to fail in certain edge cases.
        if order:

            db.session.add(order)
            db.session.commit()

            session['cart'] = []

            return redirect(url_for('show_order', order_id=order.id))

        else:
            return 'Error: Could not create order. Please contact store administration.'

    @app.route('/order/<int:order_id>')
    @login_required
    def show_order(order_id):
        """
        Order page that takes an integer as the id. Checks to make sure the user is linked
        to the order before displaying it.
        """

        if any(order_id in i for i in current_user.get_order_ids()):

            order = Order.query.get(order_id)

            if not order.paid:
                order.check_paid()

            return render_template('order.html', order=order)

        else:
            return abort(404)

    @app.route('/confirm_payment', methods=['POST'])
    def payment_webhook():
        """
        This is a payment webhook that triggers when a payment is received.

        Because this webhook isn't authenticated, we don't trust the payment information on its own.
        We check the payment status ourselves before updating.
        """

        charge = request.get_json()
        charge_id = charge['data']['id']
        order = Order.query.filter_by(charge_id=charge_id).first()

        if order:
            order.check_paid()
            if order.paid:
                return jsonify({'success': True}), 200, {
                    'ContentType': 'application/json'
                }

        return jsonify({'success': False}), 400, {
            'ContentType': 'application/json'
        }

    @app.route('/example_products')
    @login_required
    def example():
        """
        Generates example products for quick evaluation of storefront functionality.
        """

        if current_user.has_role('admin'):
            generate_example_products()
            return redirect(url_for('store_page'))
        else:
            return abort(404)

    @app.before_first_request
    def before_first_request():

        # This is just an example setup for the database.
        # Obviously if we run in production this would be replaced
        # with something a little less archaic. It works for now though.

        # Create a cart in the session
        if 'cart' not in session:
            session['cart'] = []

        # Clean out the database if we have to
        db.drop_all()

        # Create any database tables that don't exist yet.
        db.create_all()

        # Create the Role "admin" -- unless it already exists
        user_datastore.find_or_create_role(name='admin',
                                           description='Administrator')

        # Create two Users for testing purposes -- unless they already exists.
        # In each case, use Flask-Security utility function to encrypt the password.
        user_datastore.create_user(email='*****@*****.**',
                                   password=hash_password('password'))
        user_datastore.create_user(email='*****@*****.**',
                                   password=hash_password('password'))

        # Commit any database changes; the User and Roles must exist before we can add a Role to the User
        db.session.commit()

        user_datastore.add_role_to_user('*****@*****.**', 'admin')
        db.session.commit()

    return app
예제 #10
0
		'https://www.google-analytics.com'
	}
}

# use Flask Talisman for some common HTTP header security options
# https://github.com/GoogleCloudPlatform/flask-talisman
talisman = Talisman(
	application,
	content_security_policy=csp,
	content_security_policy_nonce_in=['default-src']
)

# minify HTML responses + CSS/JS, if not in debug mode
# use flask_htmlmin to minify HTML responses
application.config['MINIFY_HTML'] = True
htmlmin = HTMLMIN(application)


@application.errorhandler(404)
def page_not_found(caught_error):
	"""Summary

	Args:
		e (TYPE): Caught exception

	Returns:
		TYPE: a 404 reponse + 404.html
	"""

	return render_template('index.html'), 404
예제 #11
0
login_manager.needs_refresh_message = 'Вам необходимо повторно войти на сайт, чтобы получить доступ к этой странице'

# A tool for monitoring and debugging application from the browser
toolbar = DebugToolbarExtension()

# Library that takes care of the appearance of time inside template
moment = Moment()

# Bootstrap package for simplifying the creation of the Front-end
bootstrap = Bootstrap()

# Sluger to prettify the texts inside url
base_slugify = Slugify(to_lower=True)

# Minifying HTML codes
htmlminify = HTMLMIN()

# Cross site request forgery protection to prevent any request coming to the site from others
csrf = CSRFProtect()

# The session manager
session = Session()

# Compressor for all types of data [xml, zip, js, css]
compress = Compress()

# Principal for organizing the authorization and the user information inside the app
principal = Principal()

# Two main roles for my users
admin_permission = Permission(RoleNeed('admin'))
예제 #12
0
from celery import Celery
from flask_sqlalchemy import SQLAlchemy
from flask_caching import Cache
from flask_migrate import Migrate
from flask_compress import Compress
from flask_assets import Environment
from flask_htmlmin import HTMLMIN
from flask_login import LoginManager

from raven import Client
from raven.contrib.flask import Sentry

from configs import Config

db = SQLAlchemy()
cache = Cache()
migrate = Migrate()
compress = Compress()
assets = Environment()
sentry = Sentry()
celery = Celery(
    'celery',
    backend=Config.CELERY_RESULT_BACKEND,
    broker=Config.CELERY_BROKER_URL,
)
html_min = HTMLMIN()
login_manager = LoginManager()
client = Client()
예제 #13
0
def create_app(configfile=None):
    app = Flask(__name__)
    app.config['MINIFY_HTML'] = True
    app.secret_key = secrets.token_urlsafe(16)

    Bootstrap(app)

    HTMLMIN(app)

    @app.route('/', methods=['GET', 'POST'])
    def main():
        if request.method == 'GET':
            return render_template('base.html', title='ipevctl')
        if request.method == 'POST':
            label = request.form.get('service')
            if request.form.get('do_deployment_restart'):
                target = request.form.get('do_deployment_restart')
                kube.main('restart', label, target)
            if request.form.get('do_deployment_start'):
                target = request.form.get('do_deployment_start')
                kube.main('start', label, target)
            if request.form.get('do_deployment_stop'):
                target = request.form.get('do_deployment_stop')
                kube.main('stop', label, target)
            data = kube.main('get', label)
            namespace = [x for x in data.keys()]
            return render_template('get.html', title='ipevctl', namespace=namespace, data=data, label=label)

    @app.route('/downloadfile/<name>', methods=['GET', 'POST'])
    def get_deployment(name):
        tmpdir = request.form['create_file']
        filename = str(name) + '.yml'
        return send_file(tmpdir + filename,
                         as_attachment=True,
                         attachment_filename=filename,
                         mimetype='text/x-yaml')

    @app.route('/view', methods=['GET', 'POST'])
    def get_template_info():
        output_configmap = {}
        req = request.form['get_pods'].split(' ')
        try:
            data = kube.main('get_pod_info', req[0], req[1], req[2])
            pods_info, deployment, configmap = dict(data[0]), data[1][0], data[2]
            if configmap != None:
                configmap = configmap.to_dict()
                output_configmap['name'] = configmap['metadata']['name']
                output_configmap['namespace'] = configmap['metadata']['namespace']
                for k, v in configmap['data'].items():
                    output_configmap['data_key'] = k
                    output_configmap['data_value'] = v
            else:
                output_configmap = None
            deployment_spec = yaml.dump(cleanNullTerms(deployment.spec.template.spec.to_dict()))
            return render_template('view.html', data=pods_info, deployment=deployment_spec,
                                   deployment_name=deployment.metadata.name, tmpdir=data[1][1], configmap=output_configmap)
        except Exception as ex:
            return render_template('view.html')

    @app.route('/view/update-configmap', methods=['GET', 'POST'])
    def do_update_configmap():
        req = request.form['update_configmap']
        data_value = yaml.dump(yaml.load(req))
        if str('configmap_cred') in request.form:
            cred = request.form['configmap_cred'].split(' ')
            namespace, configmap_name, data_key = cred[0], cred[1], cred[2]
            body = {data_key: data_value}
            kube.do_update_configmap(context=namespace, namespace=namespace, name=configmap_name, body_data=body)
        else:
            cred = request.form['pod_restart'].split(' ')
            namespace, configmap_name, data_key = cred[0], cred[1], cred[2]
            deployment_name = cred[3]
            body = {data_key: req}
            kube.do_update_configmap(namespace=namespace, name=configmap_name, body_data=body)
            kube.do_deployment_restart(context=namespace, deployment=deployment_name, namespace=namespace)
        return render_template('view.html')

    return app
예제 #14
0
def create_app(config_name):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')

    Compress(app)
    HTMLMIN(app)

    admin = run_admin()
    admin.init_app(app)

    db.init_app(app)
    migrate = Migrate(app, db)

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

    register_blueprints(app)

    login_manager.init_app(app)

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

    @app.route('/robots.txt')
    @app.route('/sitemap.xml')
    def serve_static_seo_files():
        return send_from_directory(app.static_folder, request.path[1:])

    @app.route('/generate-pdf', methods=['POST'])
    def generate_pdf():
        try:
            data = request.get_json()

            template = render_template('utils/pdf_template.html', content=data['content'])
            css = ['app/static/css/vendors/bootstrap.min.css',
                   'app/static/css/style.css',
                   'app/static/css/pdf-style.css'
                   ]
            try:
                pdf = base64.b64encode(pdfkit.from_string(template, False, css=css))
            except FileNotFoundError:
                pdf = base64.b64encode(pdfkit.from_string(template, False))

            response = make_response(pdf)
            response.headers['Content-Type'] = 'application/pdf'
            response.mimetype = 'application/pdf'
            return response, 200
        except Exception as e:
            abort(Response(str(e)), 400)

    @app.errorhandler(404)
    def page_not_found(e):
        print(e)
        return render_template("404.html", title="404 Page not found!")

    @app.context_processor
    def inject_now():
        return {
            'now': datetime.utcnow(),
            'module_desc': Page.query.filter_by(breadcrumbs=request.path).first(),
            'css_js_ver': 1.10
        }

    @app.after_request
    def add_header(response):
        response.cache_control.max_age = 31536000
        return response

    return app
예제 #15
0
_config.SQLALCHEMY_DATABASE_URI = f'mysql://{_config.DB_USER}:{_config.DB_PASS}@{_config.DB_HOST}:{_config.DB_PORT}/{_config.DB_NAME}'

if environ.get('FLASK_ENV') == 'development':
    _config.DEBUG = True
else:
    _config.DEBUG = False

app.config.from_object(_config)

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

searcher = Search(app)

# Configuracion de Login
login = LoginManager(app)
login.login_view = 'login_usuario'
login.login_message = 'Necesitas ingresar al sistema para ver esta pagina.'
login.login_message_category = 'warning'

admin = Admin(app, template_mode='bootstrap3')

minifier = HTMLMIN(app)

ID_ADMIN = 1
ID_USER = 2
ID_EDITOR = 3

ID_SENADOR = 1
ID_DIPUTADO = 2
예제 #16
0
    # strip out important newlines.
    return bundle, 200, {'Content-Type': 'text/plain; charset=utf-8'}


@freezer.register_generator
def index():
    for lang in FEDORA_LANGUAGES:
        #yield {'lang_code': lang}
        for name in freeze_indexes:
            yield (name + '_i18n'), {'lang_code': lang}


if __name__ == '__main__':
    # Minification is good for production, but not for debugging.
    app.config['MINIFY_PAGE'] = True
    htmlmin = HTMLMIN(app)

    freezer.freeze()

    print('Running sanity checks.')
    print("")
    print("Download links:")
    dl_all = [check_download_link(link) for link in dl_links]

    print("")
    print("Static files:")
    checksum_all = [check_checksum_link(link) for link in checksum_links]
    releases_json = check_releases_json()

    print("")
    print("GPG keys:")
예제 #17
0
def create_app(app_name=None):

    # Configuration settings
    import config
    if not app_name:
        app_name = config.APP_NAME
    """Create the Flask application, startup logging and dynamically load
    additional modules (blueprints) that are found in this directory."""
    app = PgAdmin(__name__, static_url_path='/static')
    # Removes unwanted whitespace from render_template function
    app.jinja_env.trim_blocks = True
    app.config.from_object(config)
    app.config.update(dict(PROPAGATE_EXCEPTIONS=True))

    ##########################################################################
    # Setup logging and log the application startup
    ##########################################################################

    # Add SQL level logging, and set the base logging level
    logging.addLevelName(25, 'SQL')
    app.logger.setLevel(logging.DEBUG)
    app.logger.handlers = []

    # We also need to update the handler on the webserver in order to see
    # request. Setting the level prevents werkzeug from setting up it's own
    # stream handler thus ensuring all the logging goes through the pgAdmin
    # logger.
    logger = logging.getLogger('werkzeug')
    logger.setLevel(logging.INFO)

    # File logging
    fh = logging.FileHandler(config.LOG_FILE, encoding='utf-8')
    fh.setLevel(config.FILE_LOG_LEVEL)
    fh.setFormatter(logging.Formatter(config.FILE_LOG_FORMAT))
    app.logger.addHandler(fh)
    logger.addHandler(fh)

    # Console logging
    ch = logging.StreamHandler()
    ch.setLevel(config.CONSOLE_LOG_LEVEL)
    ch.setFormatter(logging.Formatter(config.CONSOLE_LOG_FORMAT))
    app.logger.addHandler(ch)
    logger.addHandler(ch)

    # Log the startup
    app.logger.info('########################################################')
    app.logger.info('Starting %s v%s...', config.APP_NAME, config.APP_VERSION)
    app.logger.info('########################################################')
    app.logger.debug("Python syspath: %s", sys.path)

    from pgadmin.setup import create_app_data_directory, db_upgrade

    # Sanity checks (App data directory exists)
    create_app_data_directory(config)

    ##########################################################################
    # Setup i18n
    ##########################################################################

    # Initialise i18n
    babel = Babel(app)

    app.logger.debug('Available translations: %s' % babel.list_translations())

    @babel.localeselector
    def get_locale():
        """Get the language for the user."""
        language = 'en'
        if config.SERVER_MODE is False:
            # Get the user language preference from the miscellaneous module
            misc_preference = Preferences.module('miscellaneous', False)
            if misc_preference:
                user_languages = misc_preference.preference('user_language')
                if user_languages:
                    language = user_languages.get() or language
        else:
            # If language is available in get request then return the same
            # otherwise check the session or cookie
            data = request.form
            if 'language' in data:
                language = data['language'] or language
                setattr(session, 'PGADMIN_LANGUAGE', language)
            elif hasattr(session, 'PGADMIN_LANGUAGE'):
                language = getattr(session, 'PGADMIN_LANGUAGE', language)
            elif hasattr(request.cookies, 'PGADMIN_LANGUAGE'):
                language = getattr(request.cookies, 'PGADMIN_LANGUAGE',
                                   language)

        return language

    ##########################################################################
    # Setup authentication
    ##########################################################################

    app.config[
        'SQLALCHEMY_DATABASE_URI'] = u'sqlite:///{0}?timeout={1}'.format(
            config.SQLITE_PATH.replace(u'\\', u'/'),
            getattr(config, 'SQLITE_TIMEOUT', 500))

    # Only enable password related functionality in server mode.
    if config.SERVER_MODE is True:
        # TODO: Figure out how to disable /logout and /login
        app.config['SECURITY_RECOVERABLE'] = True
        app.config['SECURITY_CHANGEABLE'] = True

    # Create database connection object and mailer
    db.init_app(app)

    ##########################################################################
    # Upgrade the schema (if required)
    ##########################################################################
    db_upgrade(app)

    Mail(app)

    import pgadmin.utils.paths as paths
    paths.init_app(app)

    # Setup Flask-Security
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(None, user_datastore)

    ##########################################################################
    # Setup security
    ##########################################################################
    with app.app_context():
        config.CSRF_SESSION_KEY = Keys.query.filter_by(
            name='CSRF_SESSION_KEY').first().value
        config.SECRET_KEY = Keys.query.filter_by(
            name='SECRET_KEY').first().value
        config.SECURITY_PASSWORD_SALT = Keys.query.filter_by(
            name='SECURITY_PASSWORD_SALT').first().value

    # Update the app.config with proper security keyes for signing CSRF data,
    # signing cookies, and the SALT for hashing the passwords.
    app.config.update(dict(CSRF_SESSION_KEY=config.CSRF_SESSION_KEY))
    app.config.update(dict(SECRET_KEY=config.SECRET_KEY))
    app.config.update(
        dict(SECURITY_PASSWORD_SALT=config.SECURITY_PASSWORD_SALT))

    security.init_app(app)

    app.session_interface = create_session_interface(app)

    ##########################################################################
    # Load all available server drivers
    ##########################################################################
    driver.init_app(app)

    ##########################################################################
    # Register language to the preferences after login
    ##########################################################################
    @user_logged_in.connect_via(app)
    def register_language(sender, user):
        # After logged in, set the language in the preferences if we get from
        # the login page
        data = request.form
        if 'language' in data:
            language = data['language']

            # Set the user language preference
            misc_preference = Preferences.module('miscellaneous')
            user_languages = misc_preference.preference('user_language')

            if user_languages and language:
                language = user_languages.set(language)

    ##########################################################################
    # Register any local servers we can discover
    ##########################################################################
    @user_logged_in.connect_via(app)
    def on_user_logged_in(sender, user):

        # Keep hold of the user ID
        user_id = user.id

        # Get the first server group for the user
        servergroup_id = 1
        servergroups = ServerGroup.query.filter_by(
            user_id=user_id).order_by("id")

        if servergroups.count() > 0:
            servergroup = servergroups.first()
            servergroup_id = servergroup.id
        '''Add a server to the config database'''
        def add_server(user_id, servergroup_id, name, superuser, port,
                       discovery_id, comment):
            # Create a server object if needed, and store it.
            servers = Server.query.filter_by(
                user_id=user_id, discovery_id=svr_discovery_id).order_by("id")

            if servers.count() > 0:
                return

            svr = Server(user_id=user_id,
                         servergroup_id=servergroup_id,
                         name=name,
                         host='localhost',
                         port=port,
                         maintenance_db='postgres',
                         username=superuser,
                         ssl_mode='prefer',
                         comment=svr_comment,
                         discovery_id=discovery_id)

            db.session.add(svr)
            db.session.commit()

        # Figure out what servers are present
        if winreg is not None:
            arch_keys = set()
            proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()

            try:
                proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower()
            except:
                proc_arch64 = None

            if proc_arch == 'x86' and not proc_arch64:
                arch_keys.add(0)
            elif proc_arch == 'x86' or proc_arch == 'amd64':
                arch_keys.add(winreg.KEY_WOW64_32KEY)
                arch_keys.add(winreg.KEY_WOW64_64KEY)

            for arch_key in arch_keys:
                for server_type in ('PostgreSQL', 'EnterpriseDB'):
                    try:
                        root_key = winreg.OpenKey(
                            winreg.HKEY_LOCAL_MACHINE,
                            "SOFTWARE\\" + server_type + "\Services", 0,
                            winreg.KEY_READ | arch_key)
                        for i in xrange(0, winreg.QueryInfoKey(root_key)[0]):
                            inst_id = winreg.EnumKey(root_key, i)
                            inst_key = winreg.OpenKey(root_key, inst_id)

                            svr_name = winreg.QueryValueEx(
                                inst_key, 'Display Name')[0]
                            svr_superuser = winreg.QueryValueEx(
                                inst_key, 'Database Superuser')[0]
                            svr_port = winreg.QueryValueEx(inst_key, 'Port')[0]
                            svr_discovery_id = inst_id
                            svr_comment = gettext(
                                "Auto-detected %s installation with the data directory at %s"
                                % (winreg.QueryValueEx(inst_key,
                                                       'Display Name')[0],
                                   winreg.QueryValueEx(inst_key,
                                                       'Data Directory')[0]))

                            add_server(user_id, servergroup_id, svr_name,
                                       svr_superuser, svr_port,
                                       svr_discovery_id, svr_comment)

                            inst_key.Close()
                    except:
                        pass
        else:
            # We use the postgres-winreg.ini file on non-Windows
            try:
                from configparser import ConfigParser
            except ImportError:
                from ConfigParser import ConfigParser  # Python 2

            registry = ConfigParser()

        try:
            registry.read('/etc/postgres-reg.ini')
            sections = registry.sections()

            # Loop the sections, and get the data from any that are PG or PPAS
            for section in sections:
                if section.startswith('PostgreSQL/') or section.startswith(
                        'EnterpriseDB/'):
                    svr_name = registry.get(section, 'Description')
                    svr_superuser = registry.get(section, 'Superuser')
                    svr_port = registry.getint(section, 'Port')
                    svr_discovery_id = section
                    description = registry.get(section, 'Description')
                    data_directory = registry.get(section, 'DataDirectory')
                    if hasattr(str, 'decode'):
                        description = description.decode('utf-8')
                        data_directory = data_directory.decode('utf-8')
                    svr_comment = gettext(
                        u"Auto-detected %s installation with the data directory at %s"
                        % (description, data_directory))
                    add_server(user_id, servergroup_id, svr_name,
                               svr_superuser, svr_port, svr_discovery_id,
                               svr_comment)

        except:
            pass

    ##########################################################################
    # Load plugin modules
    ##########################################################################
    for module in app.find_submodules('pgadmin'):
        app.logger.info('Registering blueprint module: %s' % module)
        app.register_blueprint(module)

    ##########################################################################
    # Handle the desktop login
    ##########################################################################

    @app.before_request
    def before_request():
        """Login the default user if running in desktop mode"""

        # Check the auth key is valid, if it's set, and we're not in server
        # mode, and it's not a help file request.
        if not config.SERVER_MODE and app.PGADMIN_KEY != '':
            if ((not 'key' in request.args
                 or request.args['key'] != app.PGADMIN_KEY)
                    and request.cookies.get('PGADMIN_KEY') != app.PGADMIN_KEY
                    and request.endpoint != 'help.static'):
                abort(401)

        if not config.SERVER_MODE:
            user = user_datastore.get_user(config.DESKTOP_USER)

            # Throw an error if we failed to find the desktop user, to give
            # the sysadmin a hint. We'll continue to try to login anyway as
            # that'll through a nice 500 error for us.
            if user is None:
                app.logger.error(
                    'The desktop user %s was not found in the configuration database.'
                    % config.DESKTOP_USER)
                abort(401)

            login_user(user)

    @app.after_request
    def after_request(response):
        if 'key' in request.args:
            response.set_cookie('PGADMIN_KEY', value=request.args['key'])

        return response

    ##########################################################################
    # Minify output
    ##########################################################################
    # HTMLMIN doesn't work with Python 2.6.
    if not config.DEBUG and sys.version_info >= (2, 7):
        HTMLMIN(app)

    @app.context_processor
    def inject_blueprint():
        """Inject a reference to the current blueprint, if any."""
        return {
            'current_app': current_app,
            'current_blueprint': current_blueprint
        }

    ##########################################################################
    # All done!
    ##########################################################################
    app.logger.debug('URL map: %s' % app.url_map)

    return app
예제 #18
0
"""Точка входа в приложение"""
from webbrowser import open

from flask import Flask
from flask_htmlmin import HTMLMIN
from flask_marshmallow import Marshmallow
from flask_sqlalchemy import SQLAlchemy
#from flask_wtf.csrf import CSRFProtect

from assets import ASSETS

APP = Flask(__name__)
APP.config.from_object('config.ProductionConfig')
ASSETS.init_app(APP)

htmlmin = HTMLMIN(APP)
db = SQLAlchemy(APP)
ma = Marshmallow(APP)
#csrf = CSRFProtect(APP)

from server import *

if __name__ == '__main__':
    #open('http://localhost:5000')
    APP.run(host='127.0.0.1', port=80)