flaretool package

Subpackages

Submodules

flaretool.VERSION module

flaretool.basemodels module

Base data models for flaretool services.

class flaretool.basemodels.BaseDataModel

Bases: BaseModel

model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

flaretool.command module

flaretool command line interface.

flaretool.command.cli() int
flaretool.command.main() None

flaretool.common module

HTTP layer shared by all flaretool services.

flaretool.common.DEFAULT_TIMEOUT: tuple[float, float] = (5, 30)

Default (connect, read) timeout applied when the caller does not pass one.

class flaretool.common.requests

Bases: object

Thin wrapper around requests used by all flaretool services.

The class name intentionally shadows the third-party module for backwards compatibility (from flaretool.common import requests).

All verb helpers (get(), post(), …) funnel through request(), so patching flaretool.common.requests.request in tests intercepts every call. Do not bypass this funnel.

static delete(url: str, **kwargs: Any) Response
static get(url: str, **kwargs: Any) Response
static head(url: str, **kwargs: Any) Response
static post(url: str, **kwargs: Any) Response
static put(url: str, **kwargs: Any) Response
static request(method: str, url: str, auth_enabled: bool = False, **kwargs: Any) Response

Send an HTTP request with the specified method, URL, and optional parameters.

Parameters:
  • method (str) – The HTTP method to use for the request (e.g., ‘GET’, ‘POST’, ‘PUT’, ‘DELETE’).

  • url (str) – The URL to send the request to.

  • auth_enabled (bool, optional) – Whether to force authentication for the request. Defaults to False.

  • **kwargs – Additional keyword arguments to be passed to the underlying request method.

Returns:

The response object representing the server’s response to the request.

Return type:

Response

Raises:

FlareToolNetworkError – If the request is made to a Flare service and the response status code is 403.

flaretool.constants module

Constants used across flaretool.

class flaretool.constants.ConsoleColor

Bases: object

ANSI escape sequences for console coloring.

Kept as a plain class of str constants (not a StrEnum): consumers concatenate and print these values directly, and a plain class keeps repr/identity behavior unchanged.

BG_BLACK = '\x1b[40m'
BG_BLUE = '\x1b[44m'
BG_CYAN = '\x1b[46m'
BG_DEFAULT = '\x1b[49m'
BG_GREEN = '\x1b[42m'
BG_MAGENTA = '\x1b[45m'
BG_RED = '\x1b[41m'
BG_WHITE = '\x1b[47m'
BG_YELLOW = '\x1b[43m'
BLACK = '\x1b[30m'
BLUE = '\x1b[34m'
BOLD = '\x1b[1m'
COLOR_DEFAULT = '\x1b[39m'
CYAN = '\x1b[36m'
GREEN = '\x1b[32m'
INVISIBLE = '\x1b[08m'
MAGENTA = '\x1b[35m'
RED = '\x1b[31m'
RESET = '\x1b[0m'
REVERCE = '\x1b[07m'
UNDERLINE = '\x1b[4m'
WHITE = '\x1b[37m'
YELLOW = '\x1b[33m'
class flaretool.constants.Country(*values)

Bases: Enum

AD = 'Andorra'
AE = 'United Arab Emirates'
AF = 'Afghanistan'
AG = 'Antigua and Barbuda'
AI = 'Anguilla'
AL = 'Albania'
AM = 'Armenia'
AO = 'Angola'
AQ = 'Antarctica'
AR = 'Argentina'
AS = 'American Samoa'
AT = 'Austria'
AU = 'Australia'
AW = 'Aruba'
AX = 'Åland Islands'
AZ = 'Azerbaijan'
BA = 'Bosnia and Herzegovina'
BB = 'Barbados'
BD = 'Bangladesh'
BE = 'Belgium'
BF = 'Burkina Faso'
BG = 'Bulgaria'
BH = 'Bahrain'
BI = 'Burundi'
BJ = 'Benin'
BL = 'Saint Barthélemy'
BM = 'Bermuda'
BN = 'Brunei Darussalam'
BO = 'Bolivia, Plurinational State of'
BQ = 'Bonaire, Sint Eustatius and Saba'
BR = 'Brazil'
BS = 'Bahamas'
BT = 'Bhutan'
BW = 'Botswana'
BY = 'Belarus'
BZ = 'Belize'
CA = 'Canada'
CD = 'Congo, The Democratic Republic of the'
CF = 'Central African Republic'
CG = 'Congo'
CH = 'Switzerland'
CI = "Côte d'Ivoire"
CK = 'Cook Islands'
CL = 'Chile'
CM = 'Cameroon'
CN = 'China'
CO = 'Colombia'
CR = 'Costa Rica'
CU = 'Cuba'
CV = 'Cabo Verde'
CW = 'Curaçao'
CY = 'Cyprus'
CZ = 'Czechia'
DE = 'Germany'
DJ = 'Djibouti'
DK = 'Denmark'
DM = 'Dominica'
DO = 'Dominican Republic'
DZ = 'Algeria'
EC = 'Ecuador'
EE = 'Estonia'
EG = 'Egypt'
ER = 'Eritrea'
ES = 'Spain'
ET = 'Ethiopia'
FI = 'Finland'
FJ = 'Fiji'
FK = 'Falkland Islands (Malvinas)'
FM = 'Micronesia, Federated States of'
FO = 'Faroe Islands'
FR = 'France'
GA = 'Gabon'
GB = 'United Kingdom'
GD = 'Grenada'
GE = 'Georgia'
GF = 'French Guiana'
GG = 'Guernsey'
GH = 'Ghana'
GI = 'Gibraltar'
GL = 'Greenland'
GM = 'Gambia'
GN = 'Guinea'
GP = 'Guadeloupe'
GQ = 'Equatorial Guinea'
GR = 'Greece'
GT = 'Guatemala'
GU = 'Guam'
GW = 'Guinea-Bissau'
GY = 'Guyana'
HK = 'Hong Kong'
HN = 'Honduras'
HR = 'Croatia'
HT = 'Haiti'
HU = 'Hungary'
ID = 'Indonesia'
IE = 'Ireland'
IL = 'Israel'
IM = 'Isle of Man'
IN = 'India'
IO = 'British Indian Ocean Territory'
IQ = 'Iraq'
IR = 'Iran, Islamic Republic of'
IS = 'Iceland'
IT = 'Italy'
JE = 'Jersey'
JM = 'Jamaica'
JO = 'Jordan'
JP = 'Japan'
KE = 'Kenya'
KG = 'Kyrgyzstan'
KH = 'Cambodia'
KI = 'Kiribati'
KM = 'Comoros'
KN = 'Saint Kitts and Nevis'
KP = "Korea, Democratic People's Republic of"
KR = 'Korea, Republic of'
KW = 'Kuwait'
KY = 'Cayman Islands'
KZ = 'Kazakhstan'
LA = "Lao People's Democratic Republic"
LB = 'Lebanon'
LC = 'Saint Lucia'
LI = 'Liechtenstein'
LK = 'Sri Lanka'
LR = 'Liberia'
LS = 'Lesotho'
LT = 'Lithuania'
LU = 'Luxembourg'
LV = 'Latvia'
LY = 'Libya'
MA = 'Morocco'
MC = 'Monaco'
MD = 'Moldova, Republic of'
ME = 'Montenegro'
MF = 'Saint Martin (French part)'
MG = 'Madagascar'
MH = 'Marshall Islands'
MK = 'North Macedonia'
ML = 'Mali'
MM = 'Myanmar'
MN = 'Mongolia'
MO = 'Macao'
MP = 'Northern Mariana Islands'
MQ = 'Martinique'
MR = 'Mauritania'
MS = 'Montserrat'
MT = 'Malta'
MU = 'Mauritius'
MV = 'Maldives'
MW = 'Malawi'
MX = 'Mexico'
MY = 'Malaysia'
MZ = 'Mozambique'
NA = 'Namibia'
NC = 'New Caledonia'
NE = 'Niger'
NF = 'Norfolk Island'
NG = 'Nigeria'
NI = 'Nicaragua'
NL = 'Netherlands'
NO = 'Norway'
NP = 'Nepal'
NR = 'Nauru'
NU = 'Niue'
NZ = 'New Zealand'
OM = 'Oman'
PA = 'Panama'
PE = 'Peru'
PF = 'French Polynesia'
PG = 'Papua New Guinea'
PH = 'Philippines'
PK = 'Pakistan'
PL = 'Poland'
PM = 'Saint Pierre and Miquelon'
PR = 'Puerto Rico'
PS = 'Palestine, State of'
PT = 'Portugal'
PW = 'Palau'
PY = 'Paraguay'
QA = 'Qatar'
RE = 'Réunion'
RO = 'Romania'
RS = 'Serbia'
RU = 'Russian Federation'
RW = 'Rwanda'
SA = 'Saudi Arabia'
SB = 'Solomon Islands'
SC = 'Seychelles'
SD = 'Sudan'
SE = 'Sweden'
SG = 'Singapore'
SI = 'Slovenia'
SK = 'Slovakia'
SL = 'Sierra Leone'
SM = 'San Marino'
SN = 'Senegal'
SO = 'Somalia'
SR = 'Suriname'
SS = 'South Sudan'
ST = 'Sao Tome and Principe'
SV = 'El Salvador'
SX = 'Sint Maarten (Dutch part)'
SY = 'Syrian Arab Republic'
SZ = 'Eswatini'
TC = 'Turks and Caicos Islands'
TD = 'Chad'
TG = 'Togo'
TH = 'Thailand'
TJ = 'Tajikistan'
TK = 'Tokelau'
TL = 'Timor-Leste'
TM = 'Turkmenistan'
TN = 'Tunisia'
TO = 'Tonga'
TR = 'Turkey'
TT = 'Trinidad and Tobago'
TV = 'Tuvalu'
TW = 'Taiwan, Province of China'
TZ = 'Tanzania, United Republic of'
UA = 'Ukraine'
UG = 'Uganda'
US = 'United States'
UY = 'Uruguay'
UZ = 'Uzbekistan'
VA = 'Holy See (Vatican City State)'
VC = 'Saint Vincent and the Grenadines'
VE = 'Venezuela, Bolivarian Republic of'
VG = 'Virgin Islands, British'
VI = 'Virgin Islands, U.S.'
VN = 'Viet Nam'
VU = 'Vanuatu'
WF = 'Wallis and Futuna'
WS = 'Samoa'
YE = 'Yemen'
YT = 'Mayotte'
ZA = 'South Africa'
ZM = 'Zambia'
ZW = 'Zimbabwe'

flaretool.decorators module

flaretool の汎用デコレーター群。

同期関数・非同期関数(コルーチン関数)のどちらに適用しても 透過的に動作するように実装されています。

flaretool.decorators.cache(ttl: int | float | None = None, maxsize: int = 128) Callable[[Callable[[P], R]], Callable[[P], R]]

関数の結果をキャッシュするデコレーター。TTL(Time To Live)とキャッシュサイズの制限をサポート。

有効期限の判定にはキャッシュ登録時刻(time.monotonic)を使用します。 キャッシュヒットでは有効期限は延長されず、LRUの追い出し順のみが更新されます。 キャッシュキーは引数の型を区別します(例: f(1) と f(‘1’) は別エントリ)。 キーワード引数を含む呼び出しはシグネチャにバインドして正規化されるため、 f(1, 2) と f(x=1, y=2) は同じエントリを共有します。 同期関数はスレッドセーフです。非同期関数も同じロックを使用しますが、 ロック保持区間は辞書操作のみの短時間であり await を含まないため、 イベントループをブロックしません。関数本体はロックの外で実行されます。

Parameters:
  • ttl (int | float, optional) – キャッシュの有効期限(秒)。Noneの場合は無期限。デフォルトはNone。

  • maxsize (int, optional) – キャッシュの最大サイズ。デフォルトは128。

Returns:

デコレートされた関数の戻り値。

Return type:

function

Examples

>>> @cache(ttl=300)  # 5分間キャッシュ
... def expensive_function(x, y):
...     time.sleep(2)
...     return x + y
>>> result = expensive_function(1, 2)  # 2秒かかる
>>> result = expensive_function(1, 2)  # すぐに返る(キャッシュから)
>>> @cache(ttl=10, maxsize=100)
... def api_call(endpoint):
...     return requests.get(endpoint).json()
flaretool.decorators.deprecate(version: str | None = None, alternative: str | None = None, message: str | None = None) Callable[[Callable[[P], R]], Callable[[P], R]]

関数が非推奨であることを警告するデコレーター。

Parameters:
  • version (str, optional) – この関数が非推奨になるバージョン。デフォルトはNone。

  • alternative (str, optional) – 代替として推奨される関数名。デフォルトはNone。

  • message (str, optional) – カスタム警告メッセージ。デフォルトはNone。

Returns:

デコレートされた関数。

Return type:

function

Examples

>>> @deprecate(version="2.0.0", alternative="new_function")
... def old_function():
...     return "old"
>>> old_function()
DeprecationWarning: old_function is deprecated and will be removed in version 2.0.0. Use new_function instead.
'old'
>>> @deprecate(message="この関数は使用しないでください")
... def legacy_function():
...     return "legacy"
flaretool.decorators.network_required(func: Callable[[P], R] | None = None, *, host: str = 'google.com', port: int = 443, timeout: float = 5) Callable[[P], R] | Callable[[Callable[[P], R]], Callable[[P], R]]

ネットワーク接続のチェックを行い、接続されている場合には指定されたメソッドを実行します。 接続されていない場合にはFlareToolNetworkErrorを発生させます。

@network_required のように引数なしでも、 @network_required(host=”example.com”, port=80, timeout=3) のように 接続確認先を指定しても使用できます。

Parameters:
  • func (callable, optional) – ネットワーク接続を確認した後に実行するメソッド。

  • host (str, optional) – 接続確認先ホスト。デフォルトは “google.com”。

  • port (int, optional) – 接続確認先ポート。デフォルトは 443。

  • timeout (float, optional) – 接続確認のタイムアウト秒数。デフォルトは 5。

Returns:

デコレートされた関数。

Return type:

callable

Raises:

FlareToolNetworkError – ネットワークに接続されていない場合に発生する例外。

Examples

>>> @network_required
... def fetch_data():
...     return "data"
>>> @network_required(host="example.com", port=80)
... def fetch_other():
...     return "other"
flaretool.decorators.rate_limit(calls: int, period: float) Callable[[Callable[[P], R]], Callable[[P], R]]

関数の呼び出し回数を制限するデコレーター(スライディングウィンドウ方式)。

period 秒間の呼び出し回数を calls 回までに制限します。 制限を超えた場合は空きが出るまでブロック(非同期関数の場合は待機)します。

Parameters:
  • calls (int) – period 秒間に許可する呼び出し回数。

  • period (float) – 制限期間(秒)。

Returns:

デコレートされた関数。

Return type:

function

Examples

>>> @rate_limit(calls=2, period=1.0)
... def api_call():
...     return "called"
>>> api_call()  # すぐに実行
>>> api_call()  # すぐに実行
>>> api_call()  # 1秒間の枠が空くまで待機してから実行
flaretool.decorators.repeat(tries: int, interval: float = 0) Callable[[Callable[[P], R]], Callable[[P], R | None]]

指定された間隔で関数を指定回数再実行するデコレーター。

関数内で StopIteration(非同期関数では StopAsyncIteration も可)を 送出することで繰り返しを中断できます。 tries が 0 の場合や最初の呼び出しで中断された場合は None を返します。 最後の実行後には待機しません。

Parameters:
  • tries (int) – リピートする回数

  • interval (float, optional) – 実行間隔(秒単位)。デフォルト値は0。

Returns:

デコレートされた関数

Return type:

function

Examples

>>> @repeat(5, 3)
... def print_hello():
...     print("Hello, world!")
...     if some_condition: # 実行を止めたい場合の条件
...         raise StopIteration("Stop the loop")
>>> print_hello()
Hello, world!
Hello, world!
Hello, world!
Hello, world!
Hello, world!
flaretool.decorators.retry(tries: int, delay: float = 0, backoff: float = 1, target_exception: type[BaseException] | tuple[type[BaseException], ...] | None = None, jitter: float = 0, max_delay: float | None = None) Callable[[Callable[[P], R]], Callable[[P], R]]

指定された例外(またはすべての例外)が発生した場合に関数をリトライするデコレーター。

Parameters:
  • tries (int) – 最大リトライ回数。

  • delay (float) – 最初のリトライまでの遅延秒数。デフォルトは0。

  • backoff (float) – リトライ間の遅延時間を増加させる係数。デフォルトは1。

  • target_exception (type[BaseException] | tuple[type[BaseException], ...], optional) – リトライのトリガーとなる例外クラス(またはそのタプル)。 Noneの場合はすべての例外をキャッチします。デフォルトはNone。

  • jitter (float, optional) – 遅延に加算するランダムな揺らぎの最大秒数 (0〜jitter の一様乱数)。デフォルトは0。

  • max_delay (float, optional) – 遅延秒数の上限。Noneの場合は無制限。デフォルトはNone。

Returns:

デコレートされた関数の戻り値。

Return type:

function

Raises:
  • ValueError – tries が 1 未満の場合(デコレート時に発生)。

  • Exception – 最後のリトライでも例外が発生した場合、その例外を発生させる。

Examples

>>> @retry(3, target_exception=ValueError)
... def my_function():
...    # Some code that may raise a ValueError
...    print("Function executed successfully")
...    raise ValueError("Error")
...    pass
>>> try:
...    my_function()
... except ValueError:
...    print("ValueError occurred")
Function executed successfully
Function executed successfully
Function executed successfully
ValueError occurred
flaretool.decorators.run_in_thread(func: Callable[[P], R]) Callable[[P], Future]

同期関数をバックグラウンドスレッドで実行するデコレーター。

呼び出すと即座に concurrent.futures.Future を返します。 結果は Future.result() で取得できます。 実行にはモジュール共有の ThreadPoolExecutor(最大8ワーカー)を使用します。 コルーチン関数には適用できません(asyncio.create_task 等を使用してください)。

Parameters:

func (callable) – バックグラウンドで実行する同期関数。

Returns:

Future を返すラッパー関数。

Return type:

callable

Raises:

TypeError – コルーチン関数に適用した場合に発生します。

Examples

>>> @run_in_thread
... def slow_task(x):
...     time.sleep(1)
...     return x * 2
>>> future = slow_task(5)  # すぐに返る
>>> future.result()  # 完了を待って結果を取得
10
flaretool.decorators.singleton(cls: type[R]) Callable[[...], R]

クラスをシングルトンにするデコレーター(スレッドセーフ)。

最初の呼び出しでインスタンスを生成し、以降は同じインスタンスを返します。 デコレート後の名前はインスタンスを返すファクトリー関数になります (生成されるインスタンスは元のクラスのインスタンスです)。

Parameters:

cls (type) – シングルトンにするクラス。

Returns:

常に同一インスタンスを返すファクトリー関数。

Return type:

callable

Examples

>>> @singleton
... class Config:
...     def __init__(self):
...         self.value = 42
>>> a = Config()
>>> b = Config()
>>> a is b
True
flaretool.decorators.suppress_errors(default: ~typing.Any = None, exceptions: type[BaseException] | tuple[type[BaseException], ...] = (<class 'Exception'>,), log: bool = True) Callable[[Callable[[P], R]], Callable[[P], R | Any]]

例外を抑制してデフォルト値を返すデコレーター。

指定した例外が発生した場合、例外を送出する代わりに default を返します。

Parameters:
  • default (Any, optional) – 例外発生時に返す値。デフォルトはNone。

  • exceptions (type | tuple, optional) – 抑制する例外クラス(またはそのタプル)。 デフォルトは (Exception,)。

  • log (bool, optional) – 例外発生時にログを出力するかどうか。デフォルトはTrue。

Returns:

デコレートされた関数。

Return type:

function

Examples

>>> @suppress_errors(default=0)
... def parse_number(text):
...     return int(text)
>>> parse_number("123")
123
>>> parse_number("abc")  # 例外は送出されず 0 が返る
0
flaretool.decorators.synchronized(func: Callable[[P], R]) Callable[[P], R]

関数の同時実行を防ぐデコレーター。

同期関数には関数ごとの再入可能ロック(threading.RLock)を使用します。 非同期関数には関数ごとの asyncio.Lock を使用します (複数のイベントループをまたいだ使用はできません)。

Parameters:

func (callable) – 排他制御を行う関数。

Returns:

デコレートされた関数。

Return type:

callable

Examples

>>> counter = {"value": 0}
>>> @synchronized
... def increment():
...     current = counter["value"]
...     time.sleep(0.01)
...     counter["value"] = current + 1
>>> # 複数スレッドから呼び出しても安全
flaretool.decorators.timeout(timeout: int | float) Callable[[Callable[[P], R]], Callable[[P], R]]

指定した時間内に処理が完了しない場合に TimeoutError を発生させるデコレーター。

同期関数はデーモンスレッドで実行して待機し、非同期関数は asyncio.wait_for によるタイムアウト制御を行います。 なお、同期関数の場合、タイムアウト後もバックグラウンドのスレッド自体は 処理が終わるまで動き続けます(デーモンスレッドのため インタープリター終了は妨げません)。

Parameters:

timeout (int or float) – タイムアウト時間(秒)。

Returns:

タイムアウト付きのデコレーター。

Return type:

function

Raises:

TimeoutError – タイムアウトが発生した場合に送出されます。

Examples

>>> @timeout(5)
... def my_function():
...    # Some time-consuming operation
...    time.sleep(10)
...    return "Operation completed"
>>> try:
...    result = my_function()
...    print(result)
... except TimeoutError:
...    print("Operation timed out")
Operation timed out
flaretool.decorators.timer(func: Callable[[P], R]) Callable[[P], R]

デコレートされた関数の実行時間を測定するデコレーター。 flaretoolのloggerに出力。関数が例外を送出した場合も 経過時間をログに出力します。

Parameters:

func (callable) – 実行時間を測定する関数。

Returns:

実行時間を表示し、元の関数の結果を返すラッパー関数。

Return type:

function

Examples

>>> # Logger Setup
... from flaretool.logger import setup_logger
... logger = setup_logger(logging.DEBUG, console=True)
...
>>> @timer
... def example_function(x):
...     time.sleep(x)
...     return x
>>> example_function(2)
[2024-08-01 00:00:00,000] DEBUG : example_function took 2.0000 seconds to execute.
flaretool.decorators.type_check(func: Callable[[P], R]) Callable[[P], R]

型チェックを行うデコレーター

引数のアノテーションに基づいて実行時に型チェックを行います。 デフォルト値が None のパラメーターは暗黙的に Optional として扱われ、 None の指定を許容します。X | None や Optional[X] にも対応し、 パラメーター化されたジェネリクス(例: list[str])は origin 型 (例: list)のみをチェックします。

Parameters:

func (callable) – 型チェックを行う関数。

Returns:

デコレートされた関数。

Return type:

callable

Raises:

TypeError – 引数の型が予期された型と一致しない場合に発生します。

Examples

>>> @type_check
... def my_function(arg1: int, arg2: str):
...     # 関数の処理...
...     pass
>>> my_function(10, "Hello")
10 Hello
>>> my_function("10", 20)
TypeError: Argument 'arg1' has unexpected type 'str' (expected 'int').

flaretool.enums module

flaretool 全体で使用する列挙型の定義.

class flaretool.enums.Base64Mode(*values)

Bases: Enum

flaretool.utils.base64_convert() の処理モード.

DECODE = 2

Base64デコード

ENCODE = 1

Base64エンコード

class flaretool.enums.ConversionMode(*values)

Bases: Enum

flaretool.utils.convert_value() の変換モード.

FULL_WIDTH = 2

全角に変換

HALF_WIDTH = 1

半角に変換

HIRAGANA = 5

ひらがなに変換

KATAKANA = 6

カタカナに変換

LOWER = 4

小文字に変換

UPPER = 3

大文字に変換

class flaretool.enums.HashMode(*values)

Bases: Enum

flaretool.utils.hash_value() のハッシュアルゴリズム.

MD5 = 1
SHA1 = 2
SHA256 = 3
SHA512 = 4

flaretool.errors module

Exception types raised by flaretool.

exception flaretool.errors.AuthenticationError(message: str | None = None)

Bases: FlareToolError

Raised when no or invalid API credentials are provided.

exception flaretool.errors.FlareToolError(message: str | None = None)

Bases: Exception

Base exception class for FlareTool errors.

exception flaretool.errors.FlareToolNetworkError(message: str | None = None, http_body: str | bytes | None = None, http_status: int | None = None, json_body: Any = None, headers: dict[str, Any] | None = None, code: str | None = None, **param: Any)

Bases: FlareToolError

Raised when a request to a Flare service fails.

flaretool.logger module

Logging helpers for flaretool.

flaretool.logger.get_logger(logger_name: str = 'flaretool') Logger
flaretool.logger.setup_logger(loglevel: int = 20, logger_name: str = 'flaretool', console: bool = True, file: bool = False, file_name: str = 'flaretool.log', rotating: bool = False, max_bytes: int = 1024000, backup_count: int = 5, extra: bool = False, encoding: str = 'utf-8') Logger

flaretool.settings module

flaretool settings loaded from the environment / .env file.

class flaretool.settings.BaseSettings(_case_sensitive: bool | None = None, _nested_model_default_partial_update: bool | None = None, _env_prefix: str | None = None, _env_prefix_target: EnvPrefixTarget | None = None, _env_file: DotenvType | None = PosixPath('.'), _env_file_encoding: str | None = None, _env_ignore_empty: bool | None = None, _env_nested_delimiter: str | None = None, _env_nested_max_split: int | None = None, _env_parse_none_str: str | None = None, _env_parse_enums: bool | None = None, _cli_prog_name: str | None = None, _cli_parse_args: bool | list[str] | tuple[str, ...] | None = None, _cli_settings_source: CliSettingsSource[Any] | None = None, _cli_parse_none_str: str | None = None, _cli_hide_none_type: bool | None = None, _cli_avoid_json: bool | None = None, _cli_enforce_required: bool | None = None, _cli_use_class_docs_for_groups: bool | None = None, _cli_exit_on_error: bool | None = None, _cli_prefix: str | None = None, _cli_flag_prefix_char: str | None = None, _cli_implicit_flags: bool | Literal['dual', 'toggle'] | None = None, _cli_ignore_unknown_args: bool | None = None, _cli_kebab_case: bool | Literal['all', 'no_enums'] | None = None, _cli_shortcuts: Mapping[str, str | list[str]] | None = None, _secrets_dir: PathType | None = None, _build_sources: tuple[tuple[PydanticBaseSettingsSource, ...], dict[str, Any]] | None = None, *, api_key: str | None = None)

Bases: BaseSettings

flaretool settings.

The class is named BaseSettings for backwards compatibility; prefer the FlareToolSettings alias in new code.

api_key: str | None
model_config = {'arbitrary_types_allowed': True, 'case_sensitive': False, 'cli_avoid_json': False, 'cli_enforce_required': False, 'cli_exit_on_error': True, 'cli_flag_prefix_char': '-', 'cli_hide_none_type': False, 'cli_ignore_unknown_args': False, 'cli_implicit_flags': False, 'cli_kebab_case': False, 'cli_parse_args': None, 'cli_parse_none_str': None, 'cli_prefix': '', 'cli_prog_name': None, 'cli_shortcuts': None, 'cli_use_class_docs_for_groups': False, 'enable_decoding': True, 'env_file': '.env', 'env_file_encoding': 'utf-8', 'env_ignore_empty': False, 'env_nested_delimiter': None, 'env_nested_max_split': None, 'env_parse_enums': None, 'env_parse_none_str': None, 'env_prefix': '', 'env_prefix_target': 'variable', 'extra': 'ignore', 'json_file': None, 'json_file_encoding': None, 'nested_model_default_partial_update': False, 'protected_namespaces': ('model_validate', 'model_dump', 'settings_customise_sources'), 'secrets_dir': None, 'toml_file': None, 'validate_default': True, 'yaml_config_section': None, 'yaml_file': None, 'yaml_file_encoding': None}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

flaretool.settings.FlareToolSettings

alias of BaseSettings

flaretool.settings.get_settings() BaseSettings

Return the (cached) settings instance.

The environment / .env file is read once per process; construct BaseSettings() directly if a fresh read is needed.

flaretool.utills module

Deprecated alias for flaretool.utils.

このモジュールは後方互換のために残されています。 新しいコードでは flaretool.utils を使用してください。

Deprecated since version ``flaretool.utills``: は非推奨です。flaretool.utils に置き換えられました。

flaretool.utils module

汎用ユーティリティ関数群(文字列変換/ハッシュ/Base64/一時ディレクトリなど).

class flaretool.utils.DictToFieldConverter(dictionary: dict)

Bases: object

This class converts a dictionary into field values.

Parameters:

dictionary (dict) – The dictionary to convert.

dictionary

The dictionary being converted.

Type:

dict

Raises:

AttributeError – If a requested field does not exist in the dictionary.

Example

# Create a dictionary dictionary = {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘Tokyo’}

# Create an instance of DictToFieldConverter converter = DictToFieldConverter(dictionary)

# Access field values name = converter.name age = converter.age city = converter.city

print(name) # Output: ‘John’ print(age) # Output: 30 print(city) # Output: ‘Tokyo’

flaretool.utils.base64_convert(value: str, mode: Base64Mode = Base64Mode.ENCODE, encoding: str = 'utf-8') str

文字列のBase64エンコードまたはデコードを行います。

Parameters:
  • value (str) – エンコードまたはデコードする文字列

  • mode (Base64Mode, optional) – 処理モード. デフォルトはBase64Mode.ENCODE.

  • encoding (str, optional) – エンコードに使用する文字エンコーディング. デフォルトは’utf-8’.

Returns:

エンコードまたはデコード後の文字列

Return type:

str

Raises:

ValueError – 無効な処理モードが指定された場合

flaretool.utils.convert_value(value: str, mode: ConversionMode = ConversionMode.HALF_WIDTH, ascii: bool = True, digit: bool = True, kana: bool = True, non_convert_chars: str | list[str] | None = None) str

文字列を変換(半角/全角/大文字/小文字/ひらがな/カタカナ)<br> ひらがな/カタカナの変換は全角に変換されます

Parameters:
  • value (str) – 変換する文字列

  • mode (ConversionMode, optional) – 変換モード. デフォルトはConversionMode.HALF_WIDTH.

  • ascii (bool, optional) – ASCII文字の変換を有効にするかどうか. デフォルトはTrue.

  • digit (bool, optional) – 数字の変換を有効にするかどうか. デフォルトはTrue.

  • kana (bool, optional) – カナ文字の変換を有効にするかどうか. デフォルトはTrue.

  • non_convert_chars (str or list[str], optional) – 変換しない文字列. デフォルトはNone. 全角変換時、保護された文字は直後の濁点/半濁点との合成対象になりません (例: ‘ガ’ で ‘カ’ を保護すると ‘ガ’ に合成されず ‘カ゛’ になります).

Returns:

変換後の文字列

Return type:

str

Raises:

ValueError – 無効な変換モードが指定された場合

flaretool.utils.get_temp_dir_path() str

Get the path to a temporary dir path.

Returns:

The path to the temporary path.

Return type:

str

flaretool.utils.hash_value(value: str, mode: HashMode = HashMode.MD5, encoding: str = 'utf-8') str

文字列のハッシュ計算を行います。

Parameters:
  • value (str) – ハッシュ計算する文字列

  • mode (HashMode, optional) – ハッシュモード. デフォルトはHashMode.MD5.

  • encoding (str, optional) – 文字列のエンコーディング. デフォルトは’utf-8’.

Returns:

ハッシュ値の16進数表現

Return type:

str

Raises:

ValueError – 無効なハッシュモードが指定された場合

flaretool.utils.is_file_fresh(file_path: str, days: int) bool

Check if the given file has been modified within the specified number of days.

Parameters:
  • file_path (str) – The path to the file.

  • days (int) – The number of days to check for freshness.

Returns:

True if the file is fresh, False otherwise.

Return type:

bool

flaretool.wareki module

和暦(元号)と西暦の相互変換ユーティリティ(明治/大正/昭和/平成/令和対応).

class flaretool.wareki.Era(name: str, name_short: str, romaji: str, start: date, end: date | None)

Bases: object

元号を表すデータクラス

name

元号名 (例: “令和”)

Type:

str

name_short

元号の頭文字 (例: “R”)

Type:

str

romaji

元号のローマ字表記 (例: “Reiwa”)

Type:

str

start

元号の開始日(グレゴリオ暦)

Type:

datetime.date

end

元号の終了日. 現行元号の場合はNone.

Type:

datetime.date or None

end: date | None
name: str
name_short: str
romaji: str
start: date
flaretool.wareki.get_era(date: date | datetime | str) Era

指定した日付が属する元号を取得します。

Parameters:

date (datetime.date or datetime.datetime or str) – 対象の日付. 文字列はISO形式(“2019-05-01”)のほか “2019/05/01”, “2019年5月1日” などを受け付けます(全角数字も可).

Returns:

該当する元号

Return type:

Era

Raises:

ValueError – 明治より前の日付、または日付として解釈できない場合

Examples

>>> get_era("2019-05-01").name
'令和'
>>> get_era(datetime.date(1989, 1, 7)).name
'昭和'
flaretool.wareki.get_fiscal_year(date: date | datetime | str, *, start_month: int = 4) int

指定した日付の年度(日本の会計年度)を取得します。

Parameters:
  • date (datetime.date or datetime.datetime or str) – 対象の日付

  • start_month (int, optional) – 年度の開始月 (1〜12). デフォルトは4.

Returns:

年度 (例: 2026-03-31 -> 2025)

Return type:

int

Raises:

ValueError – start_monthが1〜12の範囲外、または日付として解釈できない場合

Examples

>>> get_fiscal_year("2026-03-31")
2025
>>> get_fiscal_year("2026-04-01")
2026
flaretool.wareki.int_to_kanji(value: int) str

整数(1〜999)を漢数字に変換します。1〜99の出力は従来と同一です。

Parameters:

value (int) – 変換する整数 (1〜999)

Returns:

変換後の漢数字 (例: 8 -> “八”, 29 -> “二十九”, 101 -> “百一”)

Return type:

str

Raises:

ValueError – 1〜999の範囲外、または整数でない場合

Examples

>>> int_to_kanji(8)
'八'
>>> int_to_kanji(12)
'十二'
>>> int_to_kanji(29)
'二十九'
>>> int_to_kanji(100)
'百'
>>> int_to_kanji(201)
'二百一'
flaretool.wareki.kanji_to_int(text: str) int

漢数字(1〜999)を整数に変換します。”元” は 1 として扱います。

Parameters:

text (str) – 変換する漢数字 (例: “八”, “十二”, “二十九”, “百一”, “元”)

Returns:

変換後の整数 (1〜999)

Return type:

int

Raises:

ValueError – 漢数字として解釈できない場合、または1〜999の範囲外の場合

Examples

>>> kanji_to_int("八")
8
>>> kanji_to_int("二十九")
29
>>> kanji_to_int("百")
100
>>> kanji_to_int("二百一")
201
>>> kanji_to_int("元")
1
flaretool.wareki.to_seireki(text: str) date

和暦の文字列を西暦の日付に変換します。

“令和8年7月2日”、”令和元年5月1日”、”R8.7.2”、”R8/7/2”、”R8-7-2”、 “H31.4.30”、”Reiwa 8-7-2”、漢数字(“令和八年七月二日”)、 全角文字(“R8年7月2日”)などを受け付けます。 年月日がすべて揃っていない場合や、元号の期間外の日付 (例: “昭和65年1月1日”)はValueErrorとなります。

Parameters:

text (str) – 変換する和暦の文字列

Returns:

変換後の西暦の日付

Return type:

datetime.date

Raises:

ValueError – 和暦として解釈できない場合、存在しない日付の場合、 または元号の期間外の日付の場合

Examples

>>> to_seireki("令和8年7月2日")
datetime.date(2026, 7, 2)
>>> to_seireki("令和元年5月1日")
datetime.date(2019, 5, 1)
>>> to_seireki("H31.4.30")
datetime.date(2019, 4, 30)
flaretool.wareki.to_wareki(date: date | datetime | str, *, format: str = '{era}{year}年{month}月{day}日', gannen: bool = True) str

西暦の日付を和暦の文字列に変換します。

formatで使用できるプレースホルダー:

{era} 令和 / {era_short} R / {era_romaji} Reiwa / {year} 8 / {year_kanji} 八 / {month} 7 / {month_kanji} 七 / {day} 2 / {day_kanji} 二

漢数字プレースホルダー({year_kanji}など)は書式で参照された場合のみ 計算されます。{year_kanji}は999年まで対応し、100以上は”百”を使った 表記になります(例: 100 -> “百”, 101 -> “百一”)。

Parameters:
  • date (datetime.date or datetime.datetime or str) – 変換する日付

  • format (str, optional) – 出力書式. デフォルトは”{era}{year}年{month}月{day}日”.

  • gannen (bool, optional) – Trueの場合、元号1年目の{year}を”元”として 出力します(例: “令和元年”). {year_kanji}には影響せず、1年目は 常に”一”となります. Falseの場合は{year}も”1”になります. デフォルトはTrue.

Returns:

和暦の文字列 (例: “令和8年7月2日”)

Return type:

str

Raises:

ValueError – 明治より前の日付、日付として解釈できない場合、 またはformatに未知のプレースホルダーが含まれる場合

Examples

>>> to_wareki("2026-07-02")
'令和8年7月2日'
>>> to_wareki("2019-05-01")
'令和元年5月1日'
>>> to_wareki("2019-05-01", gannen=False)
'令和1年5月1日'
>>> to_wareki("2026-07-02", format="{era_short}{year}.{month}.{day}")
'R8.7.2'
flaretool.wareki.today_wareki(**kwargs) str

今日の日付を和暦の文字列に変換します。

Parameters:

**kwargs – to_wareki()に渡すキーワード引数 (format, gannen)

Returns:

今日の和暦文字列 (例: “令和8年7月2日”)

Return type:

str

Examples

>>> today_wareki()
'令和8年7月2日'

Module contents

flaretool python module [Terms of service](https://main.flarebrow.com/terms)

flaretool.check_version() None

Warn if a newer flaretool release is available on PyPI.

This check is opt-in: it is intentionally not executed at import time (importing the package must not perform network I/O).

flaretool.get_latest_version() str

Return the latest flaretool version published on PyPI.

Falls back to the installed version if PyPI cannot be reached.

flaretool.get_lib_version() str

Return the installed flaretool version.