dana-medical-site/migrations/import/export_dir_icons.py
2026-10-14 13:33:13 +00:00

73 lines
2.8 KiB
Python

# -*- coding: utf-8 -*-
"""Иконки и hero-картинки направлений услуг (UF-поля разделов iblock 30)."""
import sqlread, io, os, zipfile
P = 'db.sql'
ZIP = r'C:\Users\naym4\Downloads\public_html.zip'
MEDIA_DIR = r'D:\dana\media'
OUT = io.open('seed_dir_icons.sql', 'w', encoding='utf-8')
MIME = {'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png',
'.gif': 'image/gif', '.svg': 'image/svg+xml', '.webp': 'image/webp'}
def esc(s):
return "'" + str(s or '').replace("\\", "\\\\").replace("'", "''") + "'"
files = {r['ID']: r for r in sqlread.rows(P, 'b_file')}
# section id -> CODE (направления услуг)
sec_code = {}
for r in sqlread.rows(P, 'b_iblock_section'):
if r['IBLOCK_ID'] == '30':
sec_code[r['ID']] = r.get('CODE')
zf = zipfile.ZipFile(ZIP)
names = set(zf.namelist())
extracted = {}
def ensure(fid):
if fid in extracted:
return extracted[fid]
f = files.get(fid)
if not f:
return None
subdir = (f.get('SUBDIR') or '').strip(); name = (f.get('FILE_NAME') or '').strip()
arc = 'public_html/upload/%s/%s' % (subdir, name)
if not subdir or not name or arc not in names:
return None
dd = os.path.join(MEDIA_DIR, subdir.replace('/', os.sep)); os.makedirs(dd, exist_ok=True)
with zf.open(arc) as s, open(os.path.join(dd, name), 'wb') as d:
d.write(s.read())
web = '/media/%s/%s' % (subdir, name); extracted[fid] = web
return web
def emit_media(fid, web):
f = files[fid]; ext = os.path.splitext(web)[1].lower()
mime = MIME.get(ext, 'application/octet-stream')
OUT.write("INSERT INTO media (path,mime,size,width,height,alt) VALUES (%s,%s,%s,%s,%s,'') "
"ON CONFLICT (path) DO NOTHING;\n" % (
esc(web), esc(mime), f.get('FILE_SIZE') or '0',
f.get('WIDTH') or '0', f.get('HEIGHT') or '0'))
OUT.write('BEGIN;\n')
icons = heroes = 0
for r in sqlread.rows(P, 'b_uts_iblock_30_section'):
code = sec_code.get(r['VALUE_ID'])
if not code:
continue
ic = r.get('UF_ICON')
if ic and ic not in ('', 'NULL'):
web = ensure(ic)
if web:
emit_media(ic, web)
OUT.write("UPDATE services SET icon=%s WHERE path=%s AND parent_id IS NULL;\n" % (esc(web), esc(code)))
icons += 1
hero = r.get('UF_TRANSPARENT_PICTURE')
if hero and hero not in ('', 'NULL'):
web = ensure(hero)
if web:
emit_media(hero, web)
OUT.write("UPDATE services SET image_id=(SELECT id FROM media WHERE path=%s) "
"WHERE path=%s AND parent_id IS NULL AND image_id IS NULL;\n" % (esc(web), esc(code)))
heroes += 1
OUT.write('COMMIT;\n'); OUT.close()
print('direction icons:', icons, 'heroes:', heroes, 'extracted:', len(extracted))