fix: 回填命令绕过 Django OutputWrapper 写输出

py2 + Django 1.x 的 OutputWrapper.write 会执行 msg.endswith(unicode '\n'):
- 传 utf-8 字节 → bytes.endswith(unicode) 触发 ascii 解码 → UnicodeDecodeError(0xe6)
- 传 unicode → stdout 编码为 ascii 时 → UnicodeEncodeError

改为直接写底层流(stream._out):py2 写 utf-8 字节,py3 写 str。
CommandError 文案同步改成 ASCII,避免 Django 打印时再踩同一个坑。

FFIB преди 4 часа
родител
ревизия
f512cfd65b
променени са 1 файла, в които са добавени 10 реда и са изтрити 6 реда
  1. 10 6
      sales/management/commands/backfill_lottery_names.py

+ 10 - 6
sales/management/commands/backfill_lottery_names.py

@@ -141,13 +141,17 @@ PY2 = sys.version_info[0] == 2
141 141
 
142 142
 def emit(stream, text):
143 143
     """
144
-    统一输出。
144
+    统一输出,绕过 Django 的 OutputWrapper。
145 145
 
146
-    py2 的 sys.stdout 吃字节串,直接写 unicode 会按 ascii 编码报错;
147
-    py3 的 sys.stdout 吃 str,写 bytes 又会 TypeError。这里按版本区分。
146
+    py2 + Django 1.x 下 OutputWrapper.write 会做 msg.endswith(unicode '\n'):
147
+    - 传 utf-8 字节 → bytes.endswith(unicode) 触发 ascii 解码 → UnicodeDecodeError
148
+    - 传 unicode   → sys.stdout 编码是 ascii 时 → UnicodeEncodeError
149
+    所以直接写底层流:py2 写 utf-8 字节,py3 写 str。
148 150
     """
149 151
     if PY2:
150
-        stream.write(text.encode('utf-8'))
152
+        target = getattr(stream, '_out', None) or stream
153
+        target.write(text.encode('utf-8'))
154
+        target.flush()
151 155
     else:
152 156
         stream.write(text)
153 157
 
@@ -208,7 +212,7 @@ class Command(BaseCommand):
208 212
             return self.handle_parse_only(options['parse_only'])
209 213
 
210 214
         if not options['dry_run'] and not options['apply']:
211
-            raise CommandError('必须指定 --dry-run(只统计)或 --apply(写库)')
215
+            raise CommandError('specify either --dry-run (count only) or --apply (write to db)')
212 216
 
213 217
         found, file_count, scanned = collect(log_glob)
214 218
 
@@ -279,7 +283,7 @@ class Command(BaseCommand):
279 283
 
280 284
     def handle_parse_only(self, path):
281 285
         if not os.path.exists(path):
282
-            raise CommandError('日志文件不存在:%s' % path)
286
+            raise CommandError('log file not found: %s' % path)
283 287
 
284 288
         found, file_count, scanned = collect(path)
285 289