Completed
Push — master ( 0264a9...69cfd2 )
by Jace
19s
created

_format_query()   A

Complexity

Conditions 4

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.074

Importance

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