Wendong-Fan commited on
Commit
ae2d21b
·
1 Parent(s): 9bde235

update web app environment variable passing

Browse files
Files changed (3) hide show
  1. owl/app.py +104 -62
  2. owl/app_en.py +113 -63
  3. run_app.py +1 -1
owl/app.py CHANGED
@@ -148,33 +148,45 @@ def load_env_vars():
148
 
149
  # 加载.env文件中可能存在的其他环境变量
150
  if Path(".env").exists():
151
- with open(".env", "r", encoding="utf-8") as f:
152
- for line in f:
153
- line = line.strip()
154
- if line and not line.startswith("#") and "=" in line:
155
- key, value = line.split("=", 1)
156
- key = key.strip()
157
- value = value.strip().strip("\"'")
158
-
159
- # 检查是否是已知的环境变量
160
- known_var = False
161
- for group in ENV_GROUPS.values():
162
- if any(var["name"] == key for var in group):
163
- known_var = True
164
- break
165
-
166
- # 如果不是已知的环境变量,添加到自定义环境变量组
167
- if not known_var and key not in env_vars:
168
- ENV_GROUPS["自定义环境变量"].append(
169
- {
170
- "name": key,
171
- "label": key,
172
- "type": "text",
173
- "required": False,
174
- "help": "用户自定义环境变量",
175
- }
176
- )
177
- env_vars[key] = value
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
  return env_vars
180
 
@@ -186,33 +198,49 @@ def save_env_vars(env_vars):
186
  existing_content = {}
187
 
188
  if env_path.exists():
189
- with open(env_path, "r", encoding="utf-8") as f:
190
- for line in f:
191
- line = line.strip()
192
- if line and not line.startswith("#") and "=" in line:
193
- key, value = line.split("=", 1)
194
- existing_content[key.strip()] = value.strip()
 
 
 
 
 
 
195
 
196
  # 更新环境变量
197
  for key, value in env_vars.items():
198
- if value: # 只保存非空值
199
- # 确保值是字符串形式,并用引号包裹
200
  value = str(value) # 确保值是字符串
201
 
202
- # 先移除现有的引号(如果有)
203
- stripped_value = value.strip("\"'")
204
-
205
- # 用双引号包裹值,确保特殊字符被正确处理
206
- quoted_value = f'"{stripped_value}"'
207
- existing_content[key] = quoted_value
208
-
209
- # 同时更新当前进程的环境变量(使用未引用的值)
210
- os.environ[key] = stripped_value
 
 
 
 
 
 
211
 
212
  # 写入.env文件
213
- with open(env_path, "w", encoding="utf-8") as f:
214
- for key, value in existing_content.items():
215
- f.write(f"{key}={value}\n")
 
 
 
 
216
 
217
  return "✅ 环境变量已保存"
218
 
@@ -291,22 +319,36 @@ def delete_custom_env_var(name):
291
  # 从.env文件中删除该环境变量
292
  env_path = Path(".env")
293
  if env_path.exists():
294
- with open(env_path, "r", encoding="utf-8") as f:
295
- lines = f.readlines()
 
296
 
297
- with open(env_path, "w", encoding="utf-8") as f:
298
- for line in lines:
299
- # 更精确地匹配环境变量行
300
- # 检查是否为非注释行且包含变量名=
301
- line_stripped = line.strip()
302
- if line_stripped.startswith("#") or "=" not in line_stripped:
303
- f.write(line) # 保留注释行和不包含=的行
304
- continue
305
-
306
- # 提取变量名并检查是否与要删除的变量匹配
307
- var_name = line_stripped.split("=", 1)[0].strip()
308
- if var_name != name:
309
- f.write(line) # 保留不匹配的变量
 
 
 
 
 
 
 
 
 
 
 
 
 
310
 
311
  # 从当前进程的环境变量中删除
312
  if name in os.environ:
 
148
 
149
  # 加载.env文件中可能存在的其他环境变量
150
  if Path(".env").exists():
151
+ try:
152
+ with open(".env", "r", encoding="utf-8") as f:
153
+ for line in f:
154
+ line = line.strip()
155
+ if line and not line.startswith("#") and "=" in line:
156
+ try:
157
+ key, value = line.split("=", 1)
158
+ key = key.strip()
159
+ value = value.strip()
160
+
161
+ # 处理引号包裹的值
162
+ if (value.startswith('"') and value.endswith('"')) or (
163
+ value.startswith("'") and value.endswith("'")
164
+ ):
165
+ value = value[1:-1] # 移除首尾的引号
166
+
167
+ # 检查是否是已知的环境变量
168
+ known_var = False
169
+ for group in ENV_GROUPS.values():
170
+ if any(var["name"] == key for var in group):
171
+ known_var = True
172
+ break
173
+
174
+ # 如果不是已知的环境变量,添加到自定义环境变量组
175
+ if not known_var and key not in env_vars:
176
+ ENV_GROUPS["自定义环境变量"].append(
177
+ {
178
+ "name": key,
179
+ "label": key,
180
+ "type": "text",
181
+ "required": False,
182
+ "help": "用户自定义环境变量",
183
+ }
184
+ )
185
+ env_vars[key] = value
186
+ except Exception as e:
187
+ print(f"解析环境变量行时出错: {line}, 错误: {str(e)}")
188
+ except Exception as e:
189
+ print(f"加载.env文件时出错: {str(e)}")
190
 
191
  return env_vars
192
 
 
198
  existing_content = {}
199
 
200
  if env_path.exists():
201
+ try:
202
+ with open(env_path, "r", encoding="utf-8") as f:
203
+ for line in f:
204
+ line = line.strip()
205
+ if line and not line.startswith("#") and "=" in line:
206
+ try:
207
+ key, value = line.split("=", 1)
208
+ existing_content[key.strip()] = value.strip()
209
+ except Exception as e:
210
+ print(f"解析环境变量行时出错: {line}, 错误: {str(e)}")
211
+ except Exception as e:
212
+ print(f"读取.env文件时出错: {str(e)}")
213
 
214
  # 更新环境变量
215
  for key, value in env_vars.items():
216
+ if value is not None: # 允许空字符串值,但不允许None
217
+ # 确保值是字符串形式
218
  value = str(value) # 确保值是字符串
219
 
220
+ # 检查值是否已经被引号包裹
221
+ if (value.startswith('"') and value.endswith('"')) or (
222
+ value.startswith("'") and value.endswith("'")
223
+ ):
224
+ # 已经被引号包裹,保持原样
225
+ existing_content[key] = value
226
+ # 更新环境变量时移除引号
227
+ os.environ[key] = value[1:-1]
228
+ else:
229
+ # 没有被引号包裹,添加双引号
230
+ # 用双引号包裹值,确保特殊字符被正确处理
231
+ quoted_value = f'"{value}"'
232
+ existing_content[key] = quoted_value
233
+ # 同时更新当前进程的环境变量(使用未引用的值)
234
+ os.environ[key] = value
235
 
236
  # 写入.env文件
237
+ try:
238
+ with open(env_path, "w", encoding="utf-8") as f:
239
+ for key, value in existing_content.items():
240
+ f.write(f"{key}={value}\n")
241
+ except Exception as e:
242
+ print(f"写入.env文件时出错: {str(e)}")
243
+ return f"❌ 保存环境变量失败: {str(e)}"
244
 
245
  return "✅ 环境变量已保存"
246
 
 
319
  # 从.env文件中删除该环境变量
320
  env_path = Path(".env")
321
  if env_path.exists():
322
+ try:
323
+ with open(env_path, "r", encoding="utf-8") as f:
324
+ lines = f.readlines()
325
 
326
+ with open(env_path, "w", encoding="utf-8") as f:
327
+ for line in lines:
328
+ try:
329
+ # 更精确地匹配环境变量行
330
+ line_stripped = line.strip()
331
+ # 检查是否为注释行或空行
332
+ if not line_stripped or line_stripped.startswith("#"):
333
+ f.write(line) # 保留注释行和空行
334
+ continue
335
+
336
+ # 检查是否包含等号
337
+ if "=" not in line_stripped:
338
+ f.write(line) # 保留不包含等号的行
339
+ continue
340
+
341
+ # 提取变量名并检查是否与要删除的变量匹配
342
+ var_name = line_stripped.split("=", 1)[0].strip()
343
+ if var_name != name:
344
+ f.write(line) # 保留不匹配的变量
345
+ except Exception as e:
346
+ print(f"处理.env文件行时出错: {line}, 错误: {str(e)}")
347
+ # 出错时保留原行
348
+ f.write(line)
349
+ except Exception as e:
350
+ print(f"删除环境变量时出错: {str(e)}")
351
+ return f"❌ 删除环境变量失败: {str(e)}", None
352
 
353
  # 从当前进程的环境变量中删除
354
  if name in os.environ:
owl/app_en.py CHANGED
@@ -148,33 +148,49 @@ def load_env_vars():
148
 
149
  # Load other environment variables that may exist in the .env file
150
  if Path(".env").exists():
151
- with open(".env", "r", encoding="utf-8") as f:
152
- for line in f:
153
- line = line.strip()
154
- if line and not line.startswith("#") and "=" in line:
155
- key, value = line.split("=", 1)
156
- key = key.strip()
157
- value = value.strip().strip("\"'")
158
-
159
- # Check if it's a known environment variable
160
- known_var = False
161
- for group in ENV_GROUPS.values():
162
- if any(var["name"] == key for var in group):
163
- known_var = True
164
- break
165
-
166
- # If it's not a known environment variable, add it to the custom environment variables group
167
- if not known_var and key not in env_vars:
168
- ENV_GROUPS["Custom Environment Variables"].append(
169
- {
170
- "name": key,
171
- "label": key,
172
- "type": "text",
173
- "required": False,
174
- "help": "User-defined environment variable",
175
- }
176
- )
177
- env_vars[key] = value
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
  return env_vars
180
 
@@ -186,33 +202,51 @@ def save_env_vars(env_vars):
186
  existing_content = {}
187
 
188
  if env_path.exists():
189
- with open(env_path, "r", encoding="utf-8") as f:
190
- for line in f:
191
- line = line.strip()
192
- if line and not line.startswith("#") and "=" in line:
193
- key, value = line.split("=", 1)
194
- existing_content[key.strip()] = value.strip()
 
 
 
 
 
 
 
 
195
 
196
  # Update environment variables
197
  for key, value in env_vars.items():
198
- if value: # Only save non-empty values
199
- # Ensure the value is a string and wrapped in quotes
200
  value = str(value) # Ensure the value is a string
201
 
202
- # First remove existing quotes (if any)
203
- stripped_value = value.strip("\"'")
204
-
205
- # Wrap the value in double quotes to ensure special characters are handled correctly
206
- quoted_value = f'"{stripped_value}"'
207
- existing_content[key] = quoted_value
208
-
209
- # Also update the environment variable for the current process (using the unquoted value)
210
- os.environ[key] = stripped_value
 
 
 
 
 
 
211
 
212
  # Write to .env file
213
- with open(env_path, "w", encoding="utf-8") as f:
214
- for key, value in existing_content.items():
215
- f.write(f"{key}={value}\n")
 
 
 
 
216
 
217
  return "✅ Environment variables saved"
218
 
@@ -228,7 +262,7 @@ def add_custom_env_var(name, value, var_type):
228
  return f"❌ Environment variable {name} already exists", None
229
 
230
  # Add to custom environment variables group
231
- ENV_GROUPS["自定义环境变量"].append(
232
  {
233
  "name": name,
234
  "label": name,
@@ -295,22 +329,38 @@ def delete_custom_env_var(name):
295
  # Delete the environment variable from .env file
296
  env_path = Path(".env")
297
  if env_path.exists():
298
- with open(env_path, "r", encoding="utf-8") as f:
299
- lines = f.readlines()
 
300
 
301
- with open(env_path, "w", encoding="utf-8") as f:
302
- for line in lines:
303
- # More precisely match environment variable lines
304
- # Check if it's a non-comment line and contains variable_name=
305
- line_stripped = line.strip()
306
- if line_stripped.startswith("#") or "=" not in line_stripped:
307
- f.write(line) # Keep comment lines and lines without =
308
- continue
309
-
310
- # Extract variable name and check if it matches the variable to be deleted
311
- var_name = line_stripped.split("=", 1)[0].strip()
312
- if var_name != name:
313
- f.write(line) # Keep variables that don't match
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
 
315
  # Delete from current process environment variables
316
  if name in os.environ:
 
148
 
149
  # Load other environment variables that may exist in the .env file
150
  if Path(".env").exists():
151
+ try:
152
+ with open(".env", "r", encoding="utf-8") as f:
153
+ for line in f:
154
+ line = line.strip()
155
+ if line and not line.startswith("#") and "=" in line:
156
+ try:
157
+ key, value = line.split("=", 1)
158
+ key = key.strip()
159
+ value = value.strip()
160
+
161
+ # Handle quoted values
162
+ if (value.startswith('"') and value.endswith('"')) or (
163
+ value.startswith("'") and value.endswith("'")
164
+ ):
165
+ value = value[
166
+ 1:-1
167
+ ] # Remove quotes at the beginning and end
168
+
169
+ # Check if it's a known environment variable
170
+ known_var = False
171
+ for group in ENV_GROUPS.values():
172
+ if any(var["name"] == key for var in group):
173
+ known_var = True
174
+ break
175
+
176
+ # If it's not a known environment variable, add it to the custom environment variables group
177
+ if not known_var and key not in env_vars:
178
+ ENV_GROUPS["Custom Environment Variables"].append(
179
+ {
180
+ "name": key,
181
+ "label": key,
182
+ "type": "text",
183
+ "required": False,
184
+ "help": "User-defined environment variable",
185
+ }
186
+ )
187
+ env_vars[key] = value
188
+ except Exception as e:
189
+ print(
190
+ f"Error parsing environment variable line: {line}, error: {str(e)}"
191
+ )
192
+ except Exception as e:
193
+ print(f"Error loading .env file: {str(e)}")
194
 
195
  return env_vars
196
 
 
202
  existing_content = {}
203
 
204
  if env_path.exists():
205
+ try:
206
+ with open(env_path, "r", encoding="utf-8") as f:
207
+ for line in f:
208
+ line = line.strip()
209
+ if line and not line.startswith("#") and "=" in line:
210
+ try:
211
+ key, value = line.split("=", 1)
212
+ existing_content[key.strip()] = value.strip()
213
+ except Exception as e:
214
+ print(
215
+ f"Error parsing environment variable line: {line}, error: {str(e)}"
216
+ )
217
+ except Exception as e:
218
+ print(f"Error reading .env file: {str(e)}")
219
 
220
  # Update environment variables
221
  for key, value in env_vars.items():
222
+ if value is not None: # Allow empty string values, but not None
223
+ # Ensure the value is a string
224
  value = str(value) # Ensure the value is a string
225
 
226
+ # Check if the value is already wrapped in quotes
227
+ if (value.startswith('"') and value.endswith('"')) or (
228
+ value.startswith("'") and value.endswith("'")
229
+ ):
230
+ # Already wrapped in quotes, keep as is
231
+ existing_content[key] = value
232
+ # Update environment variable by removing quotes
233
+ os.environ[key] = value[1:-1]
234
+ else:
235
+ # Not wrapped in quotes, add double quotes
236
+ # Wrap the value in double quotes to ensure special characters are handled correctly
237
+ quoted_value = f'"{value}"'
238
+ existing_content[key] = quoted_value
239
+ # Also update the environment variable for the current process (using the unquoted value)
240
+ os.environ[key] = value
241
 
242
  # Write to .env file
243
+ try:
244
+ with open(env_path, "w", encoding="utf-8") as f:
245
+ for key, value in existing_content.items():
246
+ f.write(f"{key}={value}\n")
247
+ except Exception as e:
248
+ print(f"Error writing to .env file: {str(e)}")
249
+ return f"❌ Failed to save environment variables: {str(e)}"
250
 
251
  return "✅ Environment variables saved"
252
 
 
262
  return f"❌ Environment variable {name} already exists", None
263
 
264
  # Add to custom environment variables group
265
+ ENV_GROUPS["Custom Environment Variables"].append(
266
  {
267
  "name": name,
268
  "label": name,
 
329
  # Delete the environment variable from .env file
330
  env_path = Path(".env")
331
  if env_path.exists():
332
+ try:
333
+ with open(env_path, "r", encoding="utf-8") as f:
334
+ lines = f.readlines()
335
 
336
+ with open(env_path, "w", encoding="utf-8") as f:
337
+ for line in lines:
338
+ try:
339
+ # More precisely match environment variable lines
340
+ line_stripped = line.strip()
341
+ # Check if it's a comment line or empty line
342
+ if not line_stripped or line_stripped.startswith("#"):
343
+ f.write(line) # Keep comment lines and empty lines
344
+ continue
345
+
346
+ # Check if it contains an equals sign
347
+ if "=" not in line_stripped:
348
+ f.write(line) # Keep lines without equals sign
349
+ continue
350
+
351
+ # Extract variable name and check if it matches the variable to be deleted
352
+ var_name = line_stripped.split("=", 1)[0].strip()
353
+ if var_name != name:
354
+ f.write(line) # Keep variables that don't match
355
+ except Exception as e:
356
+ print(
357
+ f"Error processing .env file line: {line}, error: {str(e)}"
358
+ )
359
+ # Keep the original line when an error occurs
360
+ f.write(line)
361
+ except Exception as e:
362
+ print(f"Error deleting environment variable: {str(e)}")
363
+ return f"❌ Failed to delete environment variable: {str(e)}", None
364
 
365
  # Delete from current process environment variables
366
  if name in os.environ:
run_app.py CHANGED
@@ -58,4 +58,4 @@ def main():
58
 
59
 
60
  if __name__ == "__main__":
61
- main()
 
58
 
59
 
60
  if __name__ == "__main__":
61
+ main()