Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

PEP8 clean up

  • Loading branch information...
commit 72ad57dfcd9454e8197963f51ff694535d3f56b5 1 parent 4624187
@GrAndSE authored
View
3  lighty/commands.py
@@ -1,4 +1,4 @@
-'''Tools for run commands in framework environment using simple manage.py
+'''Tools for run commands in framework environment using simple manage.py
script
'''
import itertools
@@ -54,6 +54,7 @@ def manage():
except Exception as e:
print(e)
return
+
# Try to get command name
def error_msg(msg):
raise argparse.ArgumentTypeError('%s. Commands available:\n\t%s\n' % (
View
2  lighty/conf.py
@@ -84,7 +84,7 @@ def get(self, name, section=None):
if name in self.settings:
return self.settings[name]
else:
- if section in self.sections and name in self.sections[section]:
+ if section in self.sections and name in self.sections[section]:
return self.sections[section][name]
else:
raise KeyError('No section "%s" in configuration' % section)
View
8 lighty/monads.py
@@ -31,7 +31,7 @@ def wrapper(self):
def monad_operator(func):
- '''Decorator that wraps function with one arugment type checking and
+ '''Decorator that wraps function with one arugment type checking and
exception catching
'''
@functools.wraps(func)
@@ -39,7 +39,7 @@ def monad_operator(func):
def wrapper(self, value):
if isinstance(value, NoneMonad):
return value
- return ValueMonad(func(self, value.value
+ return ValueMonad(func(self, value.value
if isinstance(value, ValueMonad)
else value))
return wrapper
@@ -74,7 +74,7 @@ def check_argument(arg):
def monad_function(func):
- '''Decorator that wraps function with arguments, check all the values and
+ '''Decorator that wraps function with arguments, check all the values and
catch all the exceptions
'''
@functools.wraps(func)
@@ -216,7 +216,7 @@ def __init__(self, value):
'''Create new monad including value and store the code
'''
super(NoneMonad, self).__init__(value)
-
+
def __len__(self):
'''Returns 0
'''
View
18 lighty/templates/tag.py
@@ -1,8 +1,8 @@
-"""Package provides template tags manager and base tags list
+"""Package provides template tags manager and base tags list
"""
-VARIABLE = 0
-STRING = 1
-NUMBER = 2
+VARIABLE = 0
+STRING = 1
+NUMBER = 2
def parse_token(token):
@@ -20,7 +20,7 @@ def parse_token(token):
if idx > 0:
token_types.append(STRING)
tokens.append(word[0:idx])
- word = word[idx+1:]
+ word = word[idx + 1:]
if delim in word:
parts = word.split(delim)
tokens.append(parts[0])
@@ -55,17 +55,17 @@ def parse_token(token):
class TagManager(object):
- """Class used for tags manipulation
+ """Class used for tags manipulation
"""
def __init__(self):
- """Create new tag managet instance
+ """Create new tag managet instance
"""
super(TagManager, self).__init__()
self.tags = {}
def register(self, name, tag, is_block_tag=False, context_required=False,
- template_required=False, loader_required=False,
+ template_required=False, loader_required=False,
is_lazy_tag=True):
"""Register new tag
"""
@@ -98,7 +98,7 @@ def is_lazy_tag(self, name):
return self.is_tag_exists(name)[5]
def execute(self, name, token, context, block, template, loader):
- """Execute tag
+ """Execute tag
"""
tag = self.is_tag_exists(name)
args = {'token': token}
View
3  lighty/templates/template.py
@@ -250,9 +250,8 @@ def partial(self, context, name='', key_args=()):
return result
-
class LazyTemplate(Template):
- '''Lazy template class can be used to access
+ '''Lazy template class can be used to access
'''
def prepare(self):
View
8 lighty/templates/templatefilters.py
@@ -20,11 +20,11 @@ def sum(*args):
def float_format_args_parse(func, raw_value, format):
# Parse arguments
try:
- digits = abs(int(format))
+ digits = abs(int(format))
except:
raise Exception('%s arguments error: format is not integer' % func)
try:
- value = Decimal(raw_value)
+ value = Decimal(raw_value)
except:
raise Exception('%s supports only number values' % func)
return value, digits
@@ -95,9 +95,9 @@ def capfirst(value):
def stringformat(value, format):
- """Formats the variable according to the format, a string formatting
+ """Formats the variable according to the format, a string formatting
specifier.
-
+
This specifier uses Python string formating syntax, with the exception that
the leading "%" is dropped.
View
17 lighty/templates/templatetags.py
@@ -148,14 +148,14 @@ def spaceless(token, block, context):
"""This tag removes unused spaces
Template
-
+
{% spaceless %}
Some
text
{% endspaceless %}
will be rendered to:
-
+
Some text
"""
@@ -190,8 +190,8 @@ def with_tag(token, block, context):
"""
data_field, _, var_name = token.split(' ')
value = resolve(data_field, context)
- return exec_with_context(partial(exec_block, block),
- context, {var_name: value})
+ return exec_with_context(partial(exec_block, block), context,
+ {var_name: value})
tag_manager.register(
name='with',
@@ -212,7 +212,7 @@ def if_tag(token, block, context):
{% if user.is_authenticated %}Hello, {{ user.name }}!{% endif %}
TODO:
-
+
- add else
- add conditions
"""
@@ -247,7 +247,7 @@ def total(self):
@property
def last(self):
return not self.counter0 < self.total
-
+
@property
def first(self):
return self.counter0 == 0
@@ -267,7 +267,6 @@ def __call__(self, context):
return "".join([next for next in self.next(context)])
-
def for_tag(token, block, context):
"""For tag
@@ -276,7 +275,7 @@ def for_tag(token, block, context):
{% for a in items %}{{ a }}{% endfor %}
returns for items = [1, 2, 3]:
-
+
123
Also forloop variable will be added into scope. It contains few flags can
@@ -286,7 +285,7 @@ def for_tag(token, block, context):
{% spaceless %}<span
{% if forloop.first %} class="first"{% endif %}
{% if forloop.last %} class="last"{% endif %}>
- {{ forloop.counter0 }}.
+ {{ forloop.counter0 }}.
{{ forloop.counter }} from {{ forloop.total }}
</span>{% endspaceless %}
{% endfor %}
View
358 lighty/validators.py
@@ -1,221 +1,221 @@
-'''Describes validators
+'''Module contains base validators that can be used to check the data
'''
-import re, urllib
+import re
+import urllib
class ValidationError(Exception):
- '''
- Error on validation
- '''
-
- def __init__(self, message, code=None):
- '''
- Create new validation error instance with specified error message
- '''
- self.message = message
- if code is None:
- self.code = message
- else:
- self.code = code
-
- def __str__(self):
- '''
- Represent validation error
- '''
- return repr(self.message)
+ '''Error on validation
+ '''
+
+ def __init__(self, message, code=None):
+ '''Create new validation error instance with specified error message
+ '''
+ self.message = message
+ if code is None:
+ self.code = message
+ else:
+ self.code = code
+
+ def __str__(self):
+ '''
+ Represent validation error
+ '''
+ return repr(self.message)
class ChoicesValidator(object):
- '''Validator used to validate choices list
- '''
-
- def __init__(self, choices, message=None, code=None):
- '''Create new ChoicesValidator with specified choices.
-
- choices
- An iterable (e.g., a list or tuple) of 2-tuples to use as choices
- for this field.
-
- message
- The error message used by ValidationError if validation fails.
- Default value: None.
-
- code
- The error code used by ValidationError if validation fails. If code
- is not specified, "invalid" is used. Default value: None.
- '''
- self.choices = choices
- self.message = message
- if code is None:
- self.code = "invalid"
- else:
- self.code = code
-
- def __call__(self, value):
- '''Check is value argument inside of choices
- '''
- for choice in self.choices:
- if value in choice or (hasattr(choice[1], '__iter__') and
- value in choice[1]):
- return
- # Generate a message
- if self.message is None:
- message = '%s is not in choices list' % value
- else:
- message = self.message
- raise ValidationError(message, self.code)
+ '''Validator used to validate choices list
+ '''
+
+ def __init__(self, choices, message=None, code=None):
+ '''Create new ChoicesValidator with specified choices.
+
+ choices
+ An iterable (e.g., a list or tuple) of 2-tuples to use as choices
+ for this field.
+
+ message
+ The error message used by ValidationError if validation fails.
+ Default value: None.
+
+ code
+ The error code used by ValidationError if validation fails. If code
+ is not specified, "invalid" is used. Default value: None.
+ '''
+ self.choices = choices
+ self.message = message
+ if code is None:
+ self.code = "invalid"
+ else:
+ self.code = code
+
+ def __call__(self, value):
+ '''Check is value argument inside of choices
+ '''
+ for choice in self.choices:
+ if value in choice or (hasattr(choice[1], '__iter__') and
+ value in choice[1]):
+ return
+ # Generate a message
+ if self.message is None:
+ message = '%s is not in choices list' % value
+ else:
+ message = self.message
+ raise ValidationError(message, self.code)
class RegexValidator(object):
- '''
- Validator used to check is value
- '''
-
- def __init__(self, regex, message=None, code=None):
- '''
- Create new ChoicesValidator with specified choices.
-
- regex
- The regular expression pattern to search for the provided value, or
- a pre-compiled regular expression. Raises a ValidationError with
- message and code if no match is found.
-
- message
- The error message used by ValidationError if validation fails. If
- no message is specified, a generic "Enter a valid value" message is
- used. Default value: None.
-
- code
- The error code used by ValidationError if validation fails. If code
- is not specified, "invalid" is used. Default value: None.
- '''
- if isinstance(regex, str):
- regex = re.compile(regex)
- self.regex = regex
- if message is None:
- self.message = "Enter a valid value"
- else:
- self.message = message
- if code is None:
- self.code = "invalid"
- else:
- self.code = code
-
- def __call__(self, value):
- '''
- Check is value mathes pattern
- '''
- if self.regex.match(value) is None:
- raise ValidationError(self.message, self.code)
+ '''Validator used to check is value matches regular expression
+ '''
+ def __init__(self, regex, message=None, code=None):
+ '''
+ Create new ChoicesValidator with specified choices.
+
+ regex
+ The regular expression pattern to search for the provided value, or
+ a pre-compiled regular expression. Raises a ValidationError with
+ message and code if no match is found.
+
+ message
+ The error message used by ValidationError if validation fails. If
+ no message is specified, a generic "Enter a valid value" message is
+ used. Default value: None.
+
+ code
+ The error code used by ValidationError if validation fails. If code
+ is not specified, "invalid" is used. Default value: None.
+ '''
+ if isinstance(regex, str):
+ regex = re.compile(regex)
+ self.regex = regex
+ if message is None:
+ self.message = "Enter a valid value"
+ else:
+ self.message = message
+ if code is None:
+ self.code = "invalid"
+ else:
+ self.code = code
+
+ def __call__(self, value):
+ '''
+ Check is value mathes pattern
+ '''
+ if self.regex.match(value) is None:
+ raise ValidationError(self.message, self.code)
URL_VALIDATOR_USER_AGENT = ""
-URL_REGEX = "(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[a-z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\\b"
+URL_REGEX = ("(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[a-z]{2}|com|org|net|"
+ "edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\\b")
+
class URLValidator(RegexValidator):
- '''
- A RegexValidator that ensures a value looks like a URL and optionally
- verifies that the URL actually exists (i.e., doesn't return a 404 status
- code). Raises an error code of 'invalid' if it doesn't look like a URL, and
- a code of 'invalid_link' if it doesn't exist.
- '''
-
- def __init__(self, verify_exists=False,
- validator_user_agent=URL_VALIDATOR_USER_AGENT):
- '''
- verify_exists
- Default value: False. If set to True, this validator checks that
- the URL actually exists.
-
- validator_user_agent
- If verify_exists is True, Django uses the value of validator_user_
- agent as the "User-agent" for the request. This defaults to
- settings.URL_VALIDATOR_USER_AGENT.
- '''
- super(URLValidator, self).__init__(URL_REGEX, "Invalid URL format",
- "invalid")
- self.verify_exists = verify_exists
- self.validator_user_agent = validator_user_agent
-
- def __call__(self, url):
- '''
- Check is url valid
- '''
- super(URLValidator, self).__call__(url)
- if self.verify_exists:
- urlhandle = urllib.urlopen(url)
- if urlhandle.getcode() >= 400:
- raise ValidationError("Invalid link", "invalid_link")
-
-
-EMAIL_REGEX = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[a-z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$"
+ '''A RegexValidator that ensures a value looks like a URL and optionally
+ verifies that the URL actually exists (i.e., doesn't return a 404 status
+ code). Raises an error code of 'invalid' if it doesn't look like a URL, and
+ a code of 'invalid_link' if it doesn't exist.
+ '''
+
+ def __init__(self, verify_exists=False,
+ validator_user_agent=URL_VALIDATOR_USER_AGENT):
+ '''Create new URLValidator
+
+ verify_exists
+ Default value: False. If set to True, this validator checks that
+ the URL actually exists.
+
+ validator_user_agent
+ If verify_exists is True, Django uses the value of validator_user_
+ agent as the "User-agent" for the request. This defaults to
+ settings.URL_VALIDATOR_USER_AGENT.
+ '''
+ super(URLValidator, self).__init__(URL_REGEX, "Invalid URL format",
+ "invalid")
+ self.verify_exists = verify_exists
+ self.validator_user_agent = validator_user_agent
+
+ def __call__(self, url):
+ '''Check is url valid
+ '''
+ super(URLValidator, self).__call__(url)
+ if self.verify_exists:
+ urlhandle = urllib.urlopen(url)
+ if urlhandle.getcode() >= 400:
+ raise ValidationError("Invalid link", "invalid_link")
+
+EMAIL_REGEX = ("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)"
+ "*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[a-z]{2}|com|org|"
+ "net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$")
validate_email = RegexValidator(EMAIL_REGEX)
SLUG_REGEX = "^([\w-]+)$"
validate_slug = RegexValidator(SLUG_REGEX)
-IPV4_REGEX = "^(((25[0-5])|(2[0-4][\d])|([0-1]?\d?\d))(\.((25[0-5])|(2[0-4][\d])|([0-1]?\d?\d))){3})$"
+IPV4_REGEX = ("^(((25[0-5])|(2[0-4][\d])|([0-1]?\d?\d))(\.((25[0-5])|(2[0-4]"
+ "[\d])|([0-1]?\d?\d))){3})$")
validate_ipv4_address = RegexValidator(IPV4_REGEX)
validate_comma_separated_integer_list = RegexValidator("^(([\d]+\,)*[\d]+)$")
class MaxValueValidator:
- '''Raises a ValidationError with a code of 'max_value' if value is greater
- than max_value.
- '''
+ '''Raises a ValidationError with a code of 'max_value' if value is greater
+ than max_value.
+ '''
- def __init__(self, max_value):
- '''Create new MaxValueValidator with specified max_value
- '''
- self.max_value = max_value
+ def __init__(self, max_value):
+ '''Create new MaxValueValidator with specified max_value
+ '''
+ self.max_value = max_value
+
+ def __call__(self, value):
+ if value > self.max_value:
+ raise ValidationError("Not allowed value", 'max_value')
- def __call__(self, value):
- if value > self.max_value:
- raise ValidationError("Not allowed value", 'max_value')
class MinValueValidator:
- '''Raises a ValidationError with a code of 'min_value' if value is less
+ '''Raises a ValidationError with a code of 'min_value' if value is less
than min_value.
- '''
+ '''
- def __init__(self, min_value):
- '''Create new MinValueValidator with specified min_value
- '''
- self.min_value = min_value
+ def __init__(self, min_value):
+ '''Create new MinValueValidator with specified min_value
+ '''
+ self.min_value = min_value
- def __call__(self, value):
- if value < self.min_value:
- raise ValidationError("Not allowed value", 'min_value')
+ def __call__(self, value):
+ if value < self.min_value:
+ raise ValidationError("Not allowed value", 'min_value')
class MaxLengthValidator:
- '''Raises a ValidationError with a code of 'max_length' if length of value
+ '''Raises a ValidationError with a code of 'max_length' if length of value
is greater than max_value.
'''
- def __init__(self, max_length):
- '''
- Create new MaxLengthValidator with specified max_value
- '''
- self.max_length = max_length
+ def __init__(self, max_length):
+ '''
+ Create new MaxLengthValidator with specified max_value
+ '''
+ self.max_length = max_length
+
+ def __call__(self, value):
+ if len(value) > self.max_length:
+ raise ValidationError("Not allowed length", 'max_length')
- def __call__(self, value):
- if len(value) > self.max_length:
- raise ValidationError("Not allowed length", 'max_length')
class MinLengthValidator:
- '''
- Raises a ValidationError with a code of 'min_length' if length of value is
- less than min_length.
- '''
-
- def __init__(self, min_length):
- '''
- Create new MinValueValidator with specified min_value
- '''
- self.min_length = min_length
-
- def __call__(self, value):
- if len(value) < self.min_length:
- raise ValidationError("Not allowed length", 'min_length')
+ '''Raises a ValidationError with a code of 'min_length' if length of value
+ is less than min_length.
+ '''
+
+ def __init__(self, min_length):
+ '''Create new MinValueValidator with specified min_value
+ '''
+ self.min_length = min_length
+
+ def __call__(self, value):
+ if len(value) < self.min_length:
+ raise ValidationError("Not allowed length", 'min_length')
View
1  lighty/wsgi/decorators.py
@@ -13,6 +13,7 @@ def view(func, **constraints):
argument values
'''
func.is_view = True
+
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
View
5 lighty/wsgi/urls.py
@@ -25,8 +25,7 @@
def load_urls(name):
'''Load urls file. This file requires to contains urlpatterns variable. It
- could be list or tuple of results of url() function calling.
-
+ could be list or tuple of results of url() function calling.
from app_name.views import hello_view
@@ -40,7 +39,7 @@ def load_urls(name):
def load_view(view):
- '''Load view for name if needed
+ '''Load view for name if needed
'''
if callable(view):
return view if hasattr(view, 'is_view') else decorators.view(view)
Please sign in to comment.
Something went wrong with that request. Please try again.