Python flask.current_app.root_path() Examples

The following are 16 code examples of flask.current_app.root_path(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.current_app , or try the search function .
Example #1
Source File: __init__.py    From Flask-Fixtures with MIT License 6 votes vote down vote up
def setup(obj):
    log.info('setting up fixtures...')

    # Push a request and/or app context onto the stack
    push_ctx(getattr(obj, 'app'))

    # Setup the database
    obj.db.create_all()
    # Rollback any lingering transactions
    obj.db.session.rollback()


    # Construct a list of paths within which fixtures may reside
    default_fixtures_dir = os.path.join(current_app.root_path, 'fixtures')

    # All relative paths should be relative to the app's root directory.
    fixtures_dirs = [default_fixtures_dir]
    for directory in current_app.config.get('FIXTURES_DIRS', []):
        if not os.path.isabs(directory):
            directory = os.path.abspath(os.path.join(current_app.root_path, directory))
        fixtures_dirs.append(directory)

    # Load all of the fixtures
    for filename in obj.fixtures:
        load_fixtures_from_file(obj.db, filename, fixtures_dirs) 
Example #2
Source File: __init__.py    From FF.PyAdmin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_conf_json(path, file):
    """
    通用: 获取 JSON 配置文件

    :param path: 相对于 conf, e.g. bgp
    :param file: 文件名, 不带扩展名, e.g. as-name
    :return: dict,e.g. {'123': '成都'}
    """
    ret = {}
    file = os.path.join(current_app.root_path, 'conf', path, file + '.json')

    try:
        with open(file, 'r', encoding='utf-8') as f:
            ret = json.load(f)
    except Exception as e:
        current_app.logger.error('{0!r} {1}'.format(e, file))

    return ret 
Example #3
Source File: ics_generator.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def calendar_dir() -> str:
    """获得日历文件路径。生产环境为/var/calendar_files/,否则为程序根目录下的calendar_files文件夹。"""
    if get_env() == "PRODUCTION":
        return "/var/calendar_files/"
    return (current_app.root_path or "") + "/../../calendar_files/" 
Example #4
Source File: start.py    From beibq with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _exist_config(app):
    filename = "{}/config.py".format(app.root_path)
    return os.path.exists(filename) 
Example #5
Source File: start.py    From beibq with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_config(username, password, host, db):
    data = render_template("admin/start/config.html", username=username,
        password=password, host=host, db = db)
    filename = '{}/config.py'.format(current_app.root_path)
    fd = open(filename, "w")
    fd.write(data)
    fd.close() 
Example #6
Source File: start.py    From beibq with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_path(app):
    paths, config = [], app.config
    log_path, _ = os.path.split(config["ERROR_LOG"])
    paths.append(os.path.join(app.root_path, log_path))

    paths.append(os.path.join(app.static_folder, config["AVATAR_PATH"]))
    paths.append(os.path.join(app.static_folder, config["TMP_PATH"]))
    paths.append(os.path.join(app.static_folder, config["IMAGE_PATH"]))
    paths.append(os.path.join(app.static_folder, config["BOOK_COVER_PATH"]))
    for path in paths:
        if not os.path.exists(path):
            os.makedirs(path) 
Example #7
Source File: flask_gopher.py    From flask-gopher with GNU General Public License v3.0 5 votes vote down vote up
def load_file(self, filename):
        """
        Load the filename from the local directory. The type of the returned
        object depends on if the filename corresponds to a file or a directory.
        If it's a file, a flask Response object containing the file's data will
        be returned. If it's a directory, a gopher menu will be returned.

        This method uses the flask application context, which means that it
        can only be invoked from inside of a flask view.
        """
        abs_filename = safe_join(self.local_directory, filename)
        if not os.path.isabs(abs_filename):
            abs_filename = os.path.join(current_app.root_path, abs_filename)

        if os.path.isfile(abs_filename):
            return self.result_class(False, send_file(abs_filename))
        elif os.path.isdir(abs_filename):
            data = self._parse_directory(filename, abs_filename)
            return self.result_class(True, data)
        else:
            raise BadRequest() 
Example #8
Source File: index.py    From PowerDNS-Admin with MIT License 5 votes vote down vote up
def swagger_spec():
    try:
        spec_path = os.path.join(current_app.root_path, "swagger-spec.yaml")
        spec = open(spec_path, 'r')
        loaded_spec = load(spec.read(), Loader)
    except Exception as e:
        current_app.logger.error(
            'Cannot view swagger spec. Error: {0}'.format(e))
        current_app.logger.debug(traceback.format_exc())
        abort(500)

    resp = make_response(json.dumps(loaded_spec), 200)
    resp.headers['Content-Type'] = 'application/json'

    return resp 
Example #9
Source File: LFI-2.py    From skf-labs with GNU Affero General Public License v3.0 5 votes vote down vote up
def home():
    filename = request.form['filename']
    filename=filename.replace('../','')
    if os.path.isfile(current_app.root_path + '/'+ filename):
        with current_app.open_resource(filename) as f:
            read = f.read()
    else: 
        read='try harder'
    return render_template("index.html",read = read) 
Example #10
Source File: LFI-3.py    From skf-labs with GNU Affero General Public License v3.0 5 votes vote down vote up
def home():
    filename = urllib.parse.unquote(request.form['filename'])
    read='try harder...'
    if '../' not in filename:
        filename = urllib.parse.unquote(filename)
        if os.path.isfile(current_app.root_path + '/'+ filename):
            with current_app.open_resource(filename) as f:
                read = f.read()
    return render_template("index.html",read = read) 
Example #11
Source File: __init__.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def plugin(plugin):
    if request.method == "GET":
        plugins_path = os.path.join(app.root_path, "plugins")

        config_html_plugins = [
            name
            for name in os.listdir(plugins_path)
            if os.path.isfile(os.path.join(plugins_path, name, "config.html"))
        ]

        if plugin in config_html_plugins:
            config_html = open(
                os.path.join(app.root_path, "plugins", plugin, "config.html")
            ).read()
            return render_template_string(config_html)
        abort(404)
    elif request.method == "POST":
        for k, v in request.form.items():
            if k == "nonce":
                continue
            set_config(k, v)
        with app.app_context():
            clear_config()
        return "1" 
Example #12
Source File: views.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def themes(theme, path):
    """
    General static file handler
    :param theme:
    :param path:
    :return:
    """
    filename = safe_join(app.root_path, "themes", theme, "static", path)
    if os.path.isfile(filename):
        return send_file(filename)
    else:
        abort(404) 
Example #13
Source File: __init__.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def stamp_latest_revision():
    # Get proper migrations directory regardless of cwd
    directory = os.path.join(os.path.dirname(app.root_path), "migrations")
    stamp(directory=directory) 
Example #14
Source File: __init__.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def get_themes():
    dir = os.path.join(app.root_path, "themes")
    return [
        name
        for name in os.listdir(dir)
        if os.path.isdir(os.path.join(dir, name)) and name != "admin"
    ] 
Example #15
Source File: __init__.py    From flask-bower with GNU General Public License v2.0 4 votes vote down vote up
def build_url(component, filename, **values):
    """
    search bower asset and build url

    :param component: bower component (package)
    :type component: str
    :param filename: filename in bower component - can contain directories (like dist/jquery.js)
    :type filename: str
    :param values: additional url parameters
    :type values: dict[str, str]
    :return: url
    :rtype: str | None
    """
    root = current_app.config['BOWER_COMPONENTS_ROOT']
    bower_data = None
    package_data = None

    # check if component exists in bower_components directory
    if not os.path.isdir(os.path.join(current_app.root_path, root, component)):
        # FallBack to default url_for flask
        return None

    # load bower.json of specified component
    bower_file_path = os.path.join(current_app.root_path, root, component, 'bower.json')
    if os.path.exists(bower_file_path):
        with open(bower_file_path, 'r') as bower_file:
            bower_data = json.load(bower_file)

    # check if package.json exists and load package.json data
    package_file_path = os.path.join(current_app.root_path, root, component, 'package.json')
    if os.path.exists(package_file_path):
        with open(package_file_path, 'r') as package_file:
            package_data = json.load(package_file)

    # check if specified file actually exists
    if not os.path.exists(os.path.join(current_app.root_path, root, component, filename)):
        return None

    # check if minified file exists (by pattern <filename>.min.<ext>
    # returns filename if successful
    if current_app.config['BOWER_TRY_MINIFIED']:
        if '.min.' not in filename:
            minified_filename = '%s.min.%s' % tuple(filename.rsplit('.', 1))
            minified_path = os.path.join(root, component, minified_filename)

            if os.path.exists(os.path.join(current_app.root_path, minified_path)):
                filename = minified_filename

    # determine version of component and append as ?version= parameter to allow cache busting
    if current_app.config['BOWER_QUERYSTRING_REVVING']:
        if bower_data is not None and 'version' in bower_data:
            values['version'] = bower_data['version']
        elif package_data is not None and 'version' in package_data:
            values['version'] = package_data['version']
        else:
            values['version'] = os.path.getmtime(os.path.join(current_app.root_path, root, component, filename))

    return url_for('bower.serve', component=component, filename=filename, **values) 
Example #16
Source File: __init__.py    From CTFd with Apache License 2.0 4 votes vote down vote up
def export_ctf():
    # TODO: For some unknown reason dataset is only able to see alembic_version during tests.
    # Even using a real sqlite database. This makes this test impossible to pass in sqlite.
    db = dataset.connect(get_app_config("SQLALCHEMY_DATABASE_URI"))

    # Backup database
    backup = tempfile.NamedTemporaryFile()

    backup_zip = zipfile.ZipFile(backup, "w")

    tables = db.tables
    for table in tables:
        result = db[table].all()
        result_file = BytesIO()
        freeze_export(result, fileobj=result_file)
        result_file.seek(0)
        backup_zip.writestr("db/{}.json".format(table), result_file.read())

    # # Guarantee that alembic_version is saved into the export
    if "alembic_version" not in tables:
        result = {
            "count": 1,
            "results": [{"version_num": get_current_revision()}],
            "meta": {},
        }
        result_file = BytesIO()
        json.dump(result, result_file)
        result_file.seek(0)
        backup_zip.writestr("db/alembic_version.json", result_file.read())

    # Backup uploads
    uploader = get_uploader()
    uploader.sync()

    upload_folder = os.path.join(
        os.path.normpath(app.root_path), app.config.get("UPLOAD_FOLDER")
    )
    for root, dirs, files in os.walk(upload_folder):
        for file in files:
            parent_dir = os.path.basename(root)
            backup_zip.write(
                os.path.join(root, file),
                arcname=os.path.join("uploads", parent_dir, file),
            )

    backup_zip.close()
    backup.seek(0)
    return backup