Browse Source

feat(build/data): permet de lancer un script dans le contexte django

le script integre un systeme de transaction permettant
de tester les modifications de donnees avant de les commiter en base
pull/76/head
Vincent Adolphe 3 years ago committed by Vincent
parent
commit
83326b5ff9
  1. 69
      runscript.py

69
runscript.py

@ -1,25 +1,72 @@ @@ -1,25 +1,72 @@
#! /usr/bin/env python
import argparse
import os
import sys
from importlib import import_module
import django
from django.db import IntegrityError, transaction
from gaby.settings import DJANGO_SETTINGS_MODULE
DRY_RUN = True
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
# following from Python cookbook, #475186
def has_colours(stream):
if not hasattr(stream, "isatty"):
return False
if not stream.isatty():
return False # auto color only on TTYs
try:
import curses
curses.setupterm()
return curses.tigetnum("colors") > 2
except Exception:
# guess false in case of error
return False
HAS_COL = has_colours(sys.stdout)
def work_on_db():
" faire des choses dans la base de donnee, ne rien appliquer si DRY_RUN "
from gaby.references.models import Commune
print("nb objets: {0}".format(Commune.objects.count()))
def p_col(text, color=WHITE):
if HAS_COL:
f_str = "\x1b[1;{0:d}m".format(30 + color) + text + "\x1b[0m"
else:
f_str = text
sys.stdout.write(f_str)
# Entry point #
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', DJANGO_SETTINGS_MODULE)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="quick launch python script in django context"
)
parser.add_argument(
"py_script", help="python script, (as a python module, w/o .py)"
)
parser.add_argument(
"-c",
"--commit",
help="commit changes in database (default: rollback)",
action="store_true",
default=False,
)
args = parser.parse_args()
os.environ.setdefault("DJANGO_SETTINGS_MODULE", DJANGO_SETTINGS_MODULE)
django.setup()
with transaction.atomic():
work_on_db()
if DRY_RUN:
raise IntegrityError('Work In Progress: Dry run')
try:
with transaction.atomic():
import_module(args.py_script)
if not args.commit:
raise IntegrityError("dry_run")
except IntegrityError as err:
yolo = err
if "dry_run" not in err.args:
raise
else:
p_col("# DRY RUN - changes in database were rollbacked #\n", GREEN)
else:
p_col("# REAL RUN - changes in database were committed #\n", YELLOW)

Loading…
Cancel
Save
Map all the world