Python flask.current_app.config() Examples

The following are 30 code examples of flask.current_app.config(). 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: views.py    From MPContribs with MIT License 29 votes vote down vote up
def get_browser():
    if "browser" not in g:
        options = webdriver.ChromeOptions()
        options.add_argument("no-sandbox")
        options.add_argument("--disable-gpu")
        options.add_argument("--window-size=800,600")
        options.add_argument("--disable-dev-shm-usage")
        options.set_headless()
        host = "chrome" if current_app.config["DEBUG"] else "127.0.0.1"
        g.browser = webdriver.Remote(
            command_executor=f"http://{host}:4444/wd/hub",
            desired_capabilities=DesiredCapabilities.CHROME,
            options=options,
        )
    return g.browser 
Example #2
Source File: decorators.py    From api-pycon2014 with MIT License 7 votes vote down vote up
def rate_limit(limit, per, scope_func=lambda: request.remote_addr):
    def decorator(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            if current_app.config['USE_RATE_LIMITS']:
                key = 'rate-limit/%s/%s/' % (f.__name__, scope_func())
                limiter = RateLimit(key, limit, per)
                if not limiter.over_limit:
                    rv = f(*args, **kwargs)
                else:
                    rv = too_many_requests('You have exceeded your request rate')
                #rv = make_response(rv)
                g.headers = {
                    'X-RateLimit-Remaining': str(limiter.remaining),
                    'X-RateLimit-Limit': str(limiter.limit),
                    'X-RateLimit-Reset': str(limiter.reset)
                }
                return rv
            else:
                return f(*args, **kwargs)
        return wrapped
    return decorator 
Example #3
Source File: file.py    From ara-archive with GNU General Public License v3.0 6 votes vote down vote up
def index():
    """
    This is not served anywhere in the web application.
    It is used explicitly in the context of generating static files since
    flask-frozen requires url_for's to crawl content.
    url_for's are not used with file.show_file directly and are instead
    dynamically generated through javascript for performance purposes.
    """
    if current_app.config['ARA_PLAYBOOK_OVERRIDE'] is not None:
        override = current_app.config['ARA_PLAYBOOK_OVERRIDE']
        files = (models.File.query
                 .filter(models.File.playbook_id.in_(override)))
    else:
        files = models.File.query.all()

    return render_template('file_index.html', files=files) 
Example #4
Source File: users.py    From circleci-demo-python-flask with MIT License 6 votes vote down vote up
def get_user_followed_posts(id):
    user = User.query.get_or_404(id)
    page = request.args.get('page', 1, type=int)
    pagination = user.followed_posts.order_by(Post.timestamp.desc()).paginate(
        page, per_page=current_app.config['CIRCULATE_POSTS_PER_PAGE'],
        error_out=False)
    posts = pagination.items
    prev = None
    if pagination.has_prev:
        prev = url_for('api.get_user_followed_posts', page=page-1,
                       _external=True)
    next = None
    if pagination.has_next:
        next = url_for('api.get_user_followed_posts', page=page+1,
                       _external=True)
    return jsonify({
        'posts': [post.to_json() for post in posts],
        'prev': prev,
        'next': next,
        'count': pagination.total
    }) 
Example #5
Source File: test_interest_form.py    From comport with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_interest_form_post_triggers_slack_notification(self, testapp):
        ''' A valid interest form post triggers a Slack notification.
        '''

        # set a fake Slack webhook URL
        fake_webhook_url = 'http://webhook.example.com/'
        current_app.config['SLACK_WEBHOOK_URL'] = fake_webhook_url

        # create a mock to receive POST requests to that URL
        responses.add(responses.POST, fake_webhook_url, status=200)

        # post an interest form submission
        testapp.post("/interest/", params=dict(name="Jean Weaver", agency="Clinton Police Department", location="Clinton, OK", phone="580-970-3338", email="jean.weaver@example.com", comments="I'm interested in Comport as an open-source tool!"))

        # test the captured post payload
        post_body = json.loads(responses.calls[0].request.body)
        assert 'New Interest Form Submission!' in post_body['text']

        # delete the fake Slack webhook URL
        del(current_app.config['SLACK_WEBHOOK_URL'])
        # reset the mock
        responses.reset() 
Example #6
Source File: response.py    From py-flask-jsontools with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, response, status=None, headers=None, **kwargs):
        """ Init a JSON response
        :param response: Response data
        :type response: *
        :param status: Status code
        :type status: int|None
        :param headers: Additional headers
        :type headers: dict|None
        """
        # Store response
        self._response_data = self.preprocess_response_data(response)

        # PrettyPrint?
        try:
            indent = 2 if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr else None
        except RuntimeError:  # "RuntimeError: working outside of application context"
            indent = None

        # Init super
        super(JsonResponse, self).__init__(
            json.dumps(self._response_data, indent=indent),
            headers=headers, status=status, mimetype='application/json',
            direct_passthrough=True, **kwargs) 
Example #7
Source File: posts.py    From Simpleblog with MIT License 6 votes vote down vote up
def get_posts():
    # posts = Post.query.all()
    # return jsonify({'posts': [post.to_json() for post in posts]})
    page = request.args.get('page', 1, type=int)
    pagination = Post.query.paginate(
        page, per_page=current_app.config['POSTS_PER_PAGE'],
        error_out=False
    )
    posts = pagination.items
    prev = None
    if pagination.has_prev:
        prev = url_for('api.get_posts', page=page-1, _external=True)
    next = None
    if pagination.has_next:
        next = url_for('api.get_posts', page=page+1, _external=True)
    return jsonify({
        'posts': [post.to_json() for post in posts],
        'prev': prev,
        'next': next,
        'count': pagination.total
    }) 
Example #8
Source File: comments.py    From Simpleblog with MIT License 6 votes vote down vote up
def get_post_comments(id):
    post = Post.query.get_or_404(id)
    page = request.args.get('page', 1, type=int)
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page, per_page=current_app.config['COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    prev = None
    if pagination.has_prev:
        prev = url_for('api.get_post_comments', id=id, page=page-1,
                       _external=True)
    next = None
    if pagination.has_next:
        next = url_for('api.get_post_comments', id=id, page=page+1,
                       _external=True)
    return jsonify({
        'comments': [comment.to_json() for comment in comments],
        'prev': prev,
        'next': next,
        'count': pagination.total
    }) 
Example #9
Source File: users.py    From circleci-demo-python-flask with MIT License 6 votes vote down vote up
def get_user_posts(id):
    user = User.query.get_or_404(id)
    page = request.args.get('page', 1, type=int)
    pagination = user.posts.order_by(Post.timestamp.desc()).paginate(
        page, per_page=current_app.config['CIRCULATE_POSTS_PER_PAGE'],
        error_out=False)
    posts = pagination.items
    prev = None
    if pagination.has_prev:
        prev = url_for('api.get_user_posts', page=page-1, _external=True)
    next = None
    if pagination.has_next:
        next = url_for('api.get_user_posts', page=page+1, _external=True)
    return jsonify({
        'posts': [post.to_json() for post in posts],
        'prev': prev,
        'next': next,
        'count': pagination.total
    }) 
Example #10
Source File: api.py    From asu with GNU General Public License v2.0 6 votes vote down vote up
def get_versions() -> dict:
    """Return available versions

    The configuration stores a dict of versions containing additional
    information like public signing key and upstream path.

    Returns:
        dict: latest available version per branch
    """
    if "versions" not in g:
        g.versions = dict(
            map(
                lambda b: (b["name"], b),
                filter(
                    lambda b: b.get("enabled"),
                    current_app.config["VERSIONS"]["branches"],
                ),
            )
        )
        current_app.logger.info(f"Loaded {len(g.versions)} versions")
    return g.versions 
Example #11
Source File: comments.py    From circleci-demo-python-flask with MIT License 6 votes vote down vote up
def get_post_comments(id):
    post = Post.query.get_or_404(id)
    page = request.args.get('page', 1, type=int)
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page, per_page=current_app.config['CIRCULATE_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    prev = None
    if pagination.has_prev:
        prev = url_for('api.get_post_comments', page=page-1, _external=True)
    next = None
    if pagination.has_next:
        next = url_for('api.get_post_comments', page=page+1, _external=True)
    return jsonify({
        'comments': [comment.to_json() for comment in comments],
        'prev': prev,
        'next': next,
        'count': pagination.total
    }) 
Example #12
Source File: posts.py    From circleci-demo-python-flask with MIT License 6 votes vote down vote up
def get_posts():
    page = request.args.get('page', 1, type=int)
    pagination = Post.query.paginate(
        page, per_page=current_app.config['CIRCULATE_POSTS_PER_PAGE'],
        error_out=False)
    posts = pagination.items
    prev = None
    if pagination.has_prev:
        prev = url_for('api.get_posts', page=page-1, _external=True)
    next = None
    if pagination.has_next:
        next = url_for('api.get_posts', page=page+1, _external=True)
    return jsonify({
        'posts': [post.to_json() for post in posts],
        'prev': prev,
        'next': next,
        'count': pagination.total
    }) 
Example #13
Source File: users.py    From Simpleblog with MIT License 6 votes vote down vote up
def get_user_posts(id):
    user = User.query.get_or_404(id)
    page = request.args.get('page', 1, type=int)
    pagination = user.posts.order_by(Post.timestamp.desc()).paginate(
        page, per_page=current_app.config['POSTS_PER_PAGE'],
        error_out=False)
    posts = pagination.items
    prev = None
    if pagination.has_prev:
        prev = url_for('api.get_user_posts', page=page-1, _external=True)
    next = None
    if pagination.has_next:
        next = url_for('api.get_user_posts', page=page+1, _external=True)
    return jsonify({
        'posts': [post.to_json() for post in posts],
        'prev': prev,
        'next': next,
        'count': pagination.total
    }) 
Example #14
Source File: comments.py    From circleci-demo-python-flask with MIT License 6 votes vote down vote up
def get_comments():
    page = request.args.get('page', 1, type=int)
    pagination = Comment.query.order_by(Comment.timestamp.desc()).paginate(
        page, per_page=current_app.config['CIRCULATE_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    prev = None
    if pagination.has_prev:
        prev = url_for('api.get_comments', page=page-1, _external=True)
    next = None
    if pagination.has_next:
        next = url_for('api.get_comments', page=page+1, _external=True)
    return jsonify({
        'comments': [comment.to_json() for comment in comments],
        'prev': prev,
        'next': next,
        'count': pagination.total
    }) 
Example #15
Source File: router.py    From maple-file with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def delete(self, pk):
        '''
        删除图片
        '''
        user = request.user
        image = Image.query.filter_by(id=pk, user=user).get_or_404('图片不存在')
        serializer = ImageSerializer(image)
        img_path = os.path.join(current_app.config['UPLOAD_FOLDER_ROOT'],
                                image.url)
        # 删除原图
        if os.path.exists(img_path):
            os.remove(img_path)
        # 删除缩略图
        thumb_path = os.path.join(current_app.config['UPLOAD_FOLDER_ROOT'],
                                  image.url.replace('photo', 'thumb'))
        if os.path.exists(thumb_path):
            os.remove(thumb_path)
        image.delete()
        return HTTP.OK(data=serializer.data) 
Example #16
Source File: webapp.py    From ara-archive with GNU General Public License v3.0 6 votes vote down vote up
def create_app(config=None, app_name=None):
    if app_name is None:
        app_name = DEFAULT_APP_NAME

    if current_app:
        return current_app

    app = Flask(app_name)

    configure_app(app, config)
    configure_dirs(app)
    configure_logging(app)
    configure_errorhandlers(app)
    configure_template_filters(app)
    configure_context_processors(app)
    configure_blueprints(app)
    configure_static_route(app)
    configure_db(app)

    return app 
Example #17
Source File: host.py    From ara-archive with GNU General Public License v3.0 6 votes vote down vote up
def index():
    """
    This is not served anywhere in the web application.
    It is used explicitly in the context of generating static files since
    flask-frozen requires url_for's to crawl content.
    url_for's are not used with host.show_host directly and are instead
    dynamically generated through javascript for performance purposes.
    """
    if current_app.config['ARA_PLAYBOOK_OVERRIDE'] is not None:
        override = current_app.config['ARA_PLAYBOOK_OVERRIDE']
        hosts = (models.Host.query
                 .filter(models.Host.playbook_id.in_(override)))
    else:
        hosts = models.Host.query.all()

    return render_template('host_index.html', hosts=hosts) 
Example #18
Source File: result.py    From ara-archive with GNU General Public License v3.0 6 votes vote down vote up
def index():
    """
    This is not served anywhere in the web application.
    It is used explicitly in the context of generating static files since
    flask-frozen requires url_for's to crawl content.
    url_for's are not used with result.show_result directly and are instead
    dynamically generated through javascript for performance purposes.
    """
    if current_app.config['ARA_PLAYBOOK_OVERRIDE'] is not None:
        override = current_app.config['ARA_PLAYBOOK_OVERRIDE']
        results = (models.TaskResult.query
                   .join(models.Task)
                   .filter(models.Task.playbook_id.in_(override)))
    else:
        results = models.TaskResult.query.all()

    return render_template('task_result_index.html', results=results) 
Example #19
Source File: webapp.py    From ara-archive with GNU General Public License v3.0 6 votes vote down vote up
def configure_static_route(app):
    # Note (dmsimard)
    # /static/ is provided from in-tree bundled files and libraries.
    # /static/packaged/ is routed to serve packaged (i.e, XStatic) libraries.
    #
    # The reason why this isn't defined as a proper view by itself is due to
    # a limitation in flask-frozen. Blueprint'd views methods are like so:
    # "<view>.<method>. The URL generator of flask-frozen is a method decorator
    # that expects the method name as the function and, obviously, you can't
    # really have dots in functions.
    # By having the route configured at the root of the application, there's no
    # dots and we can decorate "serve_static_packaged" instead of, say,
    # "static.serve_packaged".

    @app.route('/static/packaged/<module>/<path:filename>')
    def serve_static_packaged(module, filename):
        xstatic = current_app.config['XSTATIC']

        if module in xstatic:
            return send_from_directory(xstatic[module], filename)
        else:
            abort(404) 
Example #20
Source File: rate_limit.py    From api-pycon2014 with MIT License 6 votes vote down vote up
def __init__(self, key_prefix, limit, per):
        global redis
        if redis is None and current_app.config['USE_RATE_LIMITS']:
            if current_app.config['TESTING']:
                redis = FakeRedis()
            else:
                redis = Redis()

        self.reset = (int(time.time()) // per) * per + per
        self.key = key_prefix + str(self.reset)
        self.limit = limit
        self.per = per
        p = redis.pipeline()
        p.incr(self.key)
        p.expireat(self.key, self.reset + self.expiration_window)
        self.current = min(p.execute()[0], limit) 
Example #21
Source File: users.py    From Simpleblog with MIT License 6 votes vote down vote up
def get_user_followed_posts(id):
    user = User.query.get_or_404(id)
    page = request.args.get('page', 1, type=int)
    pagination = user.followed_posts.order_by(Post.timestamp.desc()).paginate(
        page, per_page=current_app.config['POSTS_PER_PAGE'],
        error_out=False)
    posts = pagination.items
    prev = None
    if pagination.has_prev:
        prev = url_for('api.get_user_followed_posts', page=page-1,
                       _external=True)
    next = None
    if pagination.has_next:
        next = url_for('api.get_user_followed_posts', page=page+1,
                       _external=True)
    return jsonify({
        'posts': [post.to_json() for post in posts],
        'prev': prev,
        'next': next,
        'count': pagination.total
    }) 
Example #22
Source File: api.py    From asu with GNU General Public License v2.0 5 votes vote down vote up
def get_redis():
    """Return Redis connectio

    Returns:
        Redis: Configured used Redis connection
    """
    if "redis" not in g:
        g.redis = current_app.config["REDIS_CONN"]
    return g.redis 
Example #23
Source File: janitor.py    From asu with GNU General Public License v2.0 5 votes vote down vote up
def get_packages_arch_repo(version, arch, repo):
    return parse_packages_file(
        current_app.config["UPSTREAM_URL"]
        + "/"
        + version["path"]
        + f"/packages/{arch}/{repo}/Packages.manifest",
        repo,
    ) 
Example #24
Source File: api.py    From asu with GNU General Public License v2.0 5 votes vote down vote up
def api_versions():
    """API call to get available versions

    Returns:
        dict: Available versions in JSON format
    """
    return current_app.config["VERSIONS"] 
Example #25
Source File: janitor.py    From asu with GNU General Public License v2.0 5 votes vote down vote up
def get_redis():
    return current_app.config["REDIS_CONN"] 
Example #26
Source File: janitor.py    From asu with GNU General Public License v2.0 5 votes vote down vote up
def update_target_packages(version: dict, target: str):
    current_app.logger.info(f"Updating packages of {version['name']}")
    r = get_redis()

    packages = get_packages_target_base(version, target)

    if not "base-files" in packages:
        current_app.logger.warning(f"{target}: missing base-files package")
        return

    arch = packages["base-files"]["architecture"]

    for repo in ["base", "packages", "luci", "routing", "telephony"]:
        packages.update(get_packages_arch_repo(version, arch, repo))

    output_path = current_app.config["JSON_PATH"] / version["path"] / target
    output_path.mkdir(exist_ok=True, parents=True)

    (output_path / "manifest.json").write_text(
        json.dumps(packages, sort_keys=True, separators=(",", ":"))
    )

    package_index = list(packages.keys())

    (output_path / "index.json").write_text(
        json.dumps(package_index, sort_keys=True, separators=(",", ":"))
    )

    current_app.logger.info(f"{target}: found {len(package_index)} packages")
    r.sadd(f"packages-{version['name']}-{target}", *package_index) 
Example #27
Source File: webapp.py    From ara-archive with GNU General Public License v3.0 5 votes vote down vote up
def configure_db(app):
    """
    0.10 is the first version of ARA that ships with a stable database schema.
    We can identify a database that originates from before this by checking if
    there is an alembic revision available.
    If there is no alembic revision available, assume we are running the first
    revision which contains the latest state of the database prior to this.
    """
    db.init_app(app)
    log = logging.getLogger(app.logger_name)

    if app.config.get('ARA_AUTOCREATE_DATABASE'):
        with app.app_context():
            migrations = app.config['DB_MIGRATIONS']
            flask_migrate.Migrate(app, db, directory=migrations)
            config = app.extensions['migrate'].migrate.get_config(migrations)

            # Verify if the database tables have been created at all
            inspector = Inspector.from_engine(db.engine)
            if len(inspector.get_table_names()) == 0:
                log.info('Initializing new DB from scratch')
                flask_migrate.upgrade(directory=migrations)

            # Get current alembic head revision
            script = ScriptDirectory.from_config(config)
            head = script.get_current_head()

            # Get current revision, if available
            connection = db.engine.connect()
            context = MigrationContext.configure(connection)
            current = context.get_current_revision()

            if not current:
                log.info('Unstable DB schema, stamping original revision')
                flask_migrate.stamp(directory=migrations,
                                    revision='da9459a1f71c')

            if head != current:
                log.info('DB schema out of date, upgrading')
                flask_migrate.upgrade(directory=migrations) 
Example #28
Source File: janitor.py    From asu with GNU General Public License v2.0 5 votes vote down vote up
def update_version(version):
    r = get_redis()

    profiles = {"profiles": {}}

    targets = list(
        filter(
            lambda p: not p.startswith("scheduled_for_removal"), get_targets(version)
        )
    )
    current_app.logger.info(f"Found {len(targets)} targets")

    r.sadd(f"targets-{version['name']}", *targets)

    for target in targets:
        update_target_packages(version, target)
        metadata, profiles_target = update_target_profiles(version, target)
        profiles.update(metadata)
        profiles["profiles"].update(profiles_target)

        profiles.pop("target", None)

    profiles_path = current_app.config["JSON_PATH"] / version["path"] / "profiles.json"
    profiles_path.parent.mkdir(exist_ok=True, parents=True)

    profiles_path.write_text(
        json.dumps(profiles, sort_keys=True, separators=(",", ":"))
    ) 
Example #29
Source File: janitor.py    From asu with GNU General Public License v2.0 5 votes vote down vote up
def get_packages_target_base(version, target):
    return parse_packages_file(
        current_app.config["UPSTREAM_URL"]
        + "/"
        + version["path"]
        + f"/targets/{target}/packages/Packages.manifest",
        target,
    ) 
Example #30
Source File: janitor.py    From asu with GNU General Public License v2.0 5 votes vote down vote up
def update_target_profiles(version: dict, target: str):
    """Update available profiles of a specific version

    Args:
        version (dict): Containing all version information as defined in VERSIONS
    """
    current_app.logger.info(f"Updating profiles of {version['name']}")
    r = get_redis()
    req = requests.get(
        current_app.config["JSON_URL"]
        + "/"
        + version["path"]
        + f"/{target}/profiles.json"
    )

    if req.status_code != 200:
        current_app.logger.warning(f"Could not download profiles.json for {target}")
        return {}, {}

    metadata = req.json()
    profiles = metadata.pop("profiles", {})

    current_app.logger.info(f"Found {len(profiles)} profiles")

    for profile, data in profiles.items():
        for supported in data.get("supported_devices", []):
            r.hset(f"mapping-{version['name']}", supported, profile)
        r.hset(f"profiles-{version['name']}", profile, target)

        data["target"] = target

    return metadata, profiles