🔖

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

2024/06/30に公開

pip でインストールする

pip install granian

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

granian --interface asgi --port 8000 main:app

main.py の内容は次のとおり

async def app(scope, receive, send):
    assert scope['type'] == 'http'

    await send({
        'type': 'http.response.start',
        'status': 200,
        'headers': [
            [b'content-type', b'text/plain'],
        ],
    })
    await send({
        'type': 'http.response.body',
        'body': b'Hello, world!',
    })
and serve it:

http://localhost:8000 にブラウザーでアクセスできるようになる。デフォルトのポートは 8000 である。

SSL/TLS 対応にするには自己署名の証明書を読み込ませる

granian --interface asgi --port 8000 --ssl-certificate localhost.pem --ssl-keyfile localhost-key.pem 
 main:app

自己署名の証明書は mkcert で生成した

mkcert localhost

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 0x56346f355c80)
> 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
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* old SSL session ID is stale, removing
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* old SSL session ID is stale, removing
< HTTP/2 200 
< server: granian
< content-type: text/plain
< date: Sat, 29 Jun 2024 18:34:36 GMT
< content-length: 13
< 
* Connection #0 to host localhost left intact
Hello, world!

Discussion