core -- Apply black + isort to all files

This commit is contained in:
Aurélien Delobelle 2018-10-06 12:35:49 +02:00
parent 104e71dcf6
commit fdd2b35289
196 changed files with 10727 additions and 8365 deletions

View file

@ -2,8 +2,8 @@
Un mixin à utiliser avec BaseCommand pour charger des objets depuis un json
"""
import os
import json
import os
from django.core.management.base import BaseCommand
@ -13,15 +13,14 @@ class MyBaseCommand(BaseCommand):
Ajoute une méthode ``from_json`` qui charge des objets à partir d'un json.
"""
def from_json(self, filename, data_dir, klass,
callback=lambda obj: obj):
def from_json(self, filename, data_dir, klass, callback=lambda obj: obj):
"""
Charge les objets contenus dans le fichier json référencé par
``filename`` dans la base de donnée. La fonction callback est appelées
sur chaque objet avant enregistrement.
"""
self.stdout.write("Chargement de {:s}".format(filename))
with open(os.path.join(data_dir, filename), 'r') as file:
with open(os.path.join(data_dir, filename), "r") as file:
descriptions = json.load(file)
objects = []
nb_new = 0
@ -36,6 +35,7 @@ class MyBaseCommand(BaseCommand):
objects.append(obj)
nb_new += 1
self.stdout.write("- {:d} objets créés".format(nb_new))
self.stdout.write("- {:d} objets gardés en l'état"
.format(len(objects)-nb_new))
self.stdout.write(
"- {:d} objets gardés en l'état".format(len(objects) - nb_new)
)
return objects

View file

@ -15,13 +15,14 @@ from django.core.management import call_command
from gestioncof.management.base import MyBaseCommand
from gestioncof.petits_cours_models import (
PetitCoursAbility, PetitCoursSubject, LEVELS_CHOICES,
PetitCoursAttributionCounter
LEVELS_CHOICES,
PetitCoursAbility,
PetitCoursAttributionCounter,
PetitCoursSubject,
)
# Où sont stockés les fichiers json
DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)),
'data')
DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data")
class Command(MyBaseCommand):
@ -32,11 +33,11 @@ class Command(MyBaseCommand):
Permet de ne pas créer l'utilisateur "root".
"""
parser.add_argument(
'--no-root',
action='store_true',
dest='no-root',
"--no-root",
action="store_true",
dest="no-root",
default=False,
help='Ne crée pas l\'utilisateur "root"'
help='Ne crée pas l\'utilisateur "root"',
)
def handle(self, *args, **options):
@ -45,24 +46,25 @@ class Command(MyBaseCommand):
# ---
# Gaulois
gaulois = self.from_json('gaulois.json', DATA_DIR, User)
gaulois = self.from_json("gaulois.json", DATA_DIR, User)
for user in gaulois:
user.profile.is_cof = True
user.profile.save()
# Romains
self.from_json('romains.json', DATA_DIR, User)
self.from_json("romains.json", DATA_DIR, User)
# Root
no_root = options.get('no-root', False)
no_root = options.get("no-root", False)
if not no_root:
self.stdout.write("Création de l'utilisateur root")
root, _ = User.objects.get_or_create(
username='root',
first_name='super',
last_name='user',
email='root@localhost')
root.set_password('root')
username="root",
first_name="super",
last_name="user",
email="root@localhost",
)
root.set_password("root")
root.is_staff = True
root.is_superuser = True
root.profile.is_cof = True
@ -87,18 +89,17 @@ class Command(MyBaseCommand):
# L'utilisateur est compétent dans une matière
subject = random.choice(subjects)
if not PetitCoursAbility.objects.filter(
user=user,
matiere=subject).exists():
user=user, matiere=subject
).exists():
PetitCoursAbility.objects.create(
user=user,
matiere=subject,
niveau=random.choice(levels),
agrege=bool(random.randint(0, 1))
agrege=bool(random.randint(0, 1)),
)
# On initialise son compteur d'attributions
PetitCoursAttributionCounter.objects.get_or_create(
user=user,
matiere=subject
user=user, matiere=subject
)
self.stdout.write("- {:d} inscriptions".format(nb_of_teachers))
@ -106,10 +107,10 @@ class Command(MyBaseCommand):
# Le BdA
# ---
call_command('loadbdadevdata')
call_command("loadbdadevdata")
# ---
# La K-Fêt
# ---
call_command('loadkfetdevdata')
call_command("loadkfetdevdata")

View file

@ -4,11 +4,10 @@ Import des mails de GestioCOF dans la base de donnée
import json
import os
from custommail.models import Type, CustomMail, Variable
from django.core.management.base import BaseCommand
from custommail.models import CustomMail, Type, Variable
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand
DATA_LOCATION = os.path.join(os.path.dirname(__file__), "..", "data", "custommail.json")
@ -19,15 +18,15 @@ def dummy_log(__):
# XXX. this should probably be in the custommail package
def load_from_file(log=dummy_log, verbosity=1):
with open(DATA_LOCATION, 'r') as jsonfile:
with open(DATA_LOCATION, "r") as jsonfile:
mail_data = json.load(jsonfile)
# On se souvient à quel objet correspond quel pk du json
assoc = {'types': {}, 'mails': {}}
status = {'synced': 0, 'unchanged': 0}
assoc = {"types": {}, "mails": {}}
status = {"synced": 0, "unchanged": 0}
for obj in mail_data:
fields = obj['fields']
fields = obj["fields"]
# Pour les trois types d'objets :
# - On récupère les objets référencés par les clefs étrangères
@ -36,58 +35,55 @@ def load_from_file(log=dummy_log, verbosity=1):
# plus haut
# Variable types
if obj['model'] == 'custommail.variabletype':
fields['inner1'] = assoc['types'].get(fields['inner1'])
fields['inner2'] = assoc['types'].get(fields['inner2'])
if fields['kind'] == 'model':
fields['content_type'] = (
ContentType.objects
.get_by_natural_key(*fields['content_type'])
if obj["model"] == "custommail.variabletype":
fields["inner1"] = assoc["types"].get(fields["inner1"])
fields["inner2"] = assoc["types"].get(fields["inner2"])
if fields["kind"] == "model":
fields["content_type"] = ContentType.objects.get_by_natural_key(
*fields["content_type"]
)
var_type, _ = Type.objects.get_or_create(**fields)
assoc['types'][obj['pk']] = var_type
assoc["types"][obj["pk"]] = var_type
# Custom mails
if obj['model'] == 'custommail.custommail':
if obj["model"] == "custommail.custommail":
mail = None
try:
mail = CustomMail.objects.get(shortname=fields['shortname'])
status['unchanged'] += 1
mail = CustomMail.objects.get(shortname=fields["shortname"])
status["unchanged"] += 1
except CustomMail.DoesNotExist:
mail = CustomMail.objects.create(**fields)
status['synced'] += 1
status["synced"] += 1
if verbosity:
log('SYNCED {:s}'.format(fields['shortname']))
assoc['mails'][obj['pk']] = mail
log("SYNCED {:s}".format(fields["shortname"]))
assoc["mails"][obj["pk"]] = mail
# Variables
if obj['model'] == 'custommail.custommailvariable':
fields['custommail'] = assoc['mails'].get(fields['custommail'])
fields['type'] = assoc['types'].get(fields['type'])
if obj["model"] == "custommail.custommailvariable":
fields["custommail"] = assoc["mails"].get(fields["custommail"])
fields["type"] = assoc["types"].get(fields["type"])
try:
Variable.objects.get(
custommail=fields['custommail'],
name=fields['name']
custommail=fields["custommail"], name=fields["name"]
)
except Variable.DoesNotExist:
Variable.objects.create(**fields)
if verbosity:
log(
'{synced:d} mails synchronized {unchanged:d} unchanged'
.format(**status)
)
log("{synced:d} mails synchronized {unchanged:d} unchanged".format(**status))
class Command(BaseCommand):
help = ("Va chercher les données mails de GestioCOF stocké au format json "
"dans /gestioncof/management/data/custommails.json. Le format des "
"données est celui donné par la commande :"
" `python manage.py dumpdata custommail --natural-foreign` "
"La bonne façon de mettre à jour ce fichier est donc de le "
"charger à l'aide de syncmails, le faire les modifications à "
"l'aide de l'interface administration et/ou du shell puis de le "
"remplacer par le nouveau résultat de la commande précédente.")
help = (
"Va chercher les données mails de GestioCOF stocké au format json "
"dans /gestioncof/management/data/custommails.json. Le format des "
"données est celui donné par la commande :"
" `python manage.py dumpdata custommail --natural-foreign` "
"La bonne façon de mettre à jour ce fichier est donc de le "
"charger à l'aide de syncmails, le faire les modifications à "
"l'aide de l'interface administration et/ou du shell puis de le "
"remplacer par le nouveau résultat de la commande précédente."
)
def handle(self, *args, **options):
load_from_file(log=self.stdout.write)