Completed
Pull Request — master (#322)
by Jace
03:27
created

get_tid()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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 browser or share:
33 1
        log.info("Rending image on page: %s", src)
34
35 1
        html = render_template(
36
            'image.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
    else:
47 1
        log.info("Sending image: %s", path)
48 1
        return send_file(path, mimetype=mimetype)
49
50
51 1
def track(title):
52
    """Log the requested content, server-side."""
53 1
    tid = current_app.config['GOOGLE_ANALYTICS_TID']
54
55 1
    data = dict(
56
        v=1,
57
        tid=tid,
58
        cid=request.remote_addr,
59
60
        t='pageview',
61
        dh='memegen.link',
62
        dp=request.full_path,
63
        dt=str(title),
64
65
        uip=request.remote_addr,
66
        ua=request.user_agent.string,
67
    )
68
69 1
    if tid == 'localhost':
70 1
        log.debug("Analytics data:\n%s", pprint.pformat(data))
71
    else:
72
        requests.post("http://www.google-analytics.com/collect", data=data)
73
74
75 1
def _secure(url):
76
    """Ensure HTTPS is used in production."""
77 1
    if current_app.config['ENV'] == 'prod':
78
        url = url.replace('http:', 'https:')
79 1
    return url
80
81
82 1
def _format(req, *skip, **add):
83
    """Get a formatted URL with sanitized query parameters."""
84 1
    base = req.base_url
85
86 1
    options = {k: v[0] for k, v in dict(req.args).items() if k not in skip}
87 1
    options.update(add)
88
89 1
    params = sorted("{}={}".format(k, v) for k, v in options.items())
90
91 1
    if params:
92 1
        return base + "?{}".format("&".join(params))
93
    else:
94 1
        return base
95
96
97 1
def _nocache(response):
98
    """Ensure a response is not cached."""
99
    response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
100
    response.headers['Pragma'] = 'no-cache'
101
    response.headers['Expires'] = '0'
102
    return response
103