0
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 5 years have passed since last update.

flask-sqlalchemyでデジタルサイネージを作りたい

Last updated at Posted at 2019-03-19

目的

  • DB読み込み結果をflaskで表示
  • 2レコード取得する
  • 参考サイトのサンプルを改変
  • cssは使わない
  • android(termux)でテスト
  • windowsやraspiとはちがうかも
  • 更新機能を追加した

構成

│  app3svr.py
│  app3db.py ...事前にDB作成する用のpy
├─ templates
│  └─ app3.html
└─ static ...空

結果

イメージです。

Hello,Alchemy World!

[submit]
+------+
|world |
+------+
|hello |
+------+

app3svr.py

#svr.py

from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy 

app = Flask(__name__)

# DB設定
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app3.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)


# db.Model を継承して Word クラスを定義
class Word(db.Model):
	__tablename__ = 'words'
	id = db.Column(db.Integer, primary_key=True)
	word = db.Column(db.String(10))

	def __init__(self, id , word):
		self.id = id
		self.word = word


@app.route("/" , methods=["GET", "POST"])
def hello():

	if request.method == "GET":
		# wordsをid降順で取得
		words = Word.query.order_by(Word.id.desc()).all()
	
		# テンプレートにwordsを渡す
		return render_template('app3.html', words=words)

	if request.method == "POST":
		# cell:a1が更新ありかチェック
		row = Word.query.get(1)
		if request.form["cola1"] != row.word :
			row.word = request.form["cola1"]
			db.session.commit() 
		# cell:a2が更新ありかチェック
		row = Word.query.get(2)
		if request.form["cola2"] != row.word :
			row.word = request.form["cola2"]
			db.session.commit() 
		
		# 再表示
		# wordsをid降順で取得
		words = Word.query.order_by(Word.id.desc()).all()
		# テンプレートにwordsを渡す
		return render_template('app3.html', words=words)


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

app3.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Hello,Alchemy World!</title>
</head>
<body>
  <div>
    <h1>Hello,Alchemy World! </h1>
    <!-- ul でwordsを表示 -->
    <form method="post" action="/">
    <input type="submit" >
    <table border="1">
    <!-- 配列 words の件数分、li の表示を繰り返す -->
    {% for worddata in words %}
      <tr>
      <td> 
      <input type="text" name="cola{{ worddata.id }}" value="{{ worddata.word }}"> 
      </td>
      </tr>
    {% endfor %}
    </table>
    </form>
  </div>
</body>
</html>

app3db.py

from app3svr import db, Word

# テーブル作成
db.create_all()

# word のリストを作成
word_list = [(1,'hello'),(2,'world')]
words = [Word(d[0],d[1]) for d in word_list]

# 複数行インサート
db.session.add_all(words)
db.session.commit()

参考

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