flask で firefox の指定ページを起動する

dicom ファイルを閲覧する flask は動きますが、firefox を起動していちいち localhost : 5000 にアクセスするのは面倒です。

flask で firefox の指定ページを起動できれば便利ですが、ネット検索してやっとわかりました。

flask プログラム


from flask import Flask, render_template
import threading,webbrowser

app = Flask(__name__)

@app.route('/')
def topPage():
    return render_template('top.html')
 
if __name__ == "__main__": 
    threading.Timer(1.0, lambda: webbrowser.open('http://localhost:5000') ).start()
    app.run(debug=False)

top.html

<html>
<body>
<h2>This is top-page</h2>
</body>
</html>

シェルスクリプト


#!/bin/bash

cd ~/flask
python dcm.py

このシェルスクリプトに実行権限を与えて実行すれば、自動的に top.html が表示されます。

動的ページを開くと 2 つ起動される

静的な top.html を起動する場合には起動されるのは 1 つなのですが、データベースで抽出したデータを貼り付けるようなページを自動的に開こうとすると、firefox が 2 つ起動されてしまいます。

例えば以下のようにすると、


from flask import Flask, render_template, redirect
import pymysql
import threading,webbrowser

app = Flask(__name__)

@app.route('/')
def dirlist():
    db = pymysql.connect(
            host='192.168.0.102',
            user='heno',
            password='moheno',
            db='pydcmdb',
            charset='utf8',
            cursorclass=pymysql.cursors.DictCursor,
        )
    cur = db.cursor()
    sql = "SELECT * FROM taginfo;";
    cur.execute(sql)
    mbrs = cur.fetchall()
    cur.close()
    db.close()
    return render_template('select.html', title='flask test', mbrs=mbrs)

if __name__ == "__main__":
    threading.Timer(1.0, lambda: webbrowser.open('http://localhost:5000') ).start()
    app.run(debug=True)

select.html が最初に起動されて、その後で同じ画面がもう一つ起動されます。

何だかよくわかりませんが、top ページは静的に作ればいいのでそうします。