Skip to content

Commit

Permalink
Merge pull request apiguy#36 from raizyr/fix-code-style
Browse files Browse the repository at this point in the history
fix flake8 errors except for complexity
  • Loading branch information
hoatle authored Sep 23, 2016
2 parents 8063c46 + c49ce43 commit 30d2c70
Show file tree
Hide file tree
Showing 20 changed files with 241 additions and 107 deletions.
1 change: 1 addition & 0 deletions docs/_themes/flask_theme_support.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# flake8: noqa
# flasky extensions. flasky pygments style based on tango style
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Expand Down
1 change: 1 addition & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# -*- coding: utf-8 -*-
# flake8: noqa
#
# Flask Classy documentation build configuration file, created by
# sphinx-quickstart on Tue Oct 30 13:14:07 2012.
Expand Down
87 changes: 53 additions & 34 deletions flask_classful.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,6 @@
:license: BSD, see LICENSE for more details.
"""

__version__ = "0.14.0-dev0"


import sys
import functools
import inspect
Expand All @@ -23,6 +20,8 @@

_py2 = sys.version_info[0] == 2

__version__ = "0.14.0-dev0"


def route(rule, **options):
"""A decorator that is used to define custom routes for methods in
Expand All @@ -34,7 +33,7 @@ def decorator(f):
# Put the rule cache on the method itself instead of globally
if not hasattr(f, '_rule_cache') or f._rule_cache is None:
f._rule_cache = {f.__name__: [(rule, options)]}
elif not f.__name__ in f._rule_cache:
elif f.__name__ not in f._rule_cache:
f._rule_cache[f.__name__] = [(rule, options)]
else:
f._rule_cache[f.__name__].append((rule, options))
Expand All @@ -54,7 +53,9 @@ class FlaskView(object):
route_base = None
route_prefix = None
trailing_slash = True
method_dashified = False # TODO(hoatle): make True as default instead, this is not a compatible change
# TODO(hoatle): make method_dashified=True as default instead,
# this is not a compatible change
method_dashified = False
special_methods = {
"get": ["GET"],
"put": ["PUT"],
Expand Down Expand Up @@ -91,14 +92,16 @@ def register(cls, app, route_base=None, subdomain=None, route_prefix=None,
:param route_prefix: A prefix to be applied to all routes registered
for this class. Precedes route_base. Overrides
the class' route_prefix if it has been set.
:param trailing_slash: An option to put trailing slashes at the end of routes
without parameters.
:param method_dashified: An option to dashify method name from some_route to /some-route/
route instead of default /some_route/
:param trailing_slash: An option to put trailing slashes at the end of
routes without parameters.
:param method_dashified: An option to dashify method name from
some_route to /some-route/ route instead of
default /some_route/
"""

if cls is FlaskView:
raise TypeError("cls must be a subclass of FlaskView, not FlaskView itself")
raise TypeError(
"cls must be a subclass of FlaskView, not FlaskView itself")

if route_base:
cls.orig_route_base = cls.route_base
Expand Down Expand Up @@ -144,15 +147,19 @@ def register(cls, app, route_base=None, subdomain=None, route_prefix=None,
else:
endpoint = "{0!s}_{1:d}".format(route_name, idx)

app.add_url_rule(rule, endpoint, proxy, subdomain=subdomain, **options)
app.add_url_rule(
rule, endpoint, proxy,
subdomain=subdomain, **options)

elif name in cls.special_methods:
methods = cls.special_methods[name]

rule = cls.build_rule("/", value)
if not cls.trailing_slash and rule != '/':
rule = rule.rstrip("/")
app.add_url_rule(rule, route_name, proxy, methods=methods, subdomain=subdomain)
app.add_url_rule(
rule, route_name, proxy,
methods=methods, subdomain=subdomain)

else:
if cls.method_dashified is True:
Expand All @@ -161,9 +168,12 @@ def register(cls, app, route_base=None, subdomain=None, route_prefix=None,
if not cls.trailing_slash:
route_str = route_str.rstrip('/')
rule = cls.build_rule(route_str, value)
app.add_url_rule(rule, route_name, proxy, subdomain=subdomain)
app.add_url_rule(
rule, route_name, proxy, subdomain=subdomain)
except DecoratorCompatibilityError:
raise DecoratorCompatibilityError("Incompatible decorator detected on {0!s} in class {1!s}".format(name, cls.__name__))
raise DecoratorCompatibilityError(
"Incompatible decorator detected on {0!s} in class {1!s}"
.format(name, cls.__name__))

if hasattr(cls, "orig_route_base"):
cls.route_base = cls.orig_route_base
Expand Down Expand Up @@ -203,7 +213,8 @@ def make_proxy_method(cls, name):
i = cls()
view = getattr(i, name)

# Since the view is a bound instance method, first make it an actual function
# Since the view is a bound instance method,
# first make it an actual function
# So function attributes work correctly
def make_func(fn):
@functools.wraps(fn)
Expand Down Expand Up @@ -246,23 +257,26 @@ def proxy(**forgettable_view_args):
if not isinstance(response, ResponseBase):

if not cls.representations:
# No representations defined, then the default is to just output
# what the view function returned as a response
# No representations defined, then the default is to just
# output what the view function returned as a response
response = make_response(response, code, headers)
else:
# Return the representation that best matches the representations
# in the Accept header
# Return the representation that best matches the
# representations in the Accept header
resp_representation = request.accept_mimetypes.best_match(
cls.representations.keys())

if resp_representation:
response = cls.representations[resp_representation](response, code, headers)
response = cls.representations[
resp_representation
](response, code, headers)
else:
# Nothing adequate found, make the response any one of the representations
# defined
# Nothing adequate found, make the response any one of
# the representations defined
# TODO(hoatle): or just make_response?
response = cls.representations[list(cls.representations.keys())[0]](
response, code, headers)
response = cls.representations[
list(cls.representations.keys())[0]
](response, code, headers)

# If the header or code is set, regenerate the response
elif any(x is not None for x in (code, headers)):
Expand All @@ -280,7 +294,6 @@ def proxy(**forgettable_view_args):

return response


return proxy

@classmethod
Expand Down Expand Up @@ -313,12 +326,12 @@ def build_rule(cls, rule, method=None):
if method:
argspec = get_true_argspec(method)
args = argspec[0]
query_params = argspec[3] # All default args that should be ignored
query_params = argspec[3] # All default args should be ignored
annotations = getattr(argspec, 'annotations', {})
for i, arg in enumerate(args):
if arg not in ignored_rule_args:
if not query_params or len(args) - i > len(query_params):
# This is not optional param, so it's not query argument
# This isn't optional param, so it's not query argument
rule_part = "<{0!s}>".format(arg)
if not _py2:
# in py3, try to determine url variable converters
Expand All @@ -330,7 +343,6 @@ def build_rule(cls, rule, method=None):
result = "/{0!s}".format("/".join(rule_parts))
return re.sub(r'(/)\1+', r'\1', result)


@classmethod
def get_route_base(cls):
"""Returns the route base to use for the current class."""
Expand All @@ -354,7 +366,6 @@ def default_route_base(cls):

return route_base


@classmethod
def build_route_name(cls, method_name):
"""Creates a unique route name based on the combination of the class
Expand All @@ -367,11 +378,12 @@ def build_route_name(cls, method_name):

def _dashify_uppercase(name):
"""convert somethingWithUppercase into something-with-uppercase"""
first_cap_re = re.compile('(.)([A-Z][a-z]+)') # better to define this once
first_cap_re = re.compile('(.)([A-Z][a-z]+)') # better to define this once
all_cap_re = re.compile('([a-z0-9])([A-Z])')
s1 = first_cap_re.sub(r'\1-\2', name)
return all_cap_re.sub(r'\1-\2', s1).lower()


def _dashify_underscore(name):
"""convert something_with_underscore into something-with-underscore"""
return '-'.join(re.split('_', name))
Expand All @@ -385,14 +397,21 @@ def get_interesting_members(base_class, cls):
all_members = inspect.getmembers(cls, predicate=predicate)
return [member for member in all_members
if not member[0] in base_members
and ((hasattr(member[1], "__self__") and not member[1].__self__ in inspect.getmro(cls)) if _py2 else True)
and (
(hasattr(member[1], "__self__")
and not member[1].__self__ in inspect.getmro(cls))
if _py2 else True
)
and not member[0].startswith("_")
and not member[0].startswith("before_")
and not member[0].startswith("after_")]


def get_true_argspec(method):
"""Drills through layers of decorators attempting to locate the actual argspec for the method."""
"""
Drills through layers of decorators attempting to locate the actual argspec
for the method.
"""

try:
argspec = inspect.getargspec(method)
Expand All @@ -412,8 +431,8 @@ def get_true_argspec(method):
inner_method = cell.cell_contents
if inner_method is method:
continue
if not inspect.isfunction(inner_method) \
and not inspect.ismethod(inner_method):
if not inspect.isfunction(inner_method)\
and not inspect.ismethod(inner_method):
continue
true_argspec = get_true_argspec(inner_method)
if true_argspec:
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"""
import os
import re
from setuptools import setup, find_packages
from setuptools import setup


def get_file(*parts):
Expand Down
16 changes: 15 additions & 1 deletion test_classful/test_blueprints.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from flask import Flask, Blueprint
from .view_classes import BasicView, IndexView, JSONifyTestView
from nose.tools import *
from nose.tools import eq_

app = Flask("blueprints")
bp = Blueprint("bptest", "bptest")
Expand All @@ -13,61 +13,75 @@

client = app.test_client()


def test_bp_index():
resp = client.get("/basic/")
eq_(b"Index", resp.data)


def test_bp_get():
resp = client.get("/basic/1234")
eq_(b"Get 1234", resp.data)


def test_bp_put():
resp = client.put("/basic/1234")
eq_(b"Put 1234", resp.data)


def test_bp_patch():
resp = client.patch("/basic/1234")
eq_(b"Patch 1234", resp.data)


def test_bp_post():
resp = client.post("/basic/")
eq_(b"Post", resp.data)


def test_bp_delete():
resp = client.delete("/basic/1234")
eq_(b"Delete 1234", resp.data)


def test_bp_custom_method():
resp = client.get("/basic/custom_method/")
eq_(b"Custom Method", resp.data)


def test_bp_custom_method_with_params():
resp = client.get("/basic/custom_method_with_params/1234/abcd")
eq_(b"Custom Method 1234 abcd", resp.data)


def test_bp_routed_method():
resp = client.get("/basic/routed/")
eq_(b"Routed Method", resp.data)


def test_bp_multi_routed_method():
resp = client.get("/basic/route1/")
eq_(b"Multi Routed Method", resp.data)

resp = client.get("/basic/route2/")
eq_(b"Multi Routed Method", resp.data)


def test_bp_no_slash():
resp = client.get("/basic/noslash")
eq_(b"No Slash Method", resp.data)


def test_bp_index_view_index():
resp = client.get("/")
eq_(b"Index", resp.data)


def test_bp_custom_http_method():
resp = client.post("/basic/route3/")
eq_(b"Custom HTTP Method", resp.data)


def test_bp_url_prefix():
foo = Blueprint('foo', __name__)
BasicView.register(foo, route_base="/")
Expand Down
12 changes: 7 additions & 5 deletions test_classful/test_bp_subdomains.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from flask import Flask, Blueprint
from .view_classes import BasicView, SubdomainAttributeView, SubdomainRouteView
from nose.tools import *
from nose.tools import eq_

app = Flask("blueprints")
app.config["SERVER_NAME"] = "test.test"
Expand All @@ -18,21 +18,23 @@

client = app.test_client()


def test_bp_attr_subdomain():
resp = client.get("/subdomain-attribute/", base_url="http://sub1.test.test")
resp = client.get(
"/subdomain-attribute/", base_url="http://sub1.test.test")
eq_(b"Index", resp.data)


def test_bp_route_subdomain():
resp = client.get("/subdomain-route/", base_url="http://sub2.test.test")
eq_(b"Index", resp.data)


def test_bp_register_subdomain():
resp = client.get("/basic/", base_url="http://sub3.test.test")
eq_(b"Index", resp.data)


def test_bp_bp_subdomain():
resp = client.get("/basic/", base_url="http://sub4.test.test")
eq_(b"Index", resp.data)



Loading

0 comments on commit 30d2c70

Please sign in to comment.