コンテンツにスキップ

APIリファレンス

0.11のConfig、URL hooks、Blueprintのapp-wide hooks、request.blueprints、 JSON helperの追加仕様はFlask互換性と移行ガイドを参照してください。

0.10+のAsyncSQLAlchemyExtension、Signalとライフサイクル通知、RedisSessionStore/ RedisSessionMiddleware/RedisRateLimitMiddleware、Observability/JSONLogFormatter/ HealthChecksは非同期・共有状態・運用監視に使用例と境界をまとめています。

0.9+の親子Blueprint・CLI・ASGIテスト、 SQLAlchemyExtension / RedisExtension、入力spool APIも参照してください。

0.5.0のcontext・session・flash等と、0.7.0のrequest context・Blueprint hooks・body helperは Flask互換性のAPI一覧にまとめています。

ここに記載する名前は、特記がなければfrom higuma import ...でimportできます。 インストール中の版はhiguma.__version__で確認できます。

Applicationとrouting

Higuma

Higuma(
    import_name,
    *,
    template_folder="templates",
    static_folder="static",
    static_url_path="/static",
    max_content_length=8 * 1024 * 1024,
    request_memory_limit=1024 * 1024,
    debug=False,
    openapi_url="/openapi.json",
    docs_url="/docs",
    lifespan=None,
)

主なmethod:

  • route(rule, *, methods=None, endpoint=None, response_model=None, status_code=None, ...)
  • get、post、put、patch、delete: routeのshortcut
  • add_url_rule(rule, *, endpoint, view_func, methods=None, ...)
  • websocket(rule, *, endpoint=None, allowed_origins=None)
  • register_blueprint(blueprint, *, url_prefix=None, name_prefix="", name=None)
  • cli.command(name=None, *, help=None)、test_cli_runner()
  • test_async_client(base_url="http://localhost", root_path="", timeout=5) / ASGITestClient
  • url_for(endpoint, **values)
  • before_request、after_request、middleware、errorhandler
  • teardown_request(func)、teardown_appcontext(func)、register_error_handler(code_or_exception, func)
  • app_context()、request_context(request)、test_request_context(path="/", **kwargs)
  • update_template_context(context)
  • on_startup、on_shutdown、context_processor
  • add_middleware(middleware, *args, **kwargs)
  • render_template、jsonify、make_response
  • mount_wsgi、mount_asgi
  • mount_static(prefix, directory, *, name="static_files", html=False, index_file="index.html", max_age=3600, immutable=False, headers=None)
  • mount_spa(prefix, directory, *, name="spa", index_file="index.html", api_prefixes=("/api",), asset_prefixes=("/assets",), max_age=3600, immutable=False, headers=None)
  • openapi()、clear_template_cache()、init_database()
  • test_client()
  • asgi_app: ASGI 3 callable property(0.8+)。HTTP・WS・lifespan
  • wsgi_app: WSGI callable property(0.8+)。HTTPのみ
  • run(host="127.0.0.1", port=8000, *, workers=0, processes=1, ...)

routeのOpenAPI optionはsummary、description、tags、responses、 request_body、response_model、status_code、operation_id、 include_in_schema、openapi_extraです。response_modelは実行時にも出力を検証・変換し、 宣言外fieldを除外します。status_codeは通常の戻り値やResponseだけでなく (body, headers) 2-tupleにも適用されます(明示的status付きtupleが優先)。 errorhandler/register_error_handler/middleware/add_middleware/register_blueprintや 各route・hook・mount登録APIは、不正なstatus code・非例外クラス・非callable・空のendpoint/name・ 非Blueprint引数を登録時に検証します。

current_appは処理中のHiguma、requestは処理中のRequestへのcontext-local proxyです。 request context外で参照するとRuntimeErrorになります。app.configは設定dictionary、 app.stateはlifespanで初期化した共有状態などに使えます。

StaticFiles / SPAFiles / ViteManifest(0.6.0以降)

mount_staticは登録したStaticFilesを、mount_spaはSPAFilesを返します。 root/pathのendpointは{name}_root・{name}_pathで、OpenAPIから除外します。 directoryは作業directory基準。prefixはliteralなroot-relative pathです。

StaticFiles(directory, *, html=False, index_file="index.html", max_age=3600,
            immutable=False, headers=None, check_dir=True)
SPAFiles(directory, *, index_file="index.html", api_prefixes=("/api",),
         asset_prefixes=("/assets",), max_age=3600, immutable=False, headers=None)
ViteManifest(path, *, base_url="/static/")

file helperはhelper(request, filename="")で呼べ、app mountを使うと通常のmiddleware・hooksも 適用されます。StaticFiles(check_dir=False)だけは起動時directory存在確認を遅延します。 直接helperを呼ぶだけではapp共通のconditional処理は実行されないため、通常はmount APIを使います。

Vite methodはasset_url(entry) -> str、entrypoint(entry) -> dict(file・css・imports)、 tags(entry, *, nonce=None) -> str(非空の文字列nonceのみ許可)、reload() -> Noneです。 全optionの動作・cache・予約prefix・エラー・security境界はfrontend guideを参照してください。

Blueprint(route group)

Blueprint(name, import_name, *, url_prefix="")はroute群をまとめます。route、HTTP shortcut、 websocketを持ち、register_blueprint()で登録します。

0.7.0からbefore_request(func)、after_request(func)、teardown_request(func)、 context_processor(func)、errorhandler(code_or_exception)、 register_error_handler(code_or_exception, func)も提供します。 Blueprint名は空文字とドットを禁止し、local endpointもドットを禁止します。 name_prefixはBlueprint名の前へそのまま連結します(区切りが必要なら"admin."等を指定)。 hookとerrorのscope・実行順はFlask互換性を参照してください。

Contextとrequest-local callback(0.7.0以降)

after_this_request(func)は現在のrequestだけのresponse callbackを登録し、同じ関数を返します。 request context外ではRuntimeErrorです。callbackはresponseを受け取りresponseを返します。 teardown_request(func)はcontext終了時、未処理例外またはNoneを受け取ります。 HTTPエラーや登録handlerで処理済みの例外では通常Noneです。 test_request_contextの構築引数と、Flaskとの違いはテストガイドを参照してください。

外部サーバー入口(0.8.0以降)

外部サーバーへの公開例・async実行モデル・設定・制約は ASGI・WSGIガイドを参照してください。

View / MethodView

View.as_view(name, *class_args, **class_kwargs)はclassをview functionへ変換します。 Viewではdispatch_request()を、MethodViewではget()、post()等を実装します。 MethodViewの許可methodは実装したmethod名から自動導出されます。 0.11.3以降はMethodViewの各HTTP methodおよびView.dispatch_request()でも型付きparameter (QueryParam、Body、Depends、BackgroundTasks等)の自動解決とmethod別OpenAPI schema生成に対応します。

型付き入力とdependency injection

typing.Annotatedでsourceと制約を宣言すると、handler実行前に値を取り出し、型へ変換します。

from typing import Annotated

from higuma import Body, Depends, Header, PathParam, QueryParam


def page_size(limit: Annotated[int, QueryParam(ge=1, le=100)] = 20):
    return limit


@app.post("/items/<uuid:item_id>", response_model=ItemOutput, status_code=201)
def create_item(
    item_id: Annotated[UUID, PathParam()],
    payload: Annotated[ItemInput, Body()],
    limit: Annotated[int, Depends(page_size)],
    trace_id: Annotated[str | None, Header("x-trace-id")] = None,
):
    ...
  • QueryParam、Header、Cookie、PathParam、Body、Form、FileはParameterの派生型です。
  • 共通optionはalias、title、description、deprecated、min_length、 max_length、pattern、ge、gt、le、lt(有限int/float/Decimal対応)です。
  • primitive、UUID、Decimal、date / datetime、Enum、Literal、union / optional、 collection、dataclass、TypedDictを再帰的に変換します。
  • list等にはrepeated query/form/file値を渡します。
  • Depends(callable, use_cache=True)は同期・非同期・yield dependencyを再帰解決します。 yield dependencyのcleanupはresponse bodyとbackground taskの完了後に逆順で実行されます。
  • app.dependency_overrides[dependency] = replacementでtest時に差し替えられます。
  • annotationなしのpath引数、Request、BackgroundTasksも自動注入できます。

入力不正はRequestValidationErrorとしてJSON 422になります。error detailにはloc、msg、 type、安全な場合だけinputが含まれます。password、token、secret、Cookie等の値はredactします。 出力がresponse_modelに適合しない場合はResponseValidationErrorとなり、clientには500を返します。

Request

Request

  • method、path、query_string、scheme、host、base_url、url
  • host_url、full_path、mimetype、is_json(0.7+)
  • root_path: decode済みmount prefix。scope: ASGI入力scope、他の経路ではNone(0.8+)
  • stream、iter_body(chunk_size=65536)、aiter_body(chunk_size=65536)、body_size、body_spooled(0.9+)
  • args / query: repeated keyを保持するMultiDict
  • values: GETではqueryのみ、それ以外はquery優先でformと統合(0.7+)
  • headers: case-insensitiveなHeaders
  • cookies: read-only mapping
  • json / get_json(force=False, silent=False, cache=True)
  • form、files、body、text、get_data(as_text=False)
  • path_params / view_args
  • client_addr / remote_addr
  • state、session、user
  • raw_headers: 重複を保持するbyte header pair

Headers / MultiDict

Headersはheader名をcase-insensitiveに扱います。MultiDictはget()、getlist()、 items(multi=False)、keys()、values()、to_dict(flat=True)を提供します。 重複keyの単一値は従来どおり最後の値です。Flaskの最初の値とは異なります。 request.valuesは入力元間ではquery優先で、getlist()はqueryとform両方を保持します。

UploadFile

filename、content_type、headers、field_name、sizeを持ち、read()、seek()、 getvalue()、save(destination)を使えます。secure_filename(filename, fallback="upload")は directory要素や危険な文字を除去します。一意名、拡張子、内容、quotaの検査はapplication側の責務です。

Response

基本response

  • Response(body=b"", status=200, headers=None, media_type=None, background=None)
  • HTMLResponse、PlainTextResponse、JSONResponse
  • RedirectResponse(location, status=302, ...)
  • TemplateResponse(template, context=None, ...)
  • FileResponse(path, *, filename=None, as_attachment=False, offset=0, length=None, ...)

full-fileのFileResponseとsend_file()はGET/HEADのETag、If-None-Match、single byte rangeを 自動処理し、通常ファイル以外(ディレクトリ等)や送信時の範囲不整合はPython・WSGI/ASGI・Rust全体で拒否します。明示的なoffset / lengthは指定範囲をそのままstreamします。

Responseはstatus_code / status、headers、media_type、body、historyを持ちます。 append_header()、get_json()、set_cookie()、delete_cookie()を提供します。 0.7.0から.data(読書き)、get_data(as_text=False)、set_data(str_or_bytes)、 is_json、get_json(force=False, silent=False)を使えます。buffered body用helperです。 get_json()/.jsonはJSON以外のMIMEでNone、解析失敗で例外を返します。 force=TrueでMIMEを無視、silent=Trueで解析失敗をNoneにします。 stream/file/templateの遅延内容を直接body helperで読み出すAPIではありません。 set_cookie(..., max_age=...)は整数秒またはdatetime.timedeltaを受け付け、partitioned=TrueはPython 3.14以降かつsecure=Trueで利用できます。

helperはjsonify()、make_response()、redirect()、render_template()、send_file()です。 handlerはresponseに加え、文字列、bytes-like、JSON化可能値、None、 (body, status[, headers])を返せます。dataclass、enum、UUID、Decimal、日付等はJSONおよび render_template()のテンプレートコンテキストへ構造化データとして変換されます。

Streaming / SSE

StreamingResponse(content, *, media_type=..., content_length=None, background=None)は同期・非同期 iterableから1 chunkずつ送ります。chunkはstrまたはbytes-likeです。作成時のrequest contextは stream完了まで保持されます。既知の場合だけcontent_lengthを指定してください。

EventSourceResponse(content, ...)はSSE responseです。値を直接渡すか、 ServerSentEvent(data, event=None, id=None, retry=None, comment=None)でfieldを指定します。 SSEにはtext/event-stream、Cache-Control: no-cache、buffering抑止headerが自動設定され、 gzip対象から除外されます。

Background task

0.11.1以降ではResponse(..., background=async_callback)やresponse.background = async_callbackの 直接指定もawaitし、設定時のcontextを保持します。 streamの正常終了・HEAD・途中切断・after hookによるresponse差替ではiteratorとclose可能なstream本体を閉じ、 その後backgroundとリソース解放を実行します。 ASGIの応答完了後の切断通知はbackgroundやObservabilityの完了記録を中断しません。 組み込みサーバーで切断時にPython iteratorの呼び出しが実行中なら、その終了後に後処理します。 協調しないblocking処理の強制停止や、プロセス強制終了後の実行保証ではありません。

BackgroundTask(func, *args, **kwargs)はresponse body送信後に同期・非同期callableを実行します。 BackgroundTasksはadd_task()で複数登録でき、handler引数へも自動注入できます。登録順に実行し、 task登録時のrequest contextを保持します。失敗後のtaskは実行されません。重い処理、再試行や永続性が 必要な処理にはjob queueを使ってください。

Lifecycle、middleware、session

Higuma(..., lifespan=context_manager)はworker開始時にenterし、停止時にexitします。同期・非同期 context managerを使え、yieldしたmappingはapp.stateへmergeされます。従来のon_startup / on_shutdownも同じlifecycle内で実行されます。testではwith app.test_client() as client:を使うと lifecycleを実行します。

  • SessionMiddleware(secret_key, *, cookie_name="higuma_session", max_age=..., secure=False, ...)
  • Session: dict互換でpermanent、modifiedを管理
  • CORSMiddleware
  • SecurityHeadersMiddleware
  • TrustedHostMiddleware
  • ProxyHeadersMiddleware(trusted_proxies=("127.0.0.1", "::1"))
  • RateLimitMiddleware(limit=100, window=60.0, *, key=None, max_keys=10000)

proxy headerは直接接続元がtrusted_proxiesに含まれる場合だけ信頼してください。

WebSocket

WebSocketはsend()、send_text()、send_bytes()、send_json()、receive()、 receive_text()、receive_bytes()、receive_json()、close()を提供します。切断は WebSocketDisconnect(code=1000, reason="")です。routeのallowed_originsを省略すると same-originだけを許可します。

0.8.0からasync handlerではawait ws.asend_text/asend_bytes/asend_json(...)、 await ws.areceive/areceive_text/areceive_bytes/areceive_json()、 await ws.aclose(code=1000, reason="")を使えます。組み込みとASGIの両方で対応します。 ASGI loop上で同期WS methodを直接呼び出してはいけません。

SQLite ORM

  • Database(url="sqlite:///higuma.db"): connect()、close()、create_all()、drop_all()、session()
  • Model(**values): to_dict()
  • DatabaseSession: add()、save()、delete()、query()、execute()、commit()、rollback()
  • Query: get()、filter_by()、order_by()、offset()、limit()、first()、all()、 count()、delete()、delete_all()
  • field: Field、Integer、Float、String、Boolean、Date、DateTime、Blob

fieldの共通optionはprimary_key、nullable、unique、default、indexです。 Integerはautoincrement、Stringはlengthも受けます。Query.delete()はfilterなしの全件削除を 拒否し、field未定義のModelに対するcreate_all()/QueryはTypeErrorになります。組み込みORMはSQLite用の小さな同期data mapperです。

認証とsecurity

  • AuthManager: load_user()、login_user()、logout_user()、confirm_login()と認証decorator
  • current_user / AnonymousUser
  • login_required、fresh_login_required、roles_required、permissions_required
  • PasswordHasher: scryptのhash()、verify()、needs_rehash()
  • TokenSigner: dumps()、loads(max_age=None)
  • CSRFProtection / csrf_token(field_name=None)
  • OAuth2Client: google()、line()、discord()、authorization_url()、fetch_token()、 userinfo()、validate_state()。state、PKCE、OIDC nonceをsessionで管理
  • generate_user_id(prefix="usr", entropy_bytes=18) / validate_user_id()

例外と運用

abort(status_code, detail=None, headers=None)または次のHTTPException派生型をraiseできます。

BadRequest、Unauthorized、Forbidden、NotFound、MethodNotAllowed、Conflict、 RequestEntityTooLarge、UnsupportedMediaType、RangeNotSatisfiable、TooManyRequests、 InternalServerError。

Supervisor(app, *, host="127.0.0.1", port=8000, processes=2, ...)は複数worker process、 health check、restart上限を管理します。通常はapp.run(processes=..., app_ref="module:app")または CLIから利用します。

実行コードはExamplesと リポジトリのexamplesを参照してください。