summaryrefslogtreecommitdiff
path: root/examples/couchy
diff options
context:
space:
mode:
authorDavid Lord <davidism@gmail.com>2019-02-13 11:44:18 -0800
committerDavid Lord <davidism@gmail.com>2019-03-08 08:01:31 -0800
commitab6150fa49afc61b0c5eed6d9545d03d1958e384 (patch)
treead5f13c9c2775ca59cc8e82ec124c4e065a65d1b /examples/couchy
parent048d707d25685e6aea675c53945ceb7619e60344 (diff)
downloadwerkzeug-code-style.tar.gz
apply code stylecode-style
* reorder-python-imports * line fixers * black * flake8
Diffstat (limited to 'examples/couchy')
-rw-r--r--examples/couchy/README1
-rw-r--r--examples/couchy/application.py30
-rw-r--r--examples/couchy/models.py22
-rw-r--r--examples/couchy/utils.py51
-rw-r--r--examples/couchy/views.py64
5 files changed, 103 insertions, 65 deletions
diff --git a/examples/couchy/README b/examples/couchy/README
index 1821ed11..24960448 100644
--- a/examples/couchy/README
+++ b/examples/couchy/README
@@ -5,4 +5,3 @@ Requirements :
- jinja : http://jinja.pocoo.org
- couchdb 0.72 & above : https://couchdb.apache.org/
- couchdb-python 0.3 & above : https://github.com/djc/couchdb-python
-
diff --git a/examples/couchy/application.py b/examples/couchy/application.py
index f3a56a63..b958dcbc 100644
--- a/examples/couchy/application.py
+++ b/examples/couchy/application.py
@@ -1,27 +1,28 @@
from couchdb.client import Server
-from couchy.utils import STATIC_PATH, local, local_manager, \
- url_map
+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 werkzeug.exceptions import HTTPException, NotFound
-from couchy import views
-from couchy.models import URL
+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):
+class Couchy(object):
def __init__(self, db_uri):
local.application = self
server = Server(db_uri)
try:
- db = server.create('urls')
- except:
- db = server['urls']
- self.dispatch = SharedDataMiddleware(self.dispatch, {
- '/static': STATIC_PATH
- })
+ db = server.create("urls")
+ except Exception:
+ db = server["urls"]
+ self.dispatch = SharedDataMiddleware(self.dispatch, {"/static": STATIC_PATH})
URL.db = db
@@ -38,8 +39,9 @@ class Couchy(object):
response.status_code = 404
except HTTPException as e:
response = e
- return ClosingIterator(response(environ, start_response),
- [local_manager.cleanup])
+ return ClosingIterator(
+ response(environ, start_response), [local_manager.cleanup]
+ )
def __call__(self, environ, start_response):
return self.dispatch(environ, start_response)
diff --git a/examples/couchy/models.py b/examples/couchy/models.py
index 4621a744..a0b50ca1 100644
--- a/examples/couchy/models.py
+++ b/examples/couchy/models.py
@@ -1,6 +1,12 @@
from datetime import datetime
-from couchdb.mapping import Document, TextField, BooleanField, DateTimeField
-from couchy.utils import url_for, get_random_uid
+
+from couchdb.mapping import BooleanField
+from couchdb.mapping import DateTimeField
+from couchdb.mapping import Document
+from couchdb.mapping import TextField
+
+from .utils import get_random_uid
+from .utils import url_for
class URL(Document):
@@ -19,13 +25,15 @@ class URL(Document):
return URL.db.query(code)
def store(self):
- if getattr(self._data, 'id', None) is None:
+ if getattr(self._data, "id", None) is None:
new_id = self.shorty_id if self.shorty_id else None
while 1:
id = new_id if new_id else get_random_uid()
try:
- docid = URL.db.resource.put(content=self._data, path='/%s/' % str(id))['id']
- except:
+ docid = URL.db.resource.put(
+ content=self._data, path="/%s/" % str(id)
+ )["id"]
+ except Exception:
continue
if docid:
break
@@ -36,7 +44,7 @@ class URL(Document):
@property
def short_url(self):
- return url_for('link', uid=self.id, _external=True)
+ return url_for("link", uid=self.id, _external=True)
def __repr__(self):
- return '<URL %r>' % self.id
+ return "<URL %r>" % self.id
diff --git a/examples/couchy/utils.py b/examples/couchy/utils.py
index 4fe666a3..571a7ed9 100644
--- a/examples/couchy/utils.py
+++ b/examples/couchy/utils.py
@@ -1,49 +1,62 @@
from os import path
-from random import sample, randrange
-from jinja2 import Environment, FileSystemLoader
-from werkzeug.local import Local, LocalManager
+from random import randrange
+from random import sample
+
+from jinja2 import Environment
+from jinja2 import FileSystemLoader
+from werkzeug.local import Local
+from werkzeug.local import LocalManager
+from werkzeug.routing import Map
+from werkzeug.routing import Rule
from werkzeug.urls import url_parse
from werkzeug.utils import cached_property
from werkzeug.wrappers import Response
-from werkzeug.routing import Map, Rule
-TEMPLATE_PATH = path.join(path.dirname(__file__), 'templates')
-STATIC_PATH = path.join(path.dirname(__file__), 'static')
-ALLOWED_SCHEMES = frozenset(['http', 'https', 'ftp', 'ftps'])
-URL_CHARS = 'abcdefghijkmpqrstuvwxyzABCDEFGHIJKLMNPQRST23456789'
+TEMPLATE_PATH = path.join(path.dirname(__file__), "templates")
+STATIC_PATH = path.join(path.dirname(__file__), "static")
+ALLOWED_SCHEMES = frozenset(["http", "https", "ftp", "ftps"])
+URL_CHARS = "abcdefghijkmpqrstuvwxyzABCDEFGHIJKLMNPQRST23456789"
local = Local()
local_manager = LocalManager([local])
-application = local('application')
+application = local("application")
-url_map = Map([Rule('/static/<file>', endpoint='static', build_only=True)])
+url_map = Map([Rule("/static/<file>", endpoint="static", build_only=True)])
jinja_env = Environment(loader=FileSystemLoader(TEMPLATE_PATH))
def expose(rule, **kw):
def decorate(f):
- kw['endpoint'] = f.__name__
+ kw["endpoint"] = f.__name__
url_map.add(Rule(rule, **kw))
return f
+
return decorate
+
def url_for(endpoint, _external=False, **values):
return local.url_adapter.build(endpoint, values, force_external=_external)
-jinja_env.globals['url_for'] = url_for
+
+
+jinja_env.globals["url_for"] = url_for
+
def render_template(template, **context):
- return Response(jinja_env.get_template(template).render(**context),
- mimetype='text/html')
+ return Response(
+ jinja_env.get_template(template).render(**context), mimetype="text/html"
+ )
+
def validate_url(url):
return url_parse(url)[0] in ALLOWED_SCHEMES
+
def get_random_uid():
- return ''.join(sample(URL_CHARS, randrange(3, 9)))
+ return "".join(sample(URL_CHARS, randrange(3, 9)))
-class Pagination(object):
+class Pagination(object):
def __init__(self, results, per_page, page, endpoint):
self.results = results
self.per_page = per_page
@@ -56,7 +69,11 @@ class Pagination(object):
@cached_property
def entries(self):
- return self.results[((self.page - 1) * self.per_page):(((self.page - 1) * self.per_page)+self.per_page)]
+ return self.results[
+ ((self.page - 1) * self.per_page) : (
+ ((self.page - 1) * self.per_page) + self.per_page
+ )
+ ]
has_previous = property(lambda self: self.page > 1)
has_next = property(lambda self: self.page < self.pages)
diff --git a/examples/couchy/views.py b/examples/couchy/views.py
index 39c8ea29..c1547e7d 100644
--- a/examples/couchy/views.py
+++ b/examples/couchy/views.py
@@ -1,61 +1,73 @@
-from werkzeug.utils import redirect
from werkzeug.exceptions import NotFound
-from couchy.utils import render_template, expose, \
- validate_url, url_for, Pagination
-from couchy.models import URL
+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('/')
+
+@expose("/")
def new(request):
- error = url = ''
- if request.method == 'POST':
- url = request.form.get('url')
- alias = request.form.get('alias')
+ 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'
+ 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'
+ 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 = 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)
+ return redirect(url_for("display", uid=uid))
+ return render_template("new.html", error=error, url=url)
+
-@expose('/display/<uid>')
+@expose("/display/<uid>")
def display(request, uid):
url = URL.load(uid)
if not url:
raise NotFound()
- return render_template('display.html', url=url)
+ return render_template("display.html", url=url)
-@expose('/u/<uid>')
+
+@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>')
+
+@expose("/list/", defaults={"page": 1})
+@expose("/list/<int:page>")
def list(request, page):
def wrap(doc):
data = doc.value
- data['_id'] = doc.id
+ data["_id"] = doc.id
return URL.wrap(data)
- code = '''function(doc) { if (doc.public){ map([doc._id], doc); }}'''
+ 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')
+ pagination = Pagination(results, 1, page, "list")
if pagination.page > 1 and not pagination.entries:
raise NotFound()
- return render_template('list.html', pagination=pagination)
+ return render_template("list.html", pagination=pagination)
+
def not_found(request):
- return render_template('not_found.html')
+ return render_template("not_found.html")