Python flask.request.endpoint() Examples

The following are 30 code examples of flask.request.endpoint(). 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.request , or try the search function .
Example #1
Source File: __init__.py    From Flask-HTMLmin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def response_minify(self, response):
        """
        minify response html to decrease traffic
        """

        if response.content_type == u'text/html; charset=utf-8':
            endpoint = request.endpoint or ''
            view_func = current_app.view_functions.get(endpoint, None)
            name = (
                '%s.%s' % (view_func.__module__, view_func.__name__)
                if view_func else ''
            )
            if name in self._exempt_routes:
                return response

            response.direct_passthrough = False
            response.set_data(
                self._html_minify.minify(response.get_data(as_text=True))
            )

            return response
        return response 
Example #2
Source File: middleware.py    From python-monitoring-talk with Apache License 2.0 6 votes vote down vote up
def stop_timer(response):
    # convert this into milliseconds for statsd
    resp_time = (time.time() - request.start_time)*1000
    key = REQUEST_LATENCY_METRIC_KEY_PATTERN.format(
        request.endpoint,
        request.method,
        response.status_code,
    )
    statsd.timing(key, resp_time)

    key = REQUEST_COUNT_METRIC_KEY_PATTERN.format(
        request.endpoint,
        request.method,
        response.status_code,
    )
    statsd.incr(key)
    return response 
Example #3
Source File: rest_connector.py    From thingsboard-gateway with Apache License 2.0 6 votes vote down vote up
def load_handlers(self):
        data_handlers = {
            "basic": BasicDataHandler,
            "anonymous": AnonymousDataHandler,
        }
        for mapping in self.__config.get("mapping"):
            try:
                security_type = "anonymous" if mapping.get("security") is None else mapping["security"]["type"].lower()
                if security_type != "anonymous":
                    Users.add_user(mapping['endpoint'],
                                   mapping['security']['username'],
                                   mapping['security']['password'])
                self._api.add_resource(data_handlers[security_type],
                                       mapping['endpoint'],
                                       endpoint=mapping['endpoint'],
                                       resource_class_args=(self.collect_statistic_and_send,
                                                            self.get_name(),
                                                            self.endpoints[mapping["endpoint"]]))
            except Exception as e:
                log.error("Error on creating handlers - %s", str(e)) 
Example #4
Source File: matches.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, person: str = None, format_name: str = None) -> None:
        query = match.Match.query
        if person is not None:
            query = query.filter(match.Match.players.any(db.User.name == person))
        if format_name is not None:
            fmt = db.get_format(format_name)
            if fmt is not None:
                query = query.filter(match.Match.format_id == fmt.id)
        recent = query.order_by(match.Match.id.desc()).paginate()

        self.matches = recent.items
        self.has_next = recent.has_next
        self.has_prev = recent.has_prev
        self.has_pagination = self.has_next or self.has_prev
        endpoint = request.endpoint
        if endpoint is None:
            return
        if recent.has_next:
            self.next_url = url_for(endpoint, person=person, format_name=format_name, page=recent.next_num)
        if recent.has_prev:
            self.prev_url = url_for(endpoint, person=person, format_name=format_name, page=recent.prev_num) 
Example #5
Source File: __init__.py    From beibq with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_start(app, db):
    from app.includes.start import _exist_config, exist_table, create_path, set_site
    create_path(app)
    app.start = False
    if _exist_config(app):
        from app.config import Config
        app.config.from_object(Config)
        if exist_table(app):
            app.start = True
            return
    @app.before_request
    def request_check_start():
        if app.start:
            return set_site(app)
        ends = frozenset(["admin.setup", "admin.install", "static"])
        if request.endpoint in ends:
            return
        if not _exist_config(app):
            return redirect(url_for("admin.setup"))
        return redirect(url_for("admin.install")) 
Example #6
Source File: webapp.py    From yeti with Apache License 2.0 6 votes vote down vote up
def list_routes():
    import urllib
    output = []
    for rule in webapp.url_map.iter_rules():

        options = {}
        for arg in rule.arguments:
            options[arg] = "[{0}]".format(arg)

        methods = ','.join(rule.methods)
        url = url_for(rule.endpoint, **options)
        line = urllib.unquote(
            "{:50s} {:20s} {}".format(rule.endpoint, methods, url))
        output.append(line)

    for line in sorted(output):
        print(line)

    return "<br>".join(output) 
Example #7
Source File: templates.py    From flask-unchained with MIT License 6 votes vote down vote up
def is_active(endpoint_or_kwargs: Union[str, dict]):
    endpoint = None
    href = None
    if isinstance(endpoint_or_kwargs, str):
        if '/' in endpoint_or_kwargs:
            href = endpoint_or_kwargs
        else:
            endpoint = endpoint_or_kwargs
    elif isinstance(endpoint_or_kwargs, dict):
        endpoint = endpoint_or_kwargs.get('endpoint')
        href = endpoint_or_kwargs.get('href')
    else:
        raise TypeError('the first argument to is_active must be a str or dict')

    if endpoint:
        return endpoint == request.endpoint

    return href in {request.path, request.url} 
Example #8
Source File: job_utils.py    From FATE with Apache License 2.0 6 votes vote down vote up
def job_server_routing(routing_type=0):
    def _out_wrapper(func):
        @functools.wraps(func)
        def _wrapper(*args, **kwargs):
            job_server = set()
            jobs = query_job(job_id=request.json.get('job_id', None))
            for job in jobs:
                if job.f_run_ip:
                    job_server.add(job.f_run_ip)
            if len(job_server) == 1:
                execute_host = job_server.pop()
                if execute_host != RuntimeConfig.JOB_SERVER_HOST:
                    if routing_type == 0:
                        return api_utils.request_execute_server(request=request, execute_host=execute_host)
                    else:
                        return redirect('http://{}{}'.format(execute_host, url_for(request.endpoint)), code=307)
            return func(*args, **kwargs)
        return _wrapper
    return _out_wrapper 
Example #9
Source File: __init__.py    From flask-oidc with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def logout(self):
        """
        Request the browser to please forget the cookie we set, to clear the
        current session.

        Note that as described in [1], this will not log out in the case of a
        browser that doesn't clear cookies when requested to, and the user
        could be automatically logged in when they hit any authenticated
        endpoint.

        [1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023

        .. versionadded:: 1.0
        """
        # TODO: Add single logout
        self._set_cookie_id_token(None)

    # Below here is for resource servers to validate tokens 
Example #10
Source File: server.py    From prometheus_flask_exporter with MIT License 6 votes vote down vote up
def create_app():
    app = Flask(__name__)
    metrics.init_app(app)

    with app.app_context():
        setup_api(app)

        metrics.register_default(
            metrics.counter(
                'by_path_counter', 'Request count by request paths',
                labels={'path': lambda: request.path}
            )
        )

    metrics.register_default(
        metrics.counter(
            'outside_context',
            'Example default registration outside the app context',
            labels={'endpoint': lambda: request.endpoint}
        ),
        app=app
    )

    return app 
Example #11
Source File: __init__.py    From prometheus_flask_exporter with MIT License 6 votes vote down vote up
def start_http_server(self, port, host='0.0.0.0', endpoint='/metrics'):
        """
        Start an HTTP server for exposing the metrics.
        This will be an individual Flask application,
        not the one registered with this class.

        :param port: the HTTP port to expose the metrics endpoint on
        :param host: the HTTP host to listen on (default: `0.0.0.0`)
        :param endpoint: the URL path to expose the endpoint on
            (default: `/metrics`)
        """

        if is_running_from_reloader():
            return

        app = Flask('prometheus-flask-exporter-%d' % port)
        self.register_endpoint(endpoint, app)

        def run_app():
            app.run(host=host, port=port)

        thread = threading.Thread(target=run_app)
        thread.setDaemon(True)
        thread.start() 
Example #12
Source File: ratelimit.py    From TurtleFaucet with GNU General Public License v3.0 6 votes vote down vote up
def ratelimit(limit, per=300, send_x_headers=True,
              over_limit=on_over_limit,
              fp_func=lambda: request.form.get('fingerprint'),
              ip_func=lambda: request.environ['REMOTE_ADDR'],
              key_func=lambda: request.endpoint):
    def decorator(f):
        def rate_limited(*args, **kwargs):
            ip_key = 'ip-limit/%s/%s/' % (key_func(), ip_func())
            fp_key = 'fp-limit/%s/%s/' % (key_func(), fp_func())
            rlimit = RateLimit(ip_key, fp_key, limit, per, send_x_headers)
            g._view_rate_limit = rlimit

            # check if IP has been used LIMIT times
            if rlimit.over_ip_limit:
                return over_limit(rlimit)

            # IP is good, check fingerprint now
            if not rlimit.over_ip_limit:
                if rlimit.over_fp_limit:
                    return over_limit(rlimit)

            return f(*args, **kwargs)
        return update_wrapper(rate_limited, f)
    return decorator 
Example #13
Source File: etag.py    From flask-smorest with MIT License 6 votes vote down vote up
def _verify_check_etag(self):
        """Verify check_etag was called in resource code

        Log a warning if ETag is enabled but check_etag was not called in
        resource code in a PUT, PATCH or DELETE method.

        Raise CheckEtagNotCalledError when in debug or testing mode.

        This is called automatically. It is meant to warn the developer about
        an issue in his ETag management.
        """
        if request.method in self.METHODS_NEEDING_CHECK_ETAG:
            if not _get_etag_ctx().get('etag_checked'):
                message = (
                    'ETag not checked in endpoint {} on {} request.'
                    .format(request.endpoint, request.method))
                app = current_app
                app.logger.warning(message)
                if app.debug or app.testing:
                    raise CheckEtagNotCalledError(message) 
Example #14
Source File: pagination.py    From cookiecutter-flask-restful with MIT License 6 votes vote down vote up
def paginate(query, schema):
    page = request.args.get("page", DEFAULT_PAGE_NUMBER)
    per_page = request.args.get("page_size", DEFAULT_PAGE_SIZE)
    page_obj = query.paginate(page=page, per_page=per_page)
    next_ = url_for(
        request.endpoint,
        page=page_obj.next_num if page_obj.has_next else page_obj.page,
        per_page=per_page,
        **request.view_args
    )
    prev = url_for(
        request.endpoint,
        page=page_obj.prev_num if page_obj.has_prev else page_obj.page,
        per_page=per_page,
        **request.view_args
    )

    return {
        "total": page_obj.total,
        "pages": page_obj.pages,
        "next": next_,
        "prev": prev,
        "results": schema.dump(page_obj.items),
    } 
Example #15
Source File: routes.py    From VectorCloud with GNU General Public License v3.0 6 votes vote down vote up
def check_valid_login():
    user = db.session.query(User).first()

    if any([request.endpoint.startswith('static'),
            current_user.is_authenticated,
            getattr(app.view_functions[request.endpoint],
                    'is_public', False)]):
        return

    elif user is None:
        return redirect(url_for('user_system.register'))

    else:
        return redirect(url_for('user_system.login'))


# this was a fix to make sure images stored in the cache are deleted when
# a new image is uploaded 
Example #16
Source File: web.py    From SwarmOps with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_redirect_url(endpoint="front.index"):
    """获取重定向地址
    NextUrl: 引导重定向下一步地址
    ReturnUrl: 最终重定向地址
    以上两个不存在时,如果定义了非默认endpoint,则首先返回;否则返回referrer地址,不存在时返回endpoint默认主页
    """
    url = request.args.get('NextUrl') or request.args.get('ReturnUrl')
    if not url:
        if endpoint != "front.index":
            url = url_for(endpoint)
        else:
            url = get_referrer_url() or url_for(endpoint)
    return url 
Example #17
Source File: __init__.py    From notifications-api with MIT License 5 votes vote down vote up
def init_app(app):

    @app.before_request
    def record_request_details():
        CONCURRENT_REQUESTS.inc()

        g.start = monotonic()
        g.endpoint = request.endpoint

    @app.after_request
    def after_request(response):
        CONCURRENT_REQUESTS.dec()

        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
        response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
        return response

    @app.errorhandler(Exception)
    def exception(error):
        app.logger.exception(error)
        # error.code is set for our exception types.
        msg = getattr(error, 'message', str(error))
        code = getattr(error, 'code', 500)
        return jsonify(result='error', message=msg), code

    @app.errorhandler(WerkzeugHTTPException)
    def werkzeug_exception(e):
        return make_response(
            jsonify(result='error', message=e.description),
            e.code,
            e.get_headers()
        )

    @app.errorhandler(404)
    def page_not_found(e):
        msg = e.description or "Not found"
        return jsonify(result='error', message=msg), 404 
Example #18
Source File: middleware.py    From python-monitoring-talk with Apache License 2.0 5 votes vote down vote up
def stop_timer(response):
    # convert this into milliseconds for statsd
    resp_time = (time.time() - request.start_time)*1000
    node_id = node_ids[random.choice(range(len(node_ids)))]
    with open('metrics.csv', 'a', newline='') as f:
        csvwriter = csv.writer(f)
        csvwriter.writerow([
            str(int(time.time())), 'webapp1', node_id,
            request.endpoint, request.method, str(response.status_code),
            str(resp_time)
        ])

    return response 
Example #19
Source File: __init__.py    From prometheus_flask_exporter with MIT License 5 votes vote down vote up
def register_default(self, *metric_wrappers, **kwargs):
        """
        Registers metric wrappers to track all endpoints,
        similar to `export_defaults` but with user defined metrics.
        Call this function after all routes have been set up.

        Use the metric wrappers as arguments:
          - metrics.counter(..)
          - metrics.gauge(..)
          - metrics.summary(..)
          - metrics.histogram(..)

        :param metric_wrappers: one or more metric wrappers to register
            for all available endpoints
        :param app: the Flask application to register the default metric for
            (by default it is the application registered with this class)
        """

        app = kwargs.get('app')
        if app is None:
            app = self.app or current_app

        for endpoint, view_func in app.view_functions.items():
            for wrapper in metric_wrappers:
                view_func = wrapper(view_func)
                app.view_functions[endpoint] = view_func 
Example #20
Source File: fields.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def output(self, key, obj, **kwargs):
        return url_for(self.endpoint, _external=True, **self.mapper(obj)) 
Example #21
Source File: fields.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, endpoint, mapper=None, **kwargs):
        super(UrlFor, self).__init__(**kwargs)
        self.endpoint = endpoint
        self.mapper = mapper or self.default_mapper 
Example #22
Source File: helpers.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def i18n_alternate_links():
    """Render the <link rel="alternate" hreflang />

    if page is in a I18nBlueprint
    """
    if (not request.endpoint or
            not current_app.url_map.is_endpoint_expecting(request.endpoint,
                                                          'lang_code')):
        return Markup('')

    try:
        LINK_PATTERN = (
            '<link rel="alternate" href="{url}" hreflang="{lang}" />')
        links = []
        current_lang = get_current_locale().language

        params = {}
        if request.args:
            params.update(request.args)
        if request.view_args:
            params.update(request.view_args)

        for lang in current_app.config['LANGUAGES']:
            if lang != current_lang:
                url = url_for(request.endpoint, lang_code=lang, **params)
                links.append(LINK_PATTERN.format(url=url, lang=lang))
        return Markup(''.join(links))
    except Exception:
        # Never fails
        return Markup('') 
Example #23
Source File: filters.py    From openmoves with MIT License 5 votes vote down vote up
def url_for_sortable(sort, sort_order):
    args = request.view_args.copy()
    args.update(request.args)
    args['sort'] = sort
    args['sort_order'] = sort_order
    return url_for(request.endpoint, **args) 
Example #24
Source File: web.py    From IncetOps with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_redirect_url(endpoint="front.index"):
    """获取重定向地址
    NextUrl: 引导重定向下一步地址
    ReturnUrl: 最终重定向地址
    以上两个不存在时,如果定义了非默认endpoint,则首先返回;否则返回referrer地址,不存在时返回endpoint默认主页
    """
    url = request.args.get('NextUrl') or request.args.get('ReturnUrl')
    if not url:
        if endpoint != "front.index":
            url = url_for(endpoint)
        else:
            url = get_referrer_url() or url_for(endpoint)
    return url 
Example #25
Source File: web.py    From IncetOps with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_referrer_url():
    """获取上一页地址"""
    if request.referrer and request.referrer.startswith(request.host_url) and request.endpoint and not "api." in request.endpoint:
        url = request.referrer
    else:
        url = None
    return url 
Example #26
Source File: web_ui.py    From SearchingReddit with MIT License 5 votes vote down vote up
def url_for_other_page(page):
    args = request.view_args.copy()
    args['page'] = page
    return url_for(request.endpoint, **args) 
Example #27
Source File: authorisation.py    From appkernel with Apache License 2.0 5 votes vote down vote up
def __get_required_permissions(clazz):
    pms = clazz.protected_methods.get(request.method)
    if request.endpoint in pms:
        perms = list(pms.get(request.endpoint))
    else:
        perms = list(pms.get('*'))

    if perms:
        if isinstance(perms, iam.Permission):
            perms = [perms]
        elif not isinstance(perms, list):
            raise AttributeError
    return perms 
Example #28
Source File: run.py    From helix-sandbox with GNU Affero General Public License v3.0 5 votes vote down vote up
def before_request():
  admin_created = User.query.filter_by(is_admin=True).first()
  if not admin_created and request.endpoint != 'auth.admin_setup' and request.endpoint != 'static':
    return redirect(url_for('auth.admin_setup')) 
Example #29
Source File: web.py    From SwarmOps with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_referrer_url():
    """获取上一页地址"""
    if request.referrer and request.referrer.startswith(request.host_url) and request.endpoint and not "api." in request.endpoint:
        url = request.referrer
    else:
        url = None
    return url 
Example #30
Source File: fields.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def output(self, key, obj, **kwargs):
        if not getattr(obj, 'has_prev', None):
            return None
        args = multi_to_dict(request.args)
        args.update(request.view_args)
        args['page'] = obj.page - 1
        return url_for(request.endpoint, _external=True, **args)