Completed
Pull Request — master (#344)
by Jace
03:45
created

_secure()   A

Complexity

Conditions 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
c 2
b 0
f 0
dl 0
loc 5
rs 9.4285
ccs 4
cts 4
cp 1
crap 2
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 display(title, path, share=False, raw=False, mimetype='image/jpeg'):
19
    """Render a webpage or raw image based on request."""
20 1
    mimetypes = request.headers.get('Accept', "").split(',')
21 1
    browser = 'text/html' in mimetypes
22
23 1
    src = _format(request, 'share')
24 1
    src_twitter = _format(request, 'share',
25
                          width=current_app.config['TWITTER_IMAGE_WIDTH'],
26
                          height=current_app.config['TWITTER_IMAGE_HEIGHT'])
27 1
    src_facebook = _format(request, 'share',
28
                           width=current_app.config['FACEBOOK_IMAGE_WIDTH'],
29
                           height=current_app.config['FACEBOOK_IMAGE_HEIGHT'])
30 1
    href = _format(request, 'width', 'height')
31
32 1
    if share:
33 1
        log.info("Sharing image on page: %s", src)
34
35 1
        html = render_template(
36
            'share.html',
37
            title=title,
38
            src=_secure(src),
39
            src_twitter=_secure(src_twitter),
40
            src_facebook=_secure(src_facebook),
41
            href=_secure(href),
42
            config=current_app.config,
43
        )
44 1
        return html if raw else _nocache(Response(html))
45
46 1
    elif browser:
47 1
        log.info("Embedding image on page: %s", src)
48
49 1
        html = render_template(
50
            'image.html',
51
            title=title,
52
            src=_secure(src),
53
            config=current_app.config,
54
        )
55 1
        return html if raw else _nocache(Response(html))
56
57
    else:
58 1
        log.info("Sending image: %s", path)
59 1
        return send_file(path, mimetype=mimetype)
60
61
62 1
def track(title):
63
    """Log the requested content, server-side."""
64 1
    tid = current_app.config['GOOGLE_ANALYTICS_TID']
65
66 1
    data = dict(
67
        v=1,
68
        tid=tid,
69
        cid=request.remote_addr,
70
71
        t='pageview',
72
        dh='memegen.link',
73
        dp=request.full_path,
74
        dt=str(title),
75
76
        uip=request.remote_addr,
77
        ua=request.user_agent.string,
78
    )
79
80 1
    if tid == 'localhost':
81 1
        log.debug("Analytics data:\n%s", pprint.pformat(data))
82
    else:
83
        requests.post("http://www.google-analytics.com/collect", data=data)
84
85
86 1
def _secure(url):
87
    """Ensure HTTPS is used in production."""
88 1
    if current_app.config['ENV'] == 'prod':
89 1
        url = url.replace('http:', 'https:', 1)
90 1
    return url
91
92
93 1
def _format(req, *skip, **add):
94
    """Get a formatted URL with sanitized query parameters."""
95 1
    base = req.base_url
96
97 1
    options = {k: v[0] for k, v in dict(req.args).items() if k not in skip}
98 1
    options.update(add)
99
100 1
    params = sorted("{}={}".format(k, v) for k, v in options.items())
101
102 1
    if params:
103 1
        return base + "?{}".format("&".join(params))
104
    else:
105 1
        return base
106
107
108 1
def _nocache(response):
109
    """Ensure a response is not cached."""
110
    response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
111
    response.headers['Pragma'] = 'no-cache'
112
    response.headers['Expires'] = '0'
113
    return response
114