Skip to content

fix: log a warning on KRX empty responses instead of printing (#294) - #298

Closed
kvandre12-commits wants to merge 1 commit into
sharebook-kr:masterfrom
kvandre12-commits:fix/294-empty-response-warning
Closed

kvandre12-commits wants to merge 1 commit into
sharebook-kr:masterfrom
kvandre12-commits:fix/294-empty-response-warning

Conversation

@kvandre12-commits

Copy link
Copy Markdown

Summary

Fixes #294.

When KRX intermittently returns an empty response (e.g. under request load / rate limiting), dataframe_empty_handler already caught the resulting exception — most commonly ValueError: Length mismatch: Expected axis has 0 elements, new values have N elements, raised when the expected column names are assigned to an empty frame — and returned an empty DataFrame.

The problem is how it reported that: it used print() to stdout, so callers hitting KRX rate limits saw output that looks like a crash even though the call actually returned an (empty) result. It also called logging.info(args, kwargs), which misuses the logging API — the kwargs dict is passed as the %-format args, which would raise inside logging if INFO logging were enabled.

This aligns with the intent of #150, where empty responses were made to degrade gracefully instead of surfacing as errors.

Change

  • Replace the print() + buggy logging.info(args, kwargs) with a single, suppressible logger.warning(...) on a module-level logger.
  • Behaviour is otherwise unchanged: an empty DataFrame is still returned, and the same exception types are still handled.
  • Callers can now silence or redirect it, e.g. logging.getLogger("pykrx").setLevel(logging.ERROR).

Before (simulated empty KRX response)

Error occurred in get_market_net_purchases_of_equities_by_ticker: Length mismatch: Expected axis has 0 elements, new values have 8 elements

Printed to stdout — indistinguishable from a real crash.

After

A single WARNING log record (suppressible via the standard logging config), and the same empty DataFrame return value.

Tests

  • New offline unit tests in tests/test_dataframe_empty_handler.py:
    • empty response → empty DataFrame + a warning record (no exception, no stdout print),
    • passthrough of non-empty results,
    • KeyError / json.JSONDecodeError handling.
  • Existing market integration tests replay cleanly:
    pytest tests/integration/test_market_api.py -k "net_purchase or equities or ohlcv_by_date" → 5 passed.
  • ruff check and ruff format --check pass.

Notes

No public API or return-value changes — this only changes how the empty-response condition is reported (stdout print → warning log).


요약 (KR)

KRX가 요청 부하/레이트리밋 등으로 일시적으로 빈 응답을 줄 때(#294), dataframe_empty_handler는 이미 예외(대개 빈 프레임에 컬럼명을 지정하며 발생하는 ValueError: Length mismatch)를 잡아 빈 DataFrame을 반환하고 있었습니다. 다만 그 사실을 print()로 stdout에 출력해 마치 크래시처럼 보였고, logging.info(args, kwargs) 호출은 logging API를 잘못 사용합니다. 이를 억제 가능한 logger.warning(...) 한 줄로 교체했습니다(반환값·동작 동일, 빈 DataFrame 반환). 이는 #150의 처리 방향과 일치합니다. 데코레이터에 대한 오프라인 단위 테스트를 추가했으며 기존 통합 테스트도 통과합니다.

…ook-kr#294)

`dataframe_empty_handler` already caught the empty-response error (commonly
`ValueError: Length mismatch` raised when column names are assigned to an
empty frame), but it reported the failure via `print()` to stdout. Users
hitting KRX rate limits under request load therefore saw output that looked
like a crash (sharebook-kr#294). The handler also called `logging.info(args, kwargs)`,
which misuses the logging API (the kwargs dict is passed as the %-format
args).

Replace the `print()` / buggy `logging.info()` with a single, suppressible
`logger.warning(...)`, while keeping the existing behaviour of returning an
empty DataFrame. This aligns with the graceful empty-response handling
referenced in sharebook-kr#150.

Also add offline unit tests for the decorator: empty response -> empty
DataFrame + a warning record, passthrough of non-empty results, and
KeyError / JSONDecodeError handling.
@seohyunjun

Copy link
Copy Markdown
Collaborator

작성해주신 PR 감사합니다.
#291 Issue와 같은 문제로 사전에 먼저 제출한 이가 있어 #292 PR 승인했습니다. 혹시 더 추가하고 싶은 logger나 제안 있으면 변경된 코드로 작성해주시면 승인해드리겠습니다. 🙏

@seohyunjun seohyunjun added the duplicate This issue or pull request already exists label Sep 30, 2026
@seohyunjun seohyunjun closed this Sep 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

duplicate This issue or pull request already exists

Projects

None yet

2 participants