File: application.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 (47 lines) | stat: -rw-r--r-- 1,501 bytes parent folder | download
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
from couchdb.client import Server
from werkzeug.exceptions import HTTPException
from werkzeug.exceptions import NotFound
from werkzeug.middleware.shared_data import SharedDataMiddleware
from werkzeug.wrappers import Request
from werkzeug.wsgi import ClosingIterator

from . import views
from .models import URL
from .utils import local
from .utils import local_manager
from .utils import STATIC_PATH
from .utils import url_map


class Couchy(object):
    def __init__(self, db_uri):
        local.application = self

        server = Server(db_uri)
        try:
            db = server.create("urls")
        except Exception:
            db = server["urls"]
        self.dispatch = SharedDataMiddleware(self.dispatch, {"/static": STATIC_PATH})

        URL.db = db

    def dispatch(self, environ, start_response):
        local.application = self
        request = Request(environ)
        local.url_adapter = adapter = url_map.bind_to_environ(environ)
        try:
            endpoint, values = adapter.match()
            handler = getattr(views, endpoint)
            response = handler(request, **values)
        except NotFound:
            response = views.not_found(request)
            response.status_code = 404
        except HTTPException as e:
            response = e
        return ClosingIterator(
            response(environ, start_response), [local_manager.cleanup]
        )

    def __call__(self, environ, start_response):
        return self.dispatch(environ, start_response)