-
Notifications
You must be signed in to change notification settings - Fork 0
/
initialize.py
148 lines (130 loc) · 4.08 KB
/
initialize.py
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
from django.utils.crypto import get_random_string
import subprocess
from shutil import copyfile
import os
def request_input(question, options):
print(f'{question} ({", ".join([option for option in options])})')
while True:
r = input()
if r not in options:
print('Digite uma resposta válida!')
else:
return r
def ask_user(name, title, required, default=None, next_questions={}):
print()
print(f'{title} {"(Opcional)" if not required else ""}')
if list(next_questions.keys()) != []:
print(f'Opções: {list(next_questions.keys())}')
if default is not None:
default = str(default)
print(f'Não digite nada para escolher "{default}"')
answer = input(f'{name}: ')
if required and next_questions != {}:
while answer not in list(next_questions.keys()):
print(f'{answer} deve estar em {list(next_questions.keys())}!')
answer = input(f'{name}: ')
for question in next_questions[answer]:
process_question(question)
if required and answer == '':
if default is not None:
answer = default
while answer == '':
print(f'{name} é obrigatório!')
answer = input(f'{name}: ')
return answer
def process_question(question):
name = question['name']
title = question['title']
default = question.get('default', None)
ask = question.get('ask', True)
required = question.get('required', False)
next_questions = question.get('next', {})
value = default
if ask:
value = ask_user(name, title, required, default, next_questions)
env_string = f'\n# {title}\n{name}={value}\n'
with open(".env-temp", "a") as file:
file.write(env_string)
def process_questions(questions):
with open(".env-temp", "w+") as file:
file.write('# Environment Variables\n')
for question in questions:
process_question(question)
env = [
{
'name': 'DEBUG',
'title': 'Ativar modo de debug',
'default': True,
'ask': False
},
{
'name': 'SECRET_KEY',
'title': 'Chave privada de encriptação usada pelo Django',
'default': get_random_string(32),
'ask': False,
},
{
'name': 'EMAIL_ACCOUNT',
'title': 'Endereço de email para envio de logs de erro',
'ask': True,
'required': True
},
{
'name': 'EMAIL_PASSWORD',
'title': 'Senha do endereço de email',
'ask': True,
'required': True
},
{
'name': 'ADMIN_ACCOUNT',
'title': 'Conta de admin para receber logs de erro',
'default': '[email protected]',
'ask': True,
'required': True
},
{
'name': 'SHOW_TOOLBAR_CALLBACK',
'title': 'Mostrar toolbar de debug do Django',
'default': True,
'ask': False,
'required': True
},
{
'name': 'DATABASE_URL',
'title': 'URI para seu banco de dados Postgres',
'default': 'postgresql://localhost/',
'ask': False,
'required': True
}
]
def revert_changes():
print('\n')
print('Revertendo alterações...')
os.remove('.env-temp')
def process_env():
try:
process_questions(env)
r = request_input('Salvar alterações?', ['s', 'n'])
if r == 's':
print('Salvando...')
copyfile('.env-temp', '.env')
os.remove('.env-temp')
else:
revert_changes()
except KeyboardInterrupt:
revert_changes()
def process_db():
r = request_input('Migrar banco de dados?', ['s', 'n'])
if r == 's':
print('Migrando banco de dados...')
print(subprocess.check_output(['python', 'manage.py', 'migrate']).decode("utf-8"))
if __name__ == "__main__":
ask_questions = True
if os.path.isfile('.env'):
print('Arquivo de variáveis de ambiente já existe')
r = request_input('Deseja substituí-lo?', ['s', 'n'])
if r == 'n':
ask_questions = False
if ask_questions:
process_env()
process_db()