🙌

【Python】HTTP/2 対応 サーバーの Hypercorn を使う

2024/06/30に公開

pip でインストールする

pip install hypercorn

HTTP サーバーの起動は次のとおり

hypercorn hello:app
hello.py
async def app(scope, receive, send):
    if scope["type"] != "http":
        raise Exception("Only the HTTP protocol is supported")

    await send({
        'type': 'http.response.start',
        'status': 200,
        'headers': [
            (b'content-type', b'text/plain'),
            (b'content-length', b'5'),
        ],
    })
    await send({
        'type': 'http.response.body',
        'body': b'hello',
    })

起動時に自己署名証明書を指定すれば TLS 対応になる

hypercorn --certfile localhost.pem --keyfile localhost-key.pem hello:app

curl でリクエストを送信すると HTTP/2 対応であることがわかる

curl -v https://localhost:8000/
*   Trying 127.0.0.1:8000...
* Connected to localhost (127.0.0.1) port 8000 (#0)
* ALPN: offers h2,http/1.1
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
*  CAfile: /etc/ssl/certs/ca-certificates.crt
*  CApath: /etc/ssl/certs
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.3 (IN), TLS handshake, CERT verify (15):
* TLSv1.3 (IN), TLS handshake, Finished (20):
* TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.3 (OUT), TLS handshake, Finished (20):
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
* ALPN: server accepted h2
* Server certificate:
*  subject: O=mkcert development certificate; OU=masakielastic@penguin
*  start date: Jun 29 18:19:32 2024 GMT
*  expire date: Sep 29 18:19:32 2026 GMT
*  subjectAltName: host "localhost" matched cert's "localhost"
*  issuer: O=mkcert development CA; OU=masakielastic@penguin; CN=mkcert masakielastic@penguin
*  SSL certificate verify ok.
* using HTTP/2
* h2h3 [:method: GET]
* h2h3 [:path: /]
* h2h3 [:scheme: https]
* h2h3 [:authority: localhost:8000]
* h2h3 [user-agent: curl/7.88.1]
* h2h3 [accept: */*]
* Using Stream ID: 1 (easy handle 0x557c1c67dc80)
> GET / HTTP/2
> Host: localhost:8000
> user-agent: curl/7.88.1
> accept: */*
> 
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* old SSL session ID is stale, removing
< HTTP/2 200 
< content-type: text/plain
< content-length: 5
< date: Sat, 29 Jun 2024 18:46:00 GMT
< server: hypercorn-h2
< 
* Connection #0 to host localhost left intact
hello

Discussion