0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GitHub Copilotに助けられた話

Posted at

FastAPI触ってみっか、でいじり始めました。
あっちなみにWeb系ガチ初心者なので。やめてくださいね。いろいろ。

流れ

よ~し簡単なログイン画面っぽいの作るか~。

FastAPIだけで出来んのか?わかんねググろ。

う~んなんかよくワカンネ。まあおそらく単体だと出来ねぇんだろ。

Copilotく~ん、ヘルプミ~。


以下全文
質問:FastAPIで入力フォームを作るコードを書いてください

返答:

FastAPIで入力フォームを作成するには、fastapiとjinja2テンプレートエンジンを使用します。以下に、基本的な入力フォームを作成するコード例を示します。

まず、必要なライブラリをインストールします。

pip install fastapi uvicorn jinja2

次に、以下のようにFastAPIアプリケーションを作成します。

from fastapi import FastAPI, Form
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.requests import Request

app = FastAPI()

templates = Jinja2Templates(directory="templates")

@app.get("/", response_class=HTMLResponse)
async def read_form(request: Request):
    return templates.TemplateResponse("form.html", {"request": request})

@app.post("/submit")
async def handle_form(username: str = Form(...), password: str = Form(...)):
    return {"username": username, "password": password}

次に、templatesディレクトリを作成し、その中にform.htmlという名前のテンプレートファイルを作成します。

<!DOCTYPE html>
<html>
<head>
    <title>Input Form</title>
</head>
<body>
    <h1>Input Form</h1>
    <form action="/submit" method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username"><br><br>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

このコードでは、/エンドポイントにGETリクエストが来たときに、form.htmlテンプレートをレンダリングして入力フォームを表示します。フォームが送信されると、/submitエンドポイントにPOSTリクエストが送信され、フォームのデータが処理されます。

最後に、以下のコマンドでFastAPIアプリケーションを起動します。

uvicorn main:app --reload

これで、ブラウザで http://127.0.0.1:8000 にアクセスすると、入力フォームが表示され、フォームを送信するとデータが処理されることを確認できます。


もう全部やってくれる。アタシ要るこれ?

HTML必要なのかふんふん、ルーティングってこんな感じなのねふんふん、GetとかPostっていうのがあるのねふんふん、あなたトトロっていうのねふんふん。

という感じで、一から十(過言)までお膳立てしてくれるお陰で勉強がはかどります。

ちょっとしたコード追加をするときも予測して候補をあげてくれるので、タイピングが50%以下で済むのもありがたいです。

思う存分使い倒してやりましょう。AIに労基ってないよね?(暗黒微笑)

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?