Bonjour tout le monde,
Alors voila, je vous explique mon problème, tout d'abord je travailles avec python, django ET json sur un script qui cherche l'existence de deux fichiers contenu dans un dossier nommé "fixtures", si l'un d'eux (ou les deux, hein.. vue que c'est une boucle) est manquant, alors on lance le(s) script(s) associé(s) à ces deux fichiers, ici : generate_archetypescompetences.py et generate_archetypesracesattributes.py
Bien entendu, toutes les tables ne faisant pas appel à la methode "__check_if_files_exists(self)" sont seedées, et d'ailleurs, si les deux fichiers existent alors le script fonctionne....
Seulement voila, autant ces deux fichiers marchent quand lancés seuls (vue que je m'en servait avant mais j'en avais marre de devoir tout relancer à chaque fois que je voulais "seeder" ma base de donnée), autant là... tout s'écris dans un seul fichier.json ... évidement ca cause une erreur ... Et donc, j'aurais aimé savoir si vous pouviez m'aider.
Une petite aide serait sympathiquemerci
donc en gros, au lieu d'écrire dans ces deux fichiers j'ai :
Mes scripts :
script de seeding des fixtures:
Code python : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88 import os, platform, subprocess, os.path class Seed: """ Little class which allow to seed every fixtures in one time. And check if file created with script.py exist """ def __init__(self, *args): self.this_os = platform.system() self.those_files_names = [item for item in args] self.can_continue = True #if args list is empty then can_continue get "false". if not self.those_files_names: self.can_continue = False def __check_if_files_exists(self): """ check if file exist, if not : execute python script. """ can_be_used = True # get actual path actual_dir = os.getcwd() for file in self.those_files_names: # Check if file exist this_file = "generate_"+file+".py" if not os.path.isfile(actual_dir + os.path.sep + 'gestion' + os.path.sep + 'fixtures' + os.path.sep + file +".json"): try: # change directory and execute python script print("Raison de l'exception : Fichier inexistant...") print("Création du fichier...") os.chdir('gestion'+os.path.sep+'fixtures') subprocess.check_call(['python', this_file], stdin=None, stdout=None, stderr=None, shell=False) subprocess.call('exit=1', shell=True) except OSError as err: # set can_be_used on false ; can_be_used = False print("Raison: {}".format(err)) os.chdir(actual_dir) return can_be_used def seed_them_all(self): """ seed everything needed. """ if self.can_continue: subprocess.call(['python', 'manage.py', 'loaddata', 'users.json', 'corporations.json', 'guilds.json', 'races.json', 'attributes.json', 'competences.json', 'archetypes.json', 'sfx.json', 'sfxcategory.json', 'weaponscategory.json', 'weapons.json', 'ammunition', 'weaponsammunition.json', 'armors.json', 'armorscategory', 'decks.json', 'augmentations.json', 'augmentationscategory.json', 'spells.json', 'spellscategory.json', 'spellsdamagescategory.json', 'itemscategory.json' ]) if self.__check_if_files_exists(): subprocess.call(['python', 'manage.py', 'loaddata', 'archetypescompetences.json', 'archetypesracesattributes.json', ]) else: return "Aucuns arguments trouvés lors de l'instanciation de la classe." mySeed = Seed('archetypescompetences', 'archetypesracesattributes') mySeed.seed_them_all()
generation_archetypescompetences.py:
Code python : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150 import mysql.connector import json class GenerateNewJsonFile: """ Simple JSON file generation class """ def __init__(self, user, password, host, db): self.user = user self.password = password self.host = host self.db = db @staticmethod def __check(self): try: connection = mysql.connector.connect( user=self.user, password=self.password, host=self.host, database=self.db ) return True except mysql.connector.Error as err: raise Exception("Raison de l'erreur: {}".format(err)) else: connection.close() def _get_data(self): """ Put some data in list. """ if self.__check: connection = mysql.connector.connect( user=self.user, password=self.password, host=self.host, database=self.db, ) cursor_archetypes = connection.cursor(buffered=True) cursor_competences = connection.cursor(buffered=True) try: query_archetypes = "SELECT id FROM gestion_archetypes" query_competences = "SELECT id FROM gestion_competences" cursor_archetypes.execute(query_archetypes) cursor_competences.execute(query_competences) competences = [comp for comp in cursor_competences] archetypes = [arch for arch in cursor_archetypes] except mysql.connector.Error as err: raise Exception("Raison de l'erreur: {}".format(err)) except Exception as e: raise Exception("Raison de l'erreur: {}".format(e)) finally: cursor_archetypes.close() cursor_competences.close() archetypes_and_competences = [] for comp in range(1, len(competences)+1): for arch in range(1, len(archetypes)+1): if arch == 1 and comp == 1 or comp == 2: value = 2 elif arch == 1 and comp == 3 or comp == 10: value = 1 elif arch == 2 and comp == 6 or comp == 7: value = 2 elif arch == 2 and comp == 10 or comp == 12: value = 1 elif arch == 3 and comp == 23 or comp == 22: value = 2 elif arch == 3 and comp == 6 or comp == 9: value = 1 elif arch == 4 and comp == 25 or comp == 15: value = 2 elif arch == 4 and comp == 1 or comp == 5: value = 1 elif arch == 5 and comp == 16 or comp == 17: value = 2 elif arch == 5 and comp == 18 or comp == 1: value = 1 elif arch == 6 and comp == 21 or comp == 19: value = 2 elif arch == 6 and comp == 20 or comp == 10: value = 1 elif arch == 7 and comp == 28 or comp == 29: value = 2 elif arch == 7 and comp == 27 or comp == 3: value = 1 elif arch == 8 and comp == 1 or comp == 12: value = 2 elif arch == 8 and comp == 10 or comp == 13: value = 1 elif arch == 9 and comp == 26 or comp == 5: value = 2 elif arch == 9 and comp == 10 or comp == 3: value = 1 elif arch == 10 and comp == 8 or comp == 9: value = 2 elif arch == 10 and comp == 6 or comp == 10: value = 1 elif arch == 11 and comp == 35 or comp == 36: value = 2 elif arch == 11 and comp == 1 or comp == 39: value = 1 else: value = 0 archetypes_and_competences.append({"id_competences": comp, "id_archetypes": arch, "value": value}) return archetypes_and_competences def from_list_to_json(self): """ open new file with .json extension and write data in. """ data = self._get_data() try: with open('archetypescompetences.json', 'a') as file: file.write('[') i=0 for d in data: file.write(json.dumps({ 'model': 'gestion.archetypescompetences', 'pk': None, 'fields': { 'id_competences': d["id_competences"], 'id_archetypes': d["id_archetypes"], 'value': d["value"], "created_at": "2019-01-11T11:44:31Z", "updated_at": "2019-01-11T11:44:31Z", "deleted_at": None } })) i += 1 if i == len(data): file.write('\n') else: file.write(',\n') else: file.write(']') except Exception as e: return e t = GenerateNewJsonFile("xxxx", "xxxx", "xxxx", "xxxx") t.from_list_to_json()
Partager