Kgshop commited on
Commit
7f4e85f
·
verified ·
1 Parent(s): 931fd0b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -21
app.py CHANGED
@@ -15,6 +15,9 @@ DATA_FILE = 'data_detobuv.json'
15
  USERS_FILE = 'users_detobuv.json'
16
  CONFIG_FILE = 'config.json' # Файл для хранения курса KGS к USD
17
 
 
 
 
18
  # Настройки Hugging Face
19
  REPO_ID = "Kgshop/clients"
20
  HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
@@ -98,38 +101,45 @@ def load_users():
98
  def save_users(users):
99
  with open(USERS_FILE, 'w', encoding='utf-8') as file:
100
  json.dump(users, file, ensure_ascii=False, indent=4)
 
101
 
102
  def upload_db_to_hf():
103
  try:
104
  api = HfApi()
105
- api.upload_file(
106
- path_or_fileobj=DATA_FILE,
107
- path_in_repo=DATA_FILE,
108
- repo_id=REPO_ID,
109
- repo_type="dataset",
110
- token=HF_TOKEN_WRITE,
111
- commit_message=f"Автоматическое резервное копирование базы данных {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
112
- )
113
- logging.info("Резервная копия JSON базы успешно загружена на Hugging Face.")
 
 
 
 
114
  except Exception as e:
115
  logging.error(f"Ошибка при загрузке резервной копии: {e}")
116
 
117
  def download_db_from_hf():
118
  try:
119
- hf_hub_download(
120
- repo_id=REPO_ID,
121
- filename=DATA_FILE,
122
- repo_type="dataset",
123
- token=HF_TOKEN_READ,
124
- local_dir=".",
125
- local_dir_use_symlinks=False
126
- )
127
- logging.info("JSON база успешно скачана из Hugging Face.")
 
 
128
  except RepositoryNotFoundError as e:
129
  logging.error(f"Репозиторий не найден: {e}")
130
  raise
131
  except Exception as e:
132
- logging.error(f"Ошибка при скачивании JSON базы: {e}")
133
  raise
134
 
135
  def periodic_backup():
@@ -144,7 +154,7 @@ def catalog():
144
  categories = data['categories']
145
  is_authenticated = 'user' in session
146
  selected_currency = session.get('currency', 'USD') if is_authenticated else 'USD'
147
- kgs_to_usd = load_config() # Загружаем курс здесь
148
 
149
  catalog_html = '''
150
  <!DOCTYPE html>
@@ -832,6 +842,7 @@ def product_detail(index):
832
  def set_currency():
833
  if 'user' in session:
834
  currency = request.form.get('currency')
 
835
  if currency in CURRENCIES:
836
  session['currency'] = currency
837
  return redirect(url_for('catalog'))
@@ -1084,7 +1095,7 @@ def admin():
1084
 
1085
  if action == 'add_category':
1086
  category_name = request.form.get('category_name')
1087
- if category_name and category_name not in categories:
1088
  categories.append(category_name)
1089
  save_data(data)
1090
  return redirect(url_for('admin'))
@@ -1194,6 +1205,7 @@ def admin():
1194
  elif action == 'set_exchange_rate':
1195
  kgs_to_usd = float(request.form.get('kgs_to_usd').replace(',', '.'))
1196
  save_config(kgs_to_usd)
 
1197
  return redirect(url_for('admin'))
1198
 
1199
  elif action == 'delete_user':
 
15
  USERS_FILE = 'users_detobuv.json'
16
  CONFIG_FILE = 'config.json' # Файл для хранения курса KGS к USD
17
 
18
+ # Список файлов для синхронизации
19
+ SYNC_FILES = [DATA_FILE, USERS_FILE, CONFIG_FILE]
20
+
21
  # Настройки Hugging Face
22
  REPO_ID = "Kgshop/clients"
23
  HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
 
101
  def save_users(users):
102
  with open(USERS_FILE, 'w', encoding='utf-8') as file:
103
  json.dump(users, file, ensure_ascii=False, indent=4)
104
+ upload_db_to_hf() # Вызываем синхронизацию после сохранения
105
 
106
  def upload_db_to_hf():
107
  try:
108
  api = HfApi()
109
+ for file_name in SYNC_FILES:
110
+ if os.path.exists(file_name):
111
+ api.upload_file(
112
+ path_or_fileobj=file_name,
113
+ path_in_repo=file_name,
114
+ repo_id=REPO_ID,
115
+ repo_type="dataset",
116
+ token=HF_TOKEN_WRITE,
117
+ commit_message=f"Автоматическое резервное копирование файла {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
118
+ )
119
+ logging.info(f"Резервная копия {file_name} успешно загружена на Hugging Face.")
120
+ else:
121
+ logging.warning(f"Файл {file_name} не найден для загрузки.")
122
  except Exception as e:
123
  logging.error(f"Ошибка при загрузке резервной копии: {e}")
124
 
125
  def download_db_from_hf():
126
  try:
127
+ api = HfApi()
128
+ for file_name in SYNC_FILES:
129
+ hf_hub_download(
130
+ repo_id=REPO_ID,
131
+ filename=file_name,
132
+ repo_type="dataset",
133
+ token=HF_TOKEN_READ,
134
+ local_dir=".",
135
+ local_dir_use_symlinks=False
136
+ )
137
+ logging.info(f"Файл {file_name} успешно скачан из Hugging Face.")
138
  except RepositoryNotFoundError as e:
139
  logging.error(f"Репозиторий не найден: {e}")
140
  raise
141
  except Exception as e:
142
+ logging.error(f"Ошибка при скачивании файлов: {e}")
143
  raise
144
 
145
  def periodic_backup():
 
154
  categories = data['categories']
155
  is_authenticated = 'user' in session
156
  selected_currency = session.get('currency', 'USD') if is_authenticated else 'USD'
157
+ kgs_to_usd = load_config()
158
 
159
  catalog_html = '''
160
  <!DOCTYPE html>
 
842
  def set_currency():
843
  if 'user' in session:
844
  currency = request.form.get('currency')
845
+ subordinaty = request.form.get('subordinaty')
846
  if currency in CURRENCIES:
847
  session['currency'] = currency
848
  return redirect(url_for('catalog'))
 
1095
 
1096
  if action == 'add_category':
1097
  category_name = request.form.get('category_name')
1098
+ if categorystreamer_name and category_name not in categories:
1099
  categories.append(category_name)
1100
  save_data(data)
1101
  return redirect(url_for('admin'))
 
1205
  elif action == 'set_exchange_rate':
1206
  kgs_to_usd = float(request.form.get('kgs_to_usd').replace(',', '.'))
1207
  save_config(kgs_to_usd)
1208
+ upload_db_to_hf() # Синхронизация после изменения курса
1209
  return redirect(url_for('admin'))
1210
 
1211
  elif action == 'delete_user':