この記事では、PythonのWebフレームワークであるFlaskとJavaScriptのFetch APIを用いて、猫の画像を取得するシンプルなWebアプリケーションの開発について説明します。

FlaskとFetch APIの基本

まず、FlaskとFetch APIの基本について説明します。FlaskはPythonで書かれた軽量なWebフレームワークで、シンプルながら強力な機能を持っています。一方、Fetch APIはJavaScriptで利用できるWeb APIの一つで、非同期通信を行うことができます。

アプリケーションの構成

このアプリケーションは、Flaskで作成したサーバーと、Fetch APIを用いてサーバーと通信するクライアントから構成されます。

サーバー側のコードは以下のようになります。

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('hello.html')

if __name__ == "__main__":
    app.run(debug=True)

クライアント側のコードは以下のようになります。

const url = 'https://api.thecatapi.com/v1/images/search?size=full';
const options = { method: 'GET' }

function getCatImage(url, options){
    return fetch(url, options)
    .then( response => response.json() );
}

async function getImage(url, options){
    const response = await getCatImage(url, options);
    const imageDiv = document.getElementById("image");
    const imageElement = document.createElement("img");
    imageElement.src = response[0].url;
    imageElement.className = "w300";
    imageDiv.appendChild(imageElement);
}

document.getElementById("lookCatButton")
.addEventListener("click", () =>{
    getImage(url, options)
})

まとめ

この記事では、PythonのFlaskとJavaScriptのFetch APIを用いて、猫の画像を取得するシンプルなWebアプリケーションの開発方法について説明しました。これらの技術を組み合わせることで、動的なWebアプリケーションを効率的に開発することが可能です。.

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です