Skip to content

Commit

Permalink
Reformat.
Browse files Browse the repository at this point in the history
  • Loading branch information
sfermigier committed Jul 18, 2016
1 parent 17f36a5 commit 026361d
Show file tree
Hide file tree
Showing 84 changed files with 1,264 additions and 1,251 deletions.
110 changes: 57 additions & 53 deletions abilian/app.py
Expand Up @@ -250,28 +250,30 @@ def __init__(self, name=None, config=None, *args, **kwargs):
self.config['BABEL_ACCEPT_LANGUAGES'] = languages

self._jinja_loaders = list()
self.register_jinja_loaders(jinja2.PackageLoader('abilian.web',
'templates'))
self.register_jinja_loaders(
jinja2.PackageLoader('abilian.web', 'templates'))

js_filters = (('closure_js',)
if self.config.get('PRODUCTION', False) else None)

self._assets_bundles = {
'css': {'options': dict(filters=('less', 'cssmin'),
output='style-%(version)s.min.css',)},
'js-top': {'options': dict(output='top-%(version)s.min.js',
filters=js_filters,)},
'js': {'options': dict(output='app-%(version)s.min.js',
filters=js_filters)},
'css': {'options': dict(
filters=('less', 'cssmin'),
output='style-%(version)s.min.css',)},
'js-top': {'options': dict(
output='top-%(version)s.min.js',
filters=js_filters,)},
'js': {'options': dict(
output='app-%(version)s.min.js', filters=js_filters)},
}

# bundles for JS translations
for lang in languages:
code = 'js-i18n-' + lang
filename = 'lang-' + lang + '-%(version)s.min.js'
self._assets_bundles[code] = {
'options': dict(output=filename,
filters=js_filters),
'options': dict(
output=filename, filters=js_filters),
}

for http_error_code in (403, 404, 500):
Expand All @@ -280,17 +282,17 @@ def __init__(self, name=None, config=None, *args, **kwargs):
with self.app_context():
self.init_extensions()
self.register_plugins()
self.add_access_controller('static',
allow_access_for_roles(Anonymous),
endpoint=True)
self.add_access_controller(
'static', allow_access_for_roles(Anonymous), endpoint=True)
# debugtoolbar: this is needed to have it when not authenticated on a
# private site. We cannot do this in init_debug_toolbar, since auth
# service is not yet installed
self.add_access_controller('debugtoolbar',
allow_access_for_roles(Anonymous),)
self.add_access_controller('_debug_toolbar.static',
allow_access_for_roles(Anonymous),
endpoint=True)
self.add_access_controller(
'_debug_toolbar.static',
allow_access_for_roles(Anonymous),
endpoint=True)

self.maybe_register_setup_wizard()
self._finalize_assets_setup()
Expand Down Expand Up @@ -368,8 +370,9 @@ def init_breadcrumbs(self):
This happens during `request_started` event, which is triggered before any
url_value_preprocessor and `before_request` handlers.
"""
g.breadcrumb.append(BreadcrumbItem(icon='home',
url='/' + request.script_root))
g.breadcrumb.append(
BreadcrumbItem(
icon='home', url='/' + request.script_root))

def check_instance_folder(self, create=False):
"""Verify instance folder exists, is a directory, and has necessary permissions.
Expand Down Expand Up @@ -443,15 +446,15 @@ def setup_logging(self):

logging_file = self.config.get('LOGGING_CONFIG_FILE')
if logging_file:
logging_file = os.path.abspath(os.path.join(self.instance_path,
logging_file))
logging_file = os.path.abspath(
os.path.join(self.instance_path, logging_file))
else:
logging_file = resource_filename(__name__, 'default_logging.yml')

if logging_file.endswith('.conf'):
# old standard 'ini' file config
logging.config.fileConfig(logging_file,
disable_existing_loggers=False)
logging.config.fileConfig(
logging_file, disable_existing_loggers=False)
elif logging_file.endswith('.yml'):
# yml config file
logging_cfg = yaml.load(open(logging_file, 'r'))
Expand Down Expand Up @@ -512,9 +515,8 @@ def init_extensions(self):
babel.timezone_selector_func = None

babel.init_app(self)
babel.add_translations('wtforms',
translations_dir='locale',
domain='wtforms')
babel.add_translations(
'wtforms', translations_dir='locale', domain='wtforms')
babel.add_translations('abilian')
babel.localeselector(abilian.i18n.localeselector)
babel.timezoneselector(abilian.i18n.timezoneselector)
Expand Down Expand Up @@ -605,9 +607,8 @@ def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
**options)

if roles:
self.add_access_controller(endpoint,
allow_access_for_roles(roles),
endpoint=True)
self.add_access_controller(
endpoint, allow_access_for_roles(roles), endpoint=True)

def add_access_controller(self, name, func, endpoint=False):
"""Add an access controller.
Expand Down Expand Up @@ -644,29 +645,30 @@ def add_static_url(self, url_path, directory, endpoint=None, roles=None):
`/path/to/myplugin/resources` from url `http://.../static/myplugin`
"""
url_path = self.static_url_path + '/' + url_path + '/<path:filename>'
self.add_url_rule(url_path,
endpoint=endpoint,
view_func=partial(send_file_from_directory,
directory=directory),
roles=roles)
self.add_access_controller(endpoint,
allow_access_for_roles(Anonymous),
endpoint=True)
self.add_url_rule(
url_path,
endpoint=endpoint,
view_func=partial(
send_file_from_directory, directory=directory),
roles=roles)
self.add_access_controller(
endpoint, allow_access_for_roles(Anonymous), endpoint=True)

#
# Templating and context injection setup
#
def create_jinja_environment(self):
env = Flask.create_jinja_environment(self)
env.globals.update(app=current_app,
csrf=csrf,
get_locale=babel_get_locale,
local_dt=abilian.core.util.local_dt,
_n=abilian.i18n._n,
url_for=url_for,
user_photo_url=user_photo_url,
NO_VALUE=NO_VALUE,
NEVER_SET=NEVER_SET,)
env.globals.update(
app=current_app,
csrf=csrf,
get_locale=babel_get_locale,
local_dt=abilian.core.util.local_dt,
_n=abilian.i18n._n,
url_for=url_for,
user_photo_url=user_photo_url,
NO_VALUE=NO_VALUE,
NEVER_SET=NEVER_SET,)
init_filters(env)
return env

Expand Down Expand Up @@ -815,10 +817,11 @@ def create_db(self):

db.create_all()
if User.query.get(0) is None:
root = User(id=0,
last_name='SYSTEM',
email='system@example.com',
can_login=False)
root = User(
id=0,
last_name='SYSTEM',
email='system@example.com',
can_login=False)
db.session.add(root)
db.session.commit()

Expand Down Expand Up @@ -858,10 +861,11 @@ def _setup_asset_extension(self):
# static minified are here
assets.url = self.static_url_path + '/min'
assets.append_path(str(assets_dir), assets.url)
self.add_static_url('min',
str(assets_dir),
endpoint='webassets_static',
roles=Anonymous,)
self.add_static_url(
'min',
str(assets_dir),
endpoint='webassets_static',
roles=Anonymous,)

def _finalize_assets_setup(self):
assets = self.extensions['webassets']
Expand Down
85 changes: 42 additions & 43 deletions abilian/core/commands/base.py
Expand Up @@ -7,12 +7,11 @@
import runpy
from pprint import pformat

from six.moves import input
from six.moves import urllib
import sqlalchemy as sa
from flask import current_app
from flask_script import Manager, prompt_pass
from six import text_type
from six.moves import input, urllib

from abilian.core.extensions import db
from abilian.core.logging import patch_logger
Expand Down Expand Up @@ -94,23 +93,22 @@ def log_config(config):
logger.setLevel(original_level)


@manager.option('-p',
'--port',
dest='port',
help='listening port',
default=5000)
@manager.option('--show-config',
dest='show_config',
action='store_const',
const=True,
default=False,
help='show application configuration on startup')
@manager.option('--ssl',
dest='ssl',
action='store_const',
default=False,
const=True,
help='Enable werkzeug SSL')
@manager.option(
'-p', '--port', dest='port', help='listening port', default=5000)
@manager.option(
'--show-config',
dest='show_config',
action='store_const',
const=True,
default=False,
help='show application configuration on startup')
@manager.option(
'--ssl',
dest='ssl',
action='store_const',
default=False,
const=True,
help='Enable werkzeug SSL')
def run(port, show_config, ssl):
"""Like runserver. May also print application configuration if used with
--show-config.
Expand Down Expand Up @@ -166,25 +164,25 @@ def routes():

# user commands
email_opt = manager.option('email', help='user\'s email')
password_opt = manager.option('-p',
'--password',
dest='password',
default=None,
help='If absent, a prompt will ask for password',)
role_opt = manager.option('-r',
'--role',
dest='role',
choices=[r.name for r in Role.assignable_roles()],)
name_opt = manager.option('-n',
'--name',
dest='name',
default=None,
help='Last name (e.g "Smith")')
firstname_opt = manager.option('-f',
'--firstname',
dest='first_name',
default=None,
help='Fist name (e.g. "John")')
password_opt = manager.option(
'-p',
'--password',
dest='password',
default=None,
help='If absent, a prompt will ask for password',)
role_opt = manager.option(
'-r',
'--role',
dest='role',
choices=[r.name for r in Role.assignable_roles()],)
name_opt = manager.option(
'-n', '--name', dest='name', default=None, help='Last name (e.g "Smith")')
firstname_opt = manager.option(
'-f',
'--firstname',
dest='first_name',
default=None,
help='Fist name (e.g. "John")')


@email_opt
Expand All @@ -203,11 +201,12 @@ def createuser(email, password, role=None, name=None, first_name=None):
if password is None:
password = prompt_pass(u'Password')

user = User(email=email,
password=password,
last_name=name,
first_name=first_name,
can_login=True)
user = User(
email=email,
password=password,
last_name=name,
first_name=first_name,
can_login=True)
db.session.add(user)

if role in ('admin',):
Expand Down
5 changes: 3 additions & 2 deletions abilian/core/commands/config.py
Expand Up @@ -14,8 +14,9 @@
from .base import log_config, logger

#: sub-manager for config commands
manager = Manager(description='Show config / create default config',
help='Show config / create default config')
manager = Manager(
description='Show config / create default config',
help='Show config / create default config')


@manager.command
Expand Down
9 changes: 4 additions & 5 deletions abilian/core/commands/indexing.py
Expand Up @@ -36,17 +36,16 @@ def reindex(clear=False, progressive=False, batch_size=None):
svc = current_app.services['indexing']
adapted = svc.adapted
index = svc.app_state.indexes['default']
session = Session(bind=current_app.db.session.get_bind(None, None),
autocommit=True)
session = Session(
bind=current_app.db.session.get_bind(None, None), autocommit=True)

setattr(session, '_model_changes', {}) # please flask-sqlalchemy <= 1.0
indexed = set()
cleared = set()
if batch_size is not None:
batch_size = int(batch_size)
strategy_kw = dict(clear=clear,
progressive=progressive,
batch_size=batch_size)
strategy_kw = dict(
clear=clear, progressive=progressive, batch_size=batch_size)
strategy = progressive_mode if progressive else single_transaction
strategy = strategy(index, **strategy_kw)
next(strategy) # starts generator
Expand Down
21 changes: 10 additions & 11 deletions abilian/core/entities.py
Expand Up @@ -127,12 +127,12 @@ class _EntityInherit(object):

@declared_attr
def id(cls):
return Column(Integer,
ForeignKey('entity.id',
use_alter=True,
name='fk_inherited_entity_id'),
primary_key=True,
info=SYSTEM | SEARCHABLE)
return Column(
Integer,
ForeignKey(
'entity.id', use_alter=True, name='fk_inherited_entity_id'),
primary_key=True,
info=SYSTEM | SEARCHABLE)

@declared_attr
def __mapper_args__(cls):
Expand All @@ -148,9 +148,8 @@ class EntityQuery(db.Model.query_class):
def with_permission(self, permission, user=None):
security = current_app.services['security']
model = self._entity_zero().entity_zero.entity
expr = security.query_entity_with_permission(permission,
user,
Model=model)
expr = security.query_entity_with_permission(
permission, user, Model=model)
return self.filter(expr)


Expand Down Expand Up @@ -197,8 +196,8 @@ def __new__(mcs, classname, bases, d):
for permission, roles in default_permissions)
d['__default_permissions__'] = default_permissions

d['SLUG_SEPARATOR'] = text_type(d.get('SLUG_SEPARATOR',
Entity.SLUG_SEPARATOR))
d['SLUG_SEPARATOR'] = text_type(
d.get('SLUG_SEPARATOR', Entity.SLUG_SEPARATOR))

cls = BaseMeta.__new__(mcs, classname, bases, d)

Expand Down

0 comments on commit 026361d

Please sign in to comment.