File: views.py

package info (click to toggle)
python-werkzeug 1.0.1%2Bdfsg1-2%2Bdeb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 2,888 kB
  • sloc: python: 21,897; javascript: 173; makefile: 36; xml: 16
file content (73 lines) | stat: -rw-r--r-- 2,120 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from werkzeug.exceptions import NotFound
from werkzeug.utils import redirect

from .models import URL
from .utils import expose
from .utils import Pagination
from .utils import render_template
from .utils import url_for
from .utils import validate_url


@expose("/")
def new(request):
    error = url = ""
    if request.method == "POST":
        url = request.form.get("url")
        alias = request.form.get("alias")
        if not validate_url(url):
            error = "I'm sorry but you cannot shorten this URL."
        elif alias:
            if len(alias) > 140:
                error = "Your alias is too long"
            elif "/" in alias:
                error = "Your alias might not include a slash"
            elif URL.load(alias):
                error = "The alias you have requested exists already"
        if not error:
            url = URL(
                target=url,
                public="private" not in request.form,
                shorty_id=alias if alias else None,
            )
            url.store()
            uid = url.id
            return redirect(url_for("display", uid=uid))
    return render_template("new.html", error=error, url=url)


@expose("/display/<uid>")
def display(request, uid):
    url = URL.load(uid)
    if not url:
        raise NotFound()
    return render_template("display.html", url=url)


@expose("/u/<uid>")
def link(request, uid):
    url = URL.load(uid)
    if not url:
        raise NotFound()
    return redirect(url.target, 301)


@expose("/list/", defaults={"page": 1})
@expose("/list/<int:page>")
def list(request, page):
    def wrap(doc):
        data = doc.value
        data["_id"] = doc.id
        return URL.wrap(data)

    code = """function(doc) { if (doc.public){ map([doc._id], doc); }}"""
    docResults = URL.query(code)
    results = [wrap(doc) for doc in docResults]
    pagination = Pagination(results, 1, page, "list")
    if pagination.page > 1 and not pagination.entries:
        raise NotFound()
    return render_template("list.html", pagination=pagination)


def not_found(request):
    return render_template("not_found.html")