商品やサービスを提供しようとしたとき、あるいは単に価格を異なる通貨で表示したいと思ったことはありませんか?その場合、最新かつ正確な為替レートを提供することがいかに困難であるかはご存知の通りです。
そこで登場するのが、為替APIです。
為替APIは、為替レートの変換を処理するのに役立ちます。
この例では、Flaskウェブフレームワークとフロントエンドのスタイリングのための少しのJavascriptを使用して、あなた自身の通貨コンバータを構築できるように、通貨APIをシンプルなPythonアプリケーションに統合する方法を見ていきます。
Python で通貨換算器を作成するためのステップバイステップガイド
まず、開発スタックをセットアップします。
- Python 3 (> 3.7)
- Flask
- Javascript (Node)
- Yarn (npm install -global yarn)
- Vite
- Tailwind CSS
- postcss
- autoprefixer
- 無料currencyapi.com APIキー
ステップ1:I
ステップ2: スタイリングの設定 (オプション)
スタイリングは任意ですが、このステップを踏む場合は、Tailwind CSSの使用をお勧めします。
Autoprefixer & postcssを使用すると、さらにスムーズな開発が可能になります。
そのため、これらのパッケージをインストールする必要があります。
yarn create vite currency-converter --template vanilla |
ここで、tailwindを初期化します。
設定ファイル(tailwind.config.js)を作成します。
yarn add -D tailwindcss postcss autoprefixer |
この新しく作成された設定ファイルを、Viteプロジェクトの設定に合わせる必要があります。
npx tailwindcss init |
Tailwind CSSをインクルードするには、style.cssの先頭に以下の行を追加してください。
module.exports = { content: [
'./main.js',
'./index.html',
],
theme: {
extend: {},
},
plugins: [],
} |
次に、postcss のルートディレクトリに postcss.config.js という名前の設定ファイルを作成する必要があります。
そこで、以下のように追加します。
@tailwind base;@tailwind components;@tailwind utilities; |
ステップ3: vite の起動
ホットリロードでファイルを提供するために、viteをdevモードで起動します。
module.exports = { plugins: [
require('tailwindcss'),
require('autoprefixer')
]
} |
ステップ4:HTMLを準備する
次に、デフォルトのランディングページを適応させたいと思います。
そのために、index.htmlを開き、フォームを作成します。
以下の要素が必要です。
- 入力用のラッパー t
- 基本通貨を入力するためのもの。 * 基本通貨の入力
- ベースとなる通貨の選択
- 送信ボタン
- レスポンスコンテナ
index.htmlの実装はこんな感じです。
yarn devステップ5: JavaScriptでフォーム送信を処理する
main.jsで、通貨の量 (
base_currency_input) と通貨 (base_currency) をバックエンドに送ります。レスポンスとして、すべての通貨のリストと対応する値を受け取ります。
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"/><linkrel="icon"type="image/svg+xml"href="favicon.svg"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><title>Currency converter example</title></head><bodyclass="bg-gradient-to-b from-cyan-800 to-slate-800 min-h-screen py-5"><formid="currency_converter"class="mx-auto w-full max-w-sm bg-white shadow rounded-md p-5 space-y-3 text-sm"><divclass="flex items-center space-x-5"><labelfor="base_currency_input">Amount:</label><inputtype="tel"id="base_currency_input"name="base_currency_input"placeholder="1"value=""class="grow border-slate-300 border rounded-md py-2 px-4 text-sm"required /></div><divclass="flex items-center space-x-5"><labelfor="currency">Currency:</label><selectname="currency"id="currency"class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"><optionselectedvalue="USD">USD</option><optionvalue="EUR">EUR</option><optionvalue="CHF">CHF</option></select></div><buttontype="submit"class="bg-slate-800 text-white rounded-md py-2 px-4 mx-auto relative block w-full">Convert</button></form><divid="result"class="mx-auto my-5 w-full max-w-sm bg-white shadow rounded-md relative overflow-hidden text-sm empty:hidden divide-y divide-dotted divide-slate-300"></div><scripttype="module"src="/main.js"></script></body></html>ステップ6: バックエンドアプリケーションの準備
カレンシーコンバーター」フォルダーの中に、「backend-application」フォルダーを作成します。
注意: このコマンドはmacOS/Linuxで有効ですが、Windowsではこちらをご覧ください。
import'./style.css'const currencyConverter = document.getElementById('currency_converter');const baseCurrencyInput = document.getElementById('base_currency_input');const baseCurrency = document.getElementById('currency');const resultContainer = document.getElementById('result');currencyConverter.addEventListener('submit', (e) => {e.preventDefault();fetch(`http://localhost:6001/convert?` + new URLSearchParams({ 'base_currency_input': baseCurrencyInput.value, 'currency': baseCurrency.value })).then(response => response.json()).then(data => {varresult ='<div class="space-y-1 px-5 py-3 border-2 rounded-md">';for(letentry of data) {result += `<divclass="flex items-baseline justify-between"><spanclass="font-medium">${entry.code}:</span><span>${entry.value}</span></div>`;}resultContainer.innerHTML = result;});});ステップ7:バックエンドアプリの作成
最後のステップでは、
main.pyという新しいファイルを追加するだけです。mkdir backend-applicationcd backend-applicationpython3 –m venv venv. venv/bin/activatepip install Flask currencyapicomいくつかの簡単なコマンドで、アプリケーションを実行できます(他のアプリケーションとの競合を避けるために、ポートを6001にバインドしています)。
fromflaskimportFlask, request, jsonifyfromcurrencyapicomimportClientfromconfigimportCURRENCYAPI_KEYapp=Flask(__name__)@app.route("/convert", methods=['GET'])defconvert():currency_input=request.args.get('base_currency_input', '')currency=request.args.get('currency','USD')ifcurrency_inputandcurrencyin['USD','EUR','CHF']:api_client=Client(CURRENCYAPI_KEY)response=api_client.latest(currency)response=jsonify([{'value': response['data'][x]['value']*float(currency_input),'code': x}forxinresponse['data'].keys()])response.headers.add("Access-Control-Allow-Origin","*")returnresponse最後のステップでは、currencyapi.com の API キーを含む
config.pyファイルを作成する必要があります。APIキーは無料で入手でき、ドキュメントでAPIについて詳しく知ることができます。
以上です。
最新で正確な
With these few steps, you can now build your own currency converter using Python and display accurate and up-to-date prices in different currencies. There are many use cases for a currency converter; whether you use it for e-commerce stores, analytics, or spreadsheets, we hope this tutorial will guide you through the process.
この記事もチェック:Pythonのコマンドライン引数でargparseやgetoptを使う方法