1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonでマイクロサービスの作成

Last updated at Posted at 2021-11-24

#準備
Python環境の用意→インストールはこちらから
Flaskのインストール

$ pip install flask

sqlachemyのインストール

$ pip install sqlachemy

requestsのインストール

$ pip install requests

DBの用意(今回はSQLite3)

#実行環境
MacOS 11.4
Python 3.9.0
SQLite 3.32.3
requests 2.24.0
sqlachemy 1.4.26
Flask 2.0.2

#webサーバーを立てる
今回は, ブラウザ上で選択したアイテムの値段を計算するwebサイトをマイクロサービスアーキテクチャもどきで作成する.
今回の機能としては以下の2つ
①dbに登録されている商品と値段を表示する
②選択した商品のみの表示

main.py
import json
import os

from flask import Flask, render_template, request
import requests

from orders_models import Order, new_Order

app = Flask(__name__, template_folder='templates')


@app.route("/")
def main():
    all_item = Order.query.all() //Order.dbの全テーブルの全アイテムを取得
    return render_template("index.html", all_item=all_item) //index.htmlにOrder.dbの中身を送る

@app.route("/add", methods=["post"])
def show():
    url = 'http://loaclhost/order' //app.pyのURL
    id_list = request.form.getlist("add") //htmlからaddメソッドを受け取る
    for id in id_list: 
        payload = int(id) 
        requests.post(url=url, json=json.dumps(payload)) //データ部にidを格納してapp.pyに送る
    all_item = new_Order.query.all() //new_Orderテーブル内の全アイテムを取得
    return render_template("index.html", all_item=all_item)


if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=80)
app.py
import json
import os

from flask import Flask, render_template, request
from sqlalchemy.ext.asyncio import session
from sqlalchemy.orm import scoped_session, sessionmaker

from database import db_session
from orders_models import Order, new_Order

app = Flask(__name__, template_folder='templates')

@app.route("/order", methods=["post"])
def item():
    data = json.loads(request.json) 
    content = Order.query.filter_by(id=data).first() //idが一致するデータを取り出す
    i = new_Order(name=content.name, price=content.price) //dbの更新
    db_session.add(i)
    db_session.commit()

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=81)
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>order.net</title>
    </head>
         <h1>メニュー表</h1>
        {% for item in all_item %}
        <div>
            <input type="checkbox" name="add" form="add" value={{item.id}}>
            {{item.name}}:{{item.price}}
        </div>
        {% endfor %}
    <form action="/add" method="post" id="add">
        <input type="submit"  value="買い物かごに追加する">
    </form>
    </body>
</html>

#実際に動かしてみた
demo.gif

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?