Completed
Push — master ( 2a5ab9...12cd9a )
by Jace
14s
created

_sanitize_url_query_params()   A

Complexity

Conditions 4

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
c 0
b 0
f 0
dl 0
loc 9
rs 9.2
ccs 7
cts 7
cp 1
crap 4
1 1
import pprint
2 1
import logging
3 1
from urllib.parse import unquote
4
5 1
import requests
6 1
from flask import (Response, url_for, render_template, send_file,
0 ignored issues
show
Configuration introduced by
The import flask could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
7
                   current_app, request)
8
9
10 1
log = logging.getLogger(__name__)
11
12
13 1
def route(*args, **kwargs):
14
    """Unquoted version of Flask's `url_for`."""
15 1
    return _secure(unquote(url_for(*args, **kwargs)))
16
17
18 1
def _secure(url):
19
    """Ensure HTTPS is used in production."""
20 1
    if current_app.config['ENV'] == 'prod':
21
        url = url.replace('http:', 'https:')
22 1
    return url
23
24
25 1
def display(title, path, share=False, raw=False, mimetype='image/jpeg'):
26
    """Render a webpage or raw image based on request."""
27 1
    mimetypes = request.headers.get('Accept', "").split(',')
28 1
    browser = 'text/html' in mimetypes
29 1
    src_url = _sanitize_url_query_params(request)
30
31 1
    if browser or share:
32 1
        log.info("Rending image on page: %s", src_url)
33
34 1
        html = render_template(
35
            'image.html',
36
            src=_secure(src_url),
37
            title=title,
38
            ga_tid=get_tid(),
39
        )
40 1
        return html if raw else _nocache(Response(html))
41
42
    else:
43 1
        log.info("Sending image: %s", path)
44 1
        return send_file(path, mimetype=mimetype)
45
46
47 1
def _sanitize_url_query_params(req):
48
    """Ensure query string does not affect image rendering."""
49 1
    query_values = dict(req.args)
50 1
    src_query_params = ["{}={}".format(k, v[0])
51
                        for k, v in query_values.items() if k != 'share']
52 1
    src_url = req.base_url
53 1
    if len(src_query_params):
54 1
        src_url += "?{}".format("&".join(src_query_params))
55 1
    return src_url
56
57
58 1
def _nocache(response):
59
    """Ensure a response is not cached."""
60
    response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
61
    response.headers['Pragma'] = 'no-cache'
62
    response.headers['Expires'] = '0'
63
    return response
64
65
66 1
def track(title):
67
    """Log the requested content, server-side."""
68 1
    data = dict(
69
        v=1,
70
        tid=get_tid(),
71
        cid=request.remote_addr,
72
73
        t='pageview',
74
        dh='memegen.link',
75
        dp=request.full_path,
76
        dt=str(title),
77
78
        uip=request.remote_addr,
79
        ua=request.user_agent.string,
80
    )
81 1
    if get_tid(default=None):
82
        requests.post("http://www.google-analytics.com/collect", data=data)
83
    else:
84 1
        log.debug("Analytics data:\n%s", pprint.pformat(data))
85
86
87 1
def get_tid(*, default='local'):
88
    """Get the analtyics tracking identifier."""
89
    return current_app.config['GOOGLE_ANALYTICS_TID'] or default
90