Python flask.g.request_start_time() Examples

The following are 6 code examples of flask.g.request_start_time(). 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.g , or try the search function .
Example #1
Source File: app.py    From DeepOcrService with MIT License 5 votes vote down vote up
def before_request():
    g.request_start_time = time.time() 
Example #2
Source File: app.py    From DeepOcrService with MIT License 5 votes vote down vote up
def after_request(r):
    r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    r.headers["Pragma"] = "no-cache"
    r.headers["Expires"] = "0"
    r.headers['Cache-Control'] = 'public, max-age=0'
    print("request time: {:.03f}s".format(time.time() - g.request_start_time))
    return r 
Example #3
Source File: __init__.py    From bearded-avenger with Mozilla Public License 2.0 5 votes vote down vote up
def decompress():
    g.request_start_time = time.time()
    g.request_time = lambda: "%.5fs" % (time.time() - g.request_start_time)
    g.sid = str(uuid.uuid4())

    if '/u/' in request.path:
        return

    if request.headers.get('Content-Encoding') and request.headers['Content-Encoding'] == 'deflate':
        logger.debug('decompressing request: %d' % len(request.data))
        request.data = zlib.decompress(request.data)
        logger.debug('content-length: %d' % len(request.data)) 
Example #4
Source File: views.py    From oadoi with MIT License 4 votes vote down vote up
def stuff_before_request():
    if request.endpoint in ["get_doi_endpoint_v2", "get_doi_endpoint"]:
        email = request.args.get("email", None)
        if not email or email.endswith(u"example.com"):
            abort_json(422, "Email address required in API call, see http://unpaywall.org/products/api")

    if get_ip() in ["35.200.160.130", "45.249.247.101", "137.120.7.33",
                    "52.56.108.147", "193.137.134.252", "130.225.74.231"]:
        abort_json(429, "History of API use exceeding rate limits, please email support@unpaywall.org for other data access options, including free full database dump.")

    g.request_start_time = time()
    g.hybrid = 'hybrid' in request.args.keys()
    if g.hybrid:
        logger.info(u"GOT HYBRID PARAM so will run with hybrid.")

    # don't redirect http api in some cases
    if request.url.startswith("http://api."):
        return
    if "staging" in request.url or "localhost" in request.url:
        return

    # redirect everything else to https.
    new_url = None
    try:
        if request.headers["X-Forwarded-Proto"] == "https":
            pass
        elif "http://" in request.url:
            new_url = request.url.replace("http://", "https://")
    except KeyError:
        # logger.info(u"There's no X-Forwarded-Proto header; assuming localhost, serving http.")
        pass

    # redirect to naked domain from www
    if request.url.startswith("https://www.oadoi.org"):
        new_url = request.url.replace(
            "https://www.oadoi.org",
            "https://oadoi.org"
        )
        logger.info(u"URL starts with www; redirecting to " + new_url)

    if new_url:
        return redirect(new_url, 301)  # permanent



# convenience function because we do this in multiple places 
Example #5
Source File: __init__.py    From lemur with Apache License 2.0 4 votes vote down vote up
def configure_hook(app):
    """

    :param app:
    :return:
    """
    from flask import jsonify
    from werkzeug.exceptions import HTTPException

    @app.errorhandler(Exception)
    def handle_error(e):
        code = 500
        if isinstance(e, HTTPException):
            code = e.code

        app.logger.exception(e)
        return jsonify(error=str(e)), code

    @app.before_request
    def before_request():
        g.request_start_time = time.time()

    @app.after_request
    def after_request(response):
        # Return early if we don't have the start time
        if not hasattr(g, "request_start_time"):
            return response

        # Get elapsed time in milliseconds
        elapsed = time.time() - g.request_start_time
        elapsed = int(round(1000 * elapsed))

        # Collect request/response tags
        tags = {
            "endpoint": request.endpoint,
            "request_method": request.method.lower(),
            "status_code": response.status_code,
        }

        # Record our response time metric
        metrics.send("response_time", "TIMER", elapsed, metric_tags=tags)
        metrics.send("status_code_{}".format(response.status_code), "counter", 1)
        return response 
Example #6
Source File: __init__.py    From diffy with Apache License 2.0 4 votes vote down vote up
def configure_hook(app):
    """

    :param app:
    :return:
    """
    from flask import jsonify
    from werkzeug.exceptions import HTTPException

    @app.errorhandler(Exception)
    def handle_error(e):
        code = 500
        if isinstance(e, HTTPException):
            code = e.code

        app.logger.exception(e)
        return jsonify(error=str(e)), code

    @app.before_request
    def before_request():
        g.request_start_time = time.time()

    @app.after_request
    def after_request(response):
        # Return early if we don't have the start time
        if not hasattr(g, "request_start_time"):
            return response

        # Get elapsed time in milliseconds
        elapsed = time.time() - g.request_start_time
        elapsed = int(round(1000 * elapsed))

        # Collect request/response tags
        # tags = {
        #    'endpoint': request.endpoint,
        #    'request_method': request.method.lower(),
        #    'status_code': response.status_code
        # }

        # Record our response time metric
        app.logger.debug(
            f"Request Info: Elapsed: {elapsed} Status Code: {response.status_code} Endpoint: {request.endpoint} Method: {request.method}"
        )
        return response