3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flask で JSON ファイルを読む

Last updated at Posted at 2017-06-14

次のプログラムの入力ソースを、MariaDB から JSON に変更。

flask で MariaDB を使う

フォルダー構成

$ tree
.
├── data
│   └── cities.json
├── json_read.py
└── templates
    ├── hello.html
    └── layout.html
json_read.py
# --------------------------------------------------------------------
#	json_read.py
#
#						May/10/2019
#
# --------------------------------------------------------------------
from flask import Flask, render_template
import sys
import json

app = Flask(__name__)

@app.route('/')
def hello():
	name = "皆さんこんにちは"
	return name


@app.route('/json_pp')
def json_pp():
	file_json = "data/cities.json"
	fp_in = open (file_json,encoding='utf-8')
	json_str = fp_in.read()
	fp_in.close()
	dict_aa = json.loads(json_str)
#
	rows = []
	for key in sorted (dict_aa.keys()):
		unit = dict_aa[key]
		unit['id'] = key
		rows.append(unit)
#
	return render_template('hello.html', title='json', cities=rows)

#
if __name__ == "__main__":
	app.run(host='0.0.0.0',debug=True)
# --------------------------------------------------------------------
data/cities.json
{
  "t0921": {
    "name": "宇都宮",
    "population": 41295,
    "date_mod": "2003-8-12"
  },
  "t0922": {
    "name": "小山",
    "population": 38756,
    "date_mod": "2003-5-15"
  },
  "t0923": {
    "name": "佐野",
    "population": 71294,
    "date_mod": "2003-6-8"
  },
  "t0924": {
    "name": "足利",
    "population": 27138,
    "date_mod": "2003-7-21"
  },
  "t0925": {
    "name": "日光",
    "population": 74682,
    "date_mod": "2003-4-19"
  },
  "t0926": {
    "name": "下野",
    "population": 82951,
    "date_mod": "2003-10-14"
  }
}

サーバー起動

python json_read.py

クライアント

http://localhost:5000/json_pp

にアクセスする。

image.png

確認したバージョン

$ flask --version
Python 3.12.3
Flask 3.0.2
Werkzeug 3.0.1
3
6
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
3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?