pip install nexom
まずは「HTML を返すルート」を 1 本作るのが最速です。
from nexom.web.path import Path, Pathlib
from nexom.web.response import HtmlResponse
def index(request, args):
return HtmlResponse("<h1>Hello Nexom</h1>")
routing = Pathlib(
Path("", index, "index"),
)
ポイント: Nexom の handler は (request, args) を受け取って Response(または HtmlResponse/JsonResponse)を返すのが基本です。
from nexom.web.path import Path, Pathlib
routing = Pathlib(
Path("", index, "index"),
Path("doc/", docs, "docs"),
)
user/{id} のように書くと、URL の該当部分が args に入ります。
from nexom.web.response import HtmlResponse
def user(request, args):
return HtmlResponse(f"<p>User ID: {args['id']}</p>")
Path("user/{id}", user, "user")
Static を使うと、ディレクトリ配下のファイルを配信できます。
from nexom.web.path import Static
Static("static/", "./static", "static_files")
/static/xxx を ./static/xxx にマップして配信します。../)はフレームワーク側でブロックする設計です。from nexom.web.response import HtmlResponse
return HtmlResponse("<h1>OK</h1>")
from nexom.web.response import JsonResponse
return JsonResponse({"ok": True, "message": "hello"})
高度なことをしたい場合は Response を直接使います。
from nexom.web.response import Response
# バイナリや任意 Content-Type を返す
return Response(
b"binary",
content_type="application/octet-stream",
)
from nexom.web.response import Redirect
return Redirect("/to")
標準のエラーページテンプレートから HTML を生成します。
from nexom.web.response import ErrorResponse
return ErrorResponse(404, "Not Found")
str の body を返すときに charset で encode します。HtmlResponse / JsonResponse は “短く書ける” 方向で、UTF-8 を前提に使える設計です。
Nexom のテンプレートは「最小機能で予測可能」に寄せた独自構文です。
<h1>{{ title }}</h1>
<Extends base />
<Insert main>
<h1>Hello</h1>
</Insert>
<Import header />
from nexom.web.template import Templates
templates = Templates("./templates", "default", "document")
html = templates.default(title="Nexom")
return HtmlResponse(html)
python -m nexom test
python -m nexom build-server myapp
生成されるプロジェクトには以下が含まれます(構成はバージョンにより変わる場合があります)。
HtmlResponse / JsonResponse を使うResponse で headers / content-type を直接制御handler 内で複雑化しそうなら、関数を分けて「処理の塊」を小さくするのが Nexom と相性良いです。
公開運用を想定するなら、最低限この3つのテストを用意すると安心です。