-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
321 lines (261 loc) · 10.3 KB
/
main.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import base64
import json
import logging
import gitlab
import requests
from flask import Flask, Response, jsonify, request, session
from flask_cors import CORS
import pymongo as pm
gl = gitlab.Gitlab("http://git.dev.qianmi.com",
private_token="wbFxyiyeM49bPUo7w8HB")
# 连接数据库
client = pm.MongoClient('localhost', 32768)
db = client.hermes
tb_user = db.user
tb_template = db.template
# 配置中心的ip地址
config_ip = 'http://localhost:7777'
# ---------------------------------------------设置cors和返回值为json等--------------------------------------
class RestResponse(Response):
@classmethod
def force_type(cls, response, environ=None):
if isinstance(response, (list, dict)):
response = jsonify(response)
return super(Response, cls).force_type(response, environ)
app = Flask(__name__)
app.response_class = RestResponse
CORS(app, resources={r"/*": {"origins": "*"}})
# ---------------------------------------------注册模块----------------------------------------------------
@app.route("/user/signUp/post", methods=['POST'])
def post_user():
json_req = request.get_json()
username = json_req['username']
password = json_req['password']
private_token = json_req['private_token']
# 插入数据库中
tb_user.save({'username': username, 'password': password,
'privateToken': private_token})
return success_res("注册成功")
# ---------------------------------------------登陆模块----------------------------------------------------
@app.route("/user/signIn/post", methods=['post'])
def get_user():
json_req = request.get_json()
username = json_req['username']
password = json_req['password']
cur_user = tb_user.find_one({'username': username})
print(cur_user["password"] is password)
print(cur_user["password"])
print(password)
if cur_user is not None and cur_user['password'] == password:
session['private_token'] = cur_user['privateToken']
return success_res("success")
else:
return fail_res("用户不存在或这密码错误")
# ---------------------------------------------配置模板模块------------------------------------------------------
# 数据库设计: 关于某个领域的配置吧 与一个独立的名称 name, 然后里面是一个数组:数组里面保存着字典{key:'', value:''}
# 新建模板
@app.route("/properties/template/post", methods=["post"])
def post_properties_template():
json_req = request.get_json()
name = json_req['name']
properties = json_req['properties']
tb_template.save({
'name': name,
'properties': properties
})
return success_res("新建模板成功")
# 按照名称查找模板
@app.route("/properties/template/<name>/get", methods=["get"])
def get_properties_template(name):
print("姓名是: %s" % name)
res = tb_template.find_one({
'name': name
})
return success_res({
"name": res['name'],
"properties": res['properties']
})
# 查询所有的模板
@app.route("/propertes/templates/get", methods=["get"])
def get_properties_templates():
res = tb_template.find()
res_list = []
for r in res:
res_list.append({
"name": r["name"],
"properties": r["properties"]
})
return success_res(res_list)
@app.route("/properties/template/<id>/update", methods=["post"])
def update_properties_template(id):
json_req = request.get_json()
name = json_req["name"]
properties = json_req["properties"]
res = tb_template.find_one({"_id": id})
if res is None:
return fail_res("不存在此模板")
tb_template.update({
"_id": res["_id"],
"name": name,
"properties": properties
})
return success_res("success")
@app.route("/properties/template/<id>/delete")
def delete_properties_template(id):
tb_template.delete_one({
"_id": id
})
return success_res("success")
# ---------------------------------------------修改gitlab的模式------------------------------------------------
# 获取项目环境
# 环境的优先级 global application < product application < global application env < product application env
@app.route('/project/<project>/profile/<profile>/branch/<branch>/get')
def get_file_by_id(project, profile, branch):
response = requests.get(config_ip + project + "/" + profile + "/" + branch)
properties = json.loads(response.text)
project_public_pro = {}
project_private_pro = {}
project_global_pro = {}
project_global_env_pro = {}
for config in properties['propertySources']:
temp = config['name'].split('/')
if temp[-2] != project:
# 全局共有配置
if temp[-1] == 'application.properties' or temp[-1] == 'application.yml':
for key, value in config['source'].items():
project_global_pro[key] = value
else:
# 该环境全局配置
for key, value in config['source'].items():
project_global_env_pro[key] = value
else:
# 项目共有配置
if temp[-1] == 'application.properties' or temp[-1] == 'application.yml':
for key, value in config['source'].items():
project_public_pro[key] = value
else:
# 该环境项目私有配置
for key, value in config['source'].items():
project_private_pro[key] = value
zip_dict = {**project_global_pro, **project_global_env_pro}
zip_dict = {**zip_dict, **project_public_pro}
zip_dict = {**zip_dict, **project_private_pro}
res_list = []
v1, v2, v3, v4 = '', '', '', ''
for key, value in zip_dict.items():
if key in project_global_pro.keys():
v1 = project_global_pro[key]
if key in project_global_env_pro.keys():
v2 = project_global_env_pro[key]
if key in project_public_pro.keys():
v3 = project_public_pro[key]
if key in project_private_pro.keys():
v4 = project_private_pro[key]
res_list.append({'key': key, 'global': v1,
'global_env': v2, 'project': v3, 'project_env': v4})
return success_res({
"res_list": res_list
})
# 修改项目中的公共配置
@app.route("/project/<project>/get", methods=["POST"])
def post_project_config(project):
json_req = request.get_json()
put_configurations(json_req, project + "/application.properties")
return success_res("success")
# 修改项目中环境的配置
@app.route("/project/<project>/profile/<profile>/put", methods=["POST"])
def post_project_env_config(project, profile):
json_req = request.get_json()
put_configurations(json_req, project +
"/application-" + profile + ".properties")
return success_res("success")
# 修改全局的配置
@app.route("/global/put", methods=["POST"])
def post_global_config():
json_req = request.get_json()
put_configurations(json_req, "application.properties")
return success_res("success")
# 修改全局中环境的配置
@app.route("/global/profile/<profile>/put", methods=['POST'])
def post_global_env_config(profile):
json_req = request.get_json()
put_configurations(json_req, "application-" + profile + ".properties")
return success_res("success")
# 新增全局中的配置
@app.route("/global/post", methods=["POST"])
def add_global_config():
json_req = request.get_json()
post_configurations(json_req, "application.properties")
return success_res("success")
# 新增全局环境中的配置
@app.route("/global/profile/<profile>/post", methods=["POST"])
def add_global_env_config(profile):
json_req = request.get_json()
post_configurations(json_req, "application-" + profile + ".properties")
return success_res("success")
# 新增项目环境中的配置
@app.route("/project/<project>/profile/<profile>/post", methods=["POST"])
def add_project_env_config(project, profile):
json_req = request.get_json()
post_configurations(json_req, project +
"/application" + profile + ".properties")
return success_res("success")
# 新增项目中的配置
@app.route("/project/<project>/post", methods=["POST"])
def add_project_config(project):
json_req = request.get_json()
post_configurations(json_req, project + "/application.properties")
return success_res("success")
# 展示所有的项目
@app.route("/projects/get", methods=["GET"])
def get_projects():
repo = gl.projects.get('bm-life/spring-cloud-config-center')
projects = repo.repository_tree()
project_list = [pro['name'] for pro in projects if pro['type'] == 'tree']
return success_res(project_list)
# 成功返回的结果
def success_res(data, code=200):
return {
'code': code,
'data': data,
'message': 'success'
}
# 失败返回的结果
def fail_res(code=400, message='fail'):
return {
'code': code,
'message': message
}
# 获取远程的文件
def get_git_files(file_path):
project = gl.projects.get('bm-life/spring-cloud-config-center')
temp = project.files.get(file_path=file_path, ref="master")
file = base64.b64decode(temp.content)
str_config = file.decode('utf-8')
return temp, str_config.splitlines()
# update配置
def put_configurations(json_req, file_path):
file, config_list = get_git_files(file_path)
temp_list = []
for k, v in json_req.items():
for config in config_list:
temp = config.split("=")
if temp[0] == k:
temp_list.append(k + "=" + v)
else:
temp_list.append(config)
str_config = "\n".join(temp_list)
file.content = base64.b64encode(str.encode(str_config)).decode()
file.save(branch_name='master', commit_message=str(json_req.keys()))
# 新增配置
def post_configurations(json_req, file_path):
file, config_list = get_git_files(file_path)
for k, v in json_req:
config_list.append(k + "=" + v)
res = "\n".join(config_list)
file.content = base64.b64encode(str.encode(res)).decode()
file.save(branch_name='master', commit_message=str(json_req.keys()))
if __name__ == '__main__':
app.secret_key = "super secret key"
app.config["SESSION_TYPE"] = "filesystem"
app.run(debug=True, port=8080, host='0.0.0.0')