Commit c4a104b3 authored by klafyvel's avatar klafyvel Committed by chirac

I like my black.

Just ran black on the whoe repository. Fix #210.
parent 2460a7d2
Pipeline #2301 passed with stage
in 3 minutes and 19 seconds
......@@ -40,14 +40,14 @@ def _create_api_permission():
"""
api_content_type, created = ContentType.objects.get_or_create(
app_label=settings.API_CONTENT_TYPE_APP_LABEL,
model=settings.API_CONTENT_TYPE_MODEL
model=settings.API_CONTENT_TYPE_MODEL,
)
if created:
api_content_type.save()
api_permission, created = Permission.objects.get_or_create(
name=settings.API_PERMISSION_NAME,
content_type=api_content_type,
codename=settings.API_PERMISSION_CODENAME
codename=settings.API_PERMISSION_CODENAME,
)
if created:
api_permission.save()
......@@ -67,10 +67,13 @@ def can_view(user):
viewing is granted and msg is a message (can be None).
"""
kwargs = {
'app_label': settings.API_CONTENT_TYPE_APP_LABEL,
'codename': settings.API_PERMISSION_CODENAME
"app_label": settings.API_CONTENT_TYPE_APP_LABEL,
"codename": settings.API_PERMISSION_CODENAME,
}
permission = '%(app_label)s.%(codename)s' % kwargs
permission = "%(app_label)s.%(codename)s" % kwargs
can = user.has_perm(permission)
return can, None if can else _("You don't have the right to see this"
" application."), (permission,)
return (
can,
None if can else _("You don't have the right to see this" " application."),
(permission,),
)
......@@ -41,9 +41,7 @@ class ExpiringTokenAuthentication(TokenAuthentication):
user, token = base.authenticate_credentials(key)
# Check that the genration time of the token is not too old
token_duration = datetime.timedelta(
seconds=settings.API_TOKEN_DURATION
)
token_duration = datetime.timedelta(seconds=settings.API_TOKEN_DURATION)
utc_now = datetime.datetime.now(datetime.timezone.utc)
if token.created < utc_now - token_duration:
raise exceptions.AuthenticationFailed(_("The token has expired."))
......
......@@ -38,8 +38,9 @@ class PageSizedPagination(pagination.PageNumberPagination):
max_page_size: The maximum number of results a page can output no
matter what is requested.
"""
page_size_query_param = 'page_size'
all_pages_strings = ('all',)
page_size_query_param = "page_size"
all_pages_strings = ("all",)
max_page_size = 10000
def get_page_size(self, request):
......
......@@ -55,17 +55,21 @@ def _get_param_in_view(view, param_name):
AssertionError: None of the getter function or the attribute are
defined in the view.
"""
assert hasattr(view, 'get_' + param_name) \
or getattr(view, param_name, None) is not None, (
'cannot apply {} on a view that does not set '
'`.{}` or have a `.get_{}()` method.'
).format(self.__class__.__name__, param_name, param_name)
if hasattr(view, 'get_' + param_name):
param = getattr(view, 'get_' + param_name)()
assert param is not None, (
'{}.get_{}() returned None'
).format(view.__class__.__name__, param_name)
assert (
hasattr(view, "get_" + param_name)
or getattr(view, param_name, None) is not None
), (
"cannot apply {} on a view that does not set "
"`.{}` or have a `.get_{}()` method."
).format(
self.__class__.__name__, param_name, param_name
)
if hasattr(view, "get_" + param_name):
param = getattr(view, "get_" + param_name)()
assert param is not None, ("{}.get_{}() returned None").format(
view.__class__.__name__, param_name
)
return param
return getattr(view, param_name)
......@@ -97,7 +101,7 @@ class ACLPermission(permissions.BasePermission):
rest_framework.exception.MethodNotAllowed: The requested method
is not allowed for this view.
"""
perms_map = _get_param_in_view(view, 'perms_map')
perms_map = _get_param_in_view(view, "perms_map")
if method not in perms_map:
raise exceptions.MethodNotAllowed(method)
......@@ -123,7 +127,7 @@ class ACLPermission(permissions.BasePermission):
"""
# Workaround to ensure ACLPermissions are not applied
# to the root view when using DefaultRouter.
if getattr(view, '_ignore_model_permissions', False):
if getattr(view, "_ignore_model_permissions", False):
return True
if not request.user or not request.user.is_authenticated:
......@@ -148,22 +152,22 @@ class AutodetectACLPermission(permissions.BasePermission):
"""
perms_map = {
'GET': [can_see_api, lambda model: model.can_view_all],
'OPTIONS': [can_see_api, lambda model: model.can_view_all],
'HEAD': [can_see_api, lambda model: model.can_view_all],
'POST': [can_see_api, lambda model: model.can_create],
'PUT': [], # No restrictions, apply to objects
'PATCH': [], # No restrictions, apply to objects
'DELETE': [], # No restrictions, apply to objects
"GET": [can_see_api, lambda model: model.can_view_all],
"OPTIONS": [can_see_api, lambda model: model.can_view_all],
"HEAD": [can_see_api, lambda model: model.can_view_all],
"POST": [can_see_api, lambda model: model.can_create],
"PUT": [], # No restrictions, apply to objects
"PATCH": [], # No restrictions, apply to objects
"DELETE": [], # No restrictions, apply to objects
}
perms_obj_map = {
'GET': [can_see_api, lambda obj: obj.can_view],
'OPTIONS': [can_see_api, lambda obj: obj.can_view],
'HEAD': [can_see_api, lambda obj: obj.can_view],
'POST': [], # No restrictions, apply to models
'PUT': [can_see_api, lambda obj: obj.can_edit],
'PATCH': [can_see_api, lambda obj: obj.can_edit],
'DELETE': [can_see_api, lambda obj: obj.can_delete],
"GET": [can_see_api, lambda obj: obj.can_view],
"OPTIONS": [can_see_api, lambda obj: obj.can_view],
"HEAD": [can_see_api, lambda obj: obj.can_view],
"POST": [], # No restrictions, apply to models
"PUT": [can_see_api, lambda obj: obj.can_edit],
"PATCH": [can_see_api, lambda obj: obj.can_edit],
"DELETE": [can_see_api, lambda obj: obj.can_delete],
}
def get_required_permissions(self, method, model):
......@@ -210,7 +214,7 @@ class AutodetectACLPermission(permissions.BasePermission):
@staticmethod
def _queryset(view):
return _get_param_in_view(view, 'queryset')
return _get_param_in_view(view, "queryset")
def has_permission(self, request, view):
"""Check that the user has the model-based permissions to perform
......@@ -232,7 +236,7 @@ class AutodetectACLPermission(permissions.BasePermission):
"""
# Workaround to ensure ACLPermissions are not applied
# to the root view when using DefaultRouter.
if getattr(view, '_ignore_model_permissions', False):
if getattr(view, "_ignore_model_permissions", False):
return True
if not request.user or not request.user.is_authenticated:
......@@ -274,7 +278,7 @@ class AutodetectACLPermission(permissions.BasePermission):
# to make another lookup.
raise Http404
read_perms = self.get_required_object_permissions('GET', obj)
read_perms = self.get_required_object_permissions("GET", obj)
if not read_perms(request.user)[0]:
raise Http404
......
......@@ -74,7 +74,7 @@ class AllViewsRouter(DefaultRouter):
Returns:
The name to use for this route.
"""
return pattern.split('/')[-1]
return pattern.split("/")[-1]
def get_api_root_view(self, schema_urls=None, api_urls=None):
"""Create a class-based view to use as the API root.
......@@ -102,12 +102,10 @@ class AllViewsRouter(DefaultRouter):
if schema_urls and self.schema_title:
view_renderers += list(self.schema_renderers)
schema_generator = SchemaGenerator(
title=self.schema_title,
patterns=schema_urls
title=self.schema_title, patterns=schema_urls
)
schema_media_types = [
renderer.media_type
for renderer in self.schema_renderers
renderer.media_type for renderer in self.schema_renderers
]
class APIRoot(views.APIView):
......@@ -128,14 +126,14 @@ class AllViewsRouter(DefaultRouter):
namespace = request.resolver_match.namespace
for key, url_name in api_root_dict.items():
if namespace:
url_name = namespace + ':' + url_name
url_name = namespace + ":" + url_name
try:
ret[key] = reverse(
url_name,
args=args,
kwargs=kwargs,
request=request,
format=kwargs.get('format', None)
format=kwargs.get("format", None),
)
except NoReverseMatch:
# Don't bail out if eg. no list routes exist, only detail routes.
......
This diff is collapsed.
......@@ -24,28 +24,24 @@
# RestFramework config for API
REST_FRAMEWORK = {
'URL_FIELD_NAME': 'api_url',
'DEFAULT_AUTHENTICATION_CLASSES': (
'api.authentication.ExpiringTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
"URL_FIELD_NAME": "api_url",
"DEFAULT_AUTHENTICATION_CLASSES": (
"api.authentication.ExpiringTokenAuthentication",
"rest_framework.authentication.SessionAuthentication",
),
'DEFAULT_PERMISSION_CLASSES': (
'api.permissions.AutodetectACLPermission',
),
'DEFAULT_PAGINATION_CLASS': 'api.pagination.PageSizedPagination',
'PAGE_SIZE': 100
"DEFAULT_PERMISSION_CLASSES": ("api.permissions.AutodetectACLPermission",),
"DEFAULT_PAGINATION_CLASS": "api.pagination.PageSizedPagination",
"PAGE_SIZE": 100,
}
# API permission settings
API_CONTENT_TYPE_APP_LABEL = 'api'
API_CONTENT_TYPE_MODEL = 'api'
API_PERMISSION_NAME = 'Can use the API'
API_PERMISSION_CODENAME = 'use_api'
API_CONTENT_TYPE_APP_LABEL = "api"
API_CONTENT_TYPE_MODEL = "api"
API_PERMISSION_NAME = "Can use the API"
API_PERMISSION_CODENAME = "use_api"
# Activate token authentication
API_APPS = (
'rest_framework.authtoken',
)
API_APPS = ("rest_framework.authtoken",)
# The expiration time for an authentication token
API_TOKEN_DURATION = 86400 # 24 hours
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -38,13 +38,12 @@ def can_view(user):
A couple (allowed, msg) where allowed is a boolean which is True if
viewing is granted and msg is a message (can be None).
"""
can = user.has_module_perms('cotisations')
can = user.has_module_perms("cotisations")
if can:
return can, None, ('cotisations',)
return can, None, ("cotisations",)
else:
return (
can,
_("You don't have the right to view this application."),
('cotisations',)
("cotisations",),
)
......@@ -35,42 +35,50 @@ from .models import CustomInvoice, CostEstimate
class FactureAdmin(VersionAdmin):
"""Class admin d'une facture, tous les champs"""
pass
class CostEstimateAdmin(VersionAdmin):
"""Admin class for cost estimates."""
pass
class CustomInvoiceAdmin(VersionAdmin):
"""Admin class for custom invoices."""
pass
class VenteAdmin(VersionAdmin):
"""Class admin d'une vente, tous les champs (facture related)"""
pass
class ArticleAdmin(VersionAdmin):
"""Class admin d'un article en vente"""
pass
class BanqueAdmin(VersionAdmin):
"""Class admin de la liste des banques (facture related)"""
pass
class PaiementAdmin(VersionAdmin):
"""Class admin d'un moyen de paiement (facture related"""
pass
class CotisationAdmin(VersionAdmin):
"""Class admin d'une cotisation (date de debut et de fin),
Vente related"""
pass
......
This diff is collapsed.
......@@ -29,54 +29,100 @@ import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0005_auto_20160702_0006'),
]
dependencies = [("users", "0005_auto_20160702_0006")]
operations = [
migrations.CreateModel(
name='Article',
name="Article",
fields=[
('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)),
('name', models.CharField(max_length=255)),
('prix', models.DecimalField(decimal_places=2, max_digits=5)),
(
"id",
models.AutoField(
verbose_name="ID",
auto_created=True,
primary_key=True,
serialize=False,
),
),
("name", models.CharField(max_length=255)),
("prix", models.DecimalField(decimal_places=2, max_digits=5)),
],
),
migrations.CreateModel(
name='Banque',
name="Banque",
fields=[
('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)),
('name', models.CharField(max_length=255)),
(
"id",
models.AutoField(
verbose_name="ID",
auto_created=True,
primary_key=True,
serialize=False,
),
),
("name", models.CharField(max_length=255)),
],
),
migrations.CreateModel(
name='Facture',
name="Facture",
fields=[
('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)),
('cheque', models.CharField(max_length=255)),
('number', models.IntegerField()),
('date', models.DateTimeField(auto_now_add=True)),
('name', models.CharField(max_length=255)),
('prix', models.DecimalField(decimal_places=2, max_digits=5)),
('article', models.ForeignKey(to='cotisations.Article', on_delete=django.db.models.deletion.PROTECT)),
('banque', models.ForeignKey(to='cotisations.Banque', on_delete=django.db.models.deletion.PROTECT)),
(
"id",
models.AutoField(
verbose_name="ID",
auto_created=True,
primary_key=True,
serialize=False,
),
),
("cheque", models.CharField(max_length=255)),
("number", models.IntegerField()),
("date", models.DateTimeField(auto_now_add=True)),
("name", models.CharField(max_length=255)),
("prix", models.DecimalField(decimal_places=2, max_digits=5)),
(
"article",
models.ForeignKey(
to="cotisations.Article",
on_delete=django.db.models.deletion.PROTECT,
),
),
(
"banque",
models.ForeignKey(
to="cotisations.Banque",
on_delete=django.db.models.deletion.PROTECT,
),
),
],
),
migrations.CreateModel(
name='Paiement',
name="Paiement",
fields=[
('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)),
('moyen', models.CharField(max_length=255)),
(
"id",
models.AutoField(
verbose_name="ID",
auto_created=True,
primary_key=True,
serialize=False,
),
),
("moyen", models.CharField(max_length=255)),
],
),
migrations.AddField(
model_name='facture',
name='paiement',
field=models.ForeignKey(to='cotisations.Paiement', on_delete=django.db.models.deletion.PROTECT),
model_name="facture",
name="paiement",
field=models.ForeignKey(
to="cotisations.Paiement", on_delete=django.db.models.deletion.PROTECT
),
),
migrations.AddField(
model_name='facture',
name='user',
field=models.ForeignKey(to='users.User', on_delete=django.db.models.deletion.PROTECT),
model_name="facture",
name="user",
field=models.ForeignKey(
to="users.User", on_delete=django.db.models.deletion.PROTECT
),
),
]
......@@ -28,13 +28,6 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cotisations', '0001_initial'),
]