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 Project: MPContribs   Author: materialsproject   File: views.py    License: MIT License 17 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 Project: comport   Author: codeforamerica   File: test_interest_form.py    License: 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 #3
Source Project: py-flask-jsontools   Author: kolypto   File: response.py    License: 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 #4
Source Project: circleci-demo-python-flask   Author: CircleCI-Public   File: users.py    License: 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 #5
Source Project: circleci-demo-python-flask   Author: CircleCI-Public   File: users.py    License: 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 #6
Source Project: circleci-demo-python-flask   Author: CircleCI-Public   File: comments.py    License: 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 #7
Source Project: circleci-demo-python-flask   Author: CircleCI-Public   File: comments.py    License: 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 #8
Source Project: circleci-demo-python-flask   Author: CircleCI-Public   File: posts.py    License: 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 #9
Source Project: maple-file   Author: honmaple   File: router.py    License: 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 #10
Source Project: Simpleblog   Author: Blackyukun   File: users.py    License: 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 #11
Source Project: Simpleblog   Author: Blackyukun   File: users.py    License: 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 #12
Source Project: Simpleblog   Author: Blackyukun   File: comments.py    License: 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 #13
Source Project: Simpleblog   Author: Blackyukun   File: posts.py    License: 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 #14
Source Project: asu   Author: aparcar   File: api.py    License: 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 #15
Source Project: ara-archive   Author: dmsimard   File: result.py    License: 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 #16
Source Project: ara-archive   Author: dmsimard   File: host.py    License: 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 #17
Source Project: ara-archive   Author: dmsimard   File: file.py    License: 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 #18
Source Project: ara-archive   Author: dmsimard   File: webapp.py    License: 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 #19
Source Project: ara-archive   Author: dmsimard   File: webapp.py    License: 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 Project: api-pycon2014   Author: miguelgrinberg   File: rate_limit.py    License: 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 Project: api-pycon2014   Author: miguelgrinberg   File: decorators.py    License: MIT License 6 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 #22
Source Project: everyclass-server   Author: everyclass   File: mongodb.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def init_pool(current_application) -> None:
    """创建连接池,保存在 app 的 mongo 属性中"""
    current_application.mongo = MongoClient(**current_application.config['MONGODB']) 
Example #23
Source Project: everyclass-server   Author: everyclass   File: mongodb.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def get_connection() -> database.Database:
    """在连接池中获得连接"""
    if not has_app_context():
        config = get_config()
        return MongoClient(**config.MONGODB).get_database(config.MONGODB_DB)
    return current_app.mongo.get_database(current_app.config['MONGODB_DB']) 
Example #24
Source Project: MPContribs   Author: materialsproject   File: views.py    License: MIT License 5 votes vote down vote up
def applications(token, action):
    ts = current_app.config["USTS"]
    max_age = current_app.config["USTS_MAX_AGE"]
    try:
        owner, project = ts.loads(token, max_age=max_age)
    except SignatureExpired:
        return f"signature for {owner} of {project} expired."

    try:
        obj = Projects.objects.get(project=project, owner=owner, is_approved=False)
    except DoesNotExist:
        return f"{project} for {owner} already approved or denied."

    actions = ["approve", "deny"]
    if action not in actions:
        response = f"<h3>{project}</h3><ul>"
        scheme = "http" if current_app.config["DEBUG"] else "https"
        for a in actions:
            u = url_for(
                "projects.applications",
                token=token,
                action=a,
                _scheme=scheme,
                _external=True,
            )
            response += f'<li><a href="{u}">{a}</a></li>'
        return response + "</ul>"

    if action == "approve":
        obj.is_approved = True
        obj.save()  # post_save (created=False) sends notification when `is_approved` set
    else:
        obj.delete()  # post_delete signal sends notification

    return f'{project} {action.replace("y", "ie")}d and {owner} notified.' 
Example #25
Source Project: MPContribs   Author: materialsproject   File: document.py    License: MIT License 5 votes vote down vote up
def post_delete(cls, sender, document, **kwargs):
        admin_email = current_app.config["MAIL_DEFAULT_SENDER"]
        admin_topic = current_app.config["MAIL_TOPIC"]
        subject = f'Your project "{document.project}" has been deleted'
        html = render_template(
            "owner_email.html", approved=False, admin_email=admin_email
        )
        topic_arn = ":".join(
            admin_topic.split(":")[:-1] + ["mpcontribs_" + document.project]
        )
        send_email(topic_arn, subject, html)
        sns_client.delete_topic(TopicArn=topic_arn) 
Example #26
Source Project: MPContribs   Author: materialsproject   File: document.py    License: MIT License 5 votes vote down vote up
def pre_save_post_validation(cls, sender, document, **kwargs):
        document.data = validate_data(
            document.data, sender=sender, project=document.project
        )
        if hasattr(document, "formula"):
            formulae = current_app.config["FORMULAE"]
            document.formula = formulae.get(document.identifier, document.identifier)

        document.last_modified = datetime.utcnow() 
Example #27
Source Project: comport   Author: codeforamerica   File: test_extractor_api.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_extractor_post_triggers_slack_notification(self, testapp):
        ''' A valid heartbeat post triggers a Slack notification
        '''
        # set up the extractor
        department = Department.create(name="IM Police Department", short_name="IMPD", load_defaults=False)
        extractor, _ = Extractor.from_department_and_password(department=department, password="password")

        # set the correct authorization
        testapp.authorization = ('Basic', (extractor.username, 'password'))

        # 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 a sample json object to the heartbeat URL
        testapp.post_json("/data/heartbeat", params={"heartbeat": "heartbeat"})

        # test the captured post payload
        post_body = json.loads(responses.calls[0].request.body)
        assert 'Comport Pinged by Extractor!' in post_body['text']

        # delete the fake Slack webhook URL
        del(current_app.config['SLACK_WEBHOOK_URL'])
        # reset the mock
        responses.reset() 
Example #28
Source Project: flask-spark-docker   Author: mjhea0   File: views.py    License: MIT License 5 votes vote down vote up
def push_rq_connection():
    push_connection(redis.from_url(current_app.config['REDIS_URL'])) 
Example #29
Source Project: thewarden   Author: pxsocs   File: models.py    License: MIT License 5 votes vote down vote up
def get_reset_token(self, expires_sec=300):
        s = Serializer(current_app.config["SECRET_KEY"], expires_sec)
        return s.dumps({"user_id": self.id}).decode("utf-8") 
Example #30
Source Project: thewarden   Author: pxsocs   File: models.py    License: MIT License 5 votes vote down vote up
def verify_reset_token(token):
        s = Serializer(current_app.config["SECRET_KEY"])
        try:
            user_id = s.loads(token)["user_id"]
        except (KeyError, TypeError):
            return None
        return User.query.get(user_id)