Completed
Push — master ( 6cf9b5...d42209 )
by Jace
05:28
created

_format_url()   A

Complexity

Conditions 4

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
c 1
b 0
f 0
dl 0
loc 13
ccs 8
cts 8
cp 1
crap 4
rs 9.2
1 1
import logging
2 1
from urllib.parse import unquote
3
4 1
import requests
5 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...
6
                   current_app, request)
7
8
9 1
log = logging.getLogger(__name__)
10
11
12 1
def route(*args, **kwargs):
13
    """Unquoted version of Flask's `url_for`."""
14 1
    return _secure(unquote(url_for(*args, **kwargs)))
15
16
17 1
def display(title, path, share=False, raw=False, mimetype='image/jpeg'):
18
    """Render a webpage or raw image based on request."""
19 1
    mimetypes = request.headers.get('Accept', "").split(',')
20 1
    browser = 'text/html' in mimetypes
21
22 1
    img = _format_url(request, 'share')
23 1
    img_twitter = _format_url(
24
        request, 'share',
25
        width=current_app.config['TWITTER_IMAGE_WIDTH'],
26
        height=current_app.config['TWITTER_IMAGE_HEIGHT'],
27
    )
28 1
    img_facebook = _format_url(
29
        request, 'share',
30
        width=current_app.config['FACEBOOK_IMAGE_WIDTH'],
31
        height=current_app.config['FACEBOOK_IMAGE_HEIGHT'],
32
    )
33 1
    url = _format_url(request, 'width', 'height')
34
35 1
    if share:
36 1
        log.info("Sharing image on page: %s", img)
37
38 1
        html = render_template(
39
            'share.html',
40
            title=title,
41
            img=_secure(img),
42
            img_twitter=_secure(img_twitter),
43
            img_facebook=_secure(img_facebook),
44
            url=_secure(url),
45
            config=current_app.config,
46
        )
47 1
        return html if raw else _nocache(Response(html))
48
49 1
    elif browser:
50 1
        log.info("Embedding image on page: %s", img)
51
52 1
        html = render_template(
53
            'image.html',
54
            title=title,
55
            img=_secure(img),
56
            config=current_app.config,
57
        )
58 1
        return html if raw else _nocache(Response(html))
59
60
    else:
61 1
        log.info("Sending image: %s", path)
62 1
        return send_file(path, mimetype=mimetype)
63
64
65 1
def track(title):
66
    """Log the requested content, server-side."""
67 1
    google_url = current_app.config['GOOGLE_ANALYTICS_URL']
68 1
    google_tid = current_app.config['GOOGLE_ANALYTICS_TID']
69 1
    google_data = dict(
70
        v=1,
71
        tid=google_tid,
72
        cid=request.remote_addr,
73
74
        t='pageview',
75
        dh='memegen.link',
76
        dp=request.full_path,
77
        dt=str(title),
78
79
        uip=request.remote_addr,
80
        ua=request.user_agent.string,
81
    )
82 1
    if google_tid != 'localhost':
83
        response = requests.post(google_url, data=google_data)
84
        params = _format_query(google_data, as_string=True)
85
        log.debug("Tracking POST: %s %s", response.url, params)
86
87 1
    remote_url = current_app.config['REMOTE_TRACKING_URL']
88 1
    remote_data = dict(
89
        text=str(title),
90
        source='memegen.link',
91
        context=unquote(request.url),
92
    )
93 1
    if remote_url:
94
        response = requests.get(remote_url, params=remote_data)
95
        log.debug("Tracking GET: %s", response.url)
96
97
98 1
def _secure(url):
99
    """Ensure HTTPS is used in production."""
100 1
    if current_app.config['ENV'] == 'prod':
101 1
        if url.startswith('http:'):
102 1
            url = url.replace('http:', 'https:', 1)
103 1
    return url
104
105
106 1
def _format_url(req, *skip, **add):
107
    """Get a formatted URL with sanitized query parameters."""
108 1
    base = req.base_url
109
110 1
    options = {k: v[0] for k, v in dict(req.args).items() if k not in skip}
111 1
    options.update(add)
112
113 1
    params = _format_query(options)
114
115 1
    if params:
116 1
        return base + "?{}".format("&".join(params))
117
    else:
118 1
        return base
119
120
121 1
def _format_query(options, *, as_string=False):
122 1
    pattern = "{}={!r}" if as_string else "{}={}"
123 1
    pairs = sorted(pattern.format(k, v) for k, v in options.items())
124 1
    if as_string:
125
        return ' '.join(pairs)
126 1
    return pairs
127
128
129 1
def _nocache(response):
130
    """Ensure a response is not cached."""
131
    response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
132
    response.headers['Pragma'] = 'no-cache'
133
    response.headers['Expires'] = '0'
134
    return response
135