[入力->サーバーで任意処理->返信を表示]するアプリ開発
本記事のコマンドはMacに対応しています
Windowsの場合はpython3, pip3をpython, pipに置き換えてください(3を削除)
環境構築編はこちら--->その1
1. はじめに
このプロジェクトではVue.jsとFlaskを使用してシンプルなWebアプリを作成します。今回はFlaskサーバーで任意の処理を行い結果をVue.jsで表示するアプリを作成することで、より汎用性のあるプログラムの実装を学びます。
学習目標
- Flaskでの任意処理の方法を理解する
- Vue.jsで複数のアイテムを利用する方法を理解する
- 本例に留まらないアプリの開発が可能になる
2. コードの変更
以下のコードを変更します
- Flaskのコード(app.py)
- Vue.jsのコード(App.vue)
1. Flaskのコード(app.py)の変更
既存のコードを以下の様に変更してください
app.py
from flask import Flask, jsonify, request
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # CORSを有効にする
@app.route('/api/message', methods=['POST'])
def message():
data = request.json # JSONデータを受け取る
text = data.get('text', '') # 'text'キーの値を取得
response_text = text + "-Return-" # テキストに"-Return-"を追加
return jsonify({"message": response_text})
if __name__ == '__main__':
app.run(debug=True)
2. Vue.jsのコード(App.vue)
既存のコードを以下の様に変更してください
App.vue
<template>
<div id="app">
<input v-model="inputText" placeholder="Enter text here" class="text-input" />
<div class="button-container">
<button @click="sendMessage" class="send-button">Send</button>
</div>
<p :class="{'response-box': true, 'placeholder-text': responseMessage === 'Return message here'}">
{{ responseMessage }}
</p>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'App',
data() {
return {
inputText: '', // ユーザーが入力するテキスト
responseMessage: 'Return message here' // 初期メッセージを設定
};
},
methods: {
sendMessage() {
// 入力されたテキストをサーバーに送信
axios.post('http://127.0.0.1:5000/api/message', { text: this.inputText })
.then(response => {
// サーバーからの返信を表示スペースに表示
this.responseMessage = response.data.message;
})
.catch(error => {
console.error("There was an error!", error);
});
}
}
};
</script>
<style>
.text-input {
width: 100%; /* 横幅を100%に設定 */
height: 50px; /* 高さを50pxに設定 */
font-size: 16px; /* フォントサイズを大きくする */
padding: 10px; /* パディングを追加して内側の余白を確保 */
box-sizing: border-box; /* パディングを含めてサイズを計算 */
margin-bottom: 20px; /* テキスト入力欄の下にスペースを追加 */
}
.button-container {
text-align: center; /* ボタンを中央に配置 */
}
.send-button {
width: 150px; /* ボタンの幅 */
height: 50px; /* ボタンの高さ */
font-size: 16px; /* ボタンのテキストサイズ */
background-color: #4CAF50; /* ボタンの背景色 */
color: white; /* ボタンのテキスト色 */
border: none; /* ボーダーを非表示 */
border-radius: 5px; /* ボタンの角を丸める */
cursor: pointer; /* カーソルをポインタに変更 */
}
.send-button:hover {
background-color: #45a049; /* ホバー時の背景色 */
}
.response-box {
background-color: #f1f1f1; /* 背景色を設定 */
padding: 15px; /* 内側の余白を追加 */
margin-top: 20px; /* 上部にマージンを追加 */
border-radius: 5px; /* 角を丸める */
border: 1px solid #ccc; /* 薄いボーダーを追加 */
min-height: 50px; /* 最低限の高さを設定 */
color: #333; /* 通常の文字色を濃いグレーに設定 */
}
.placeholder-text {
color: #aaa; /* 初期メッセージの文字色を薄い灰色に設定 */
}
</style>
3. 起動と確認
1. 仮想環境の有効化
プロジェクトフォルダに移動して以下のコマンドを実行します
Mac
source venv/bin/activate
Windows
venv/bin/activate
以下のように、先頭に(venv)が表示されれば成功です
(venv) hoge@hoge %
2. Flaskを起動します
cd /move/to/app.pyFolder
python3 app.py
3. Vueを起動します
別のコマンドプロンプト or ターミナルを開いて実行してください
cd /move/to/vue-project/src
npm run dev
表示されたURLをコピーし、ブラウザでアクセスします
以下の画像のように表示されれば成功です!
実際にテキストを入力して送信し、返信が表示されることを確認しましょう!