概要
flask + pandas
を使っていて、
flask のエンドポイントの中でプロットをしてそれを保存したいだけだったのですが、
Terminating app due to uncaught exception
'NSInternalInconsistencyException',
reason: 'NSWindow drag regions should only be invalidated on the Main Thread!
となって落ちたときの備忘録を書きます。
TLDR
ここを見るだけでした。
flask のメイン関数を書いている python ファイルに、
import matplotlib
matplotlib.use('agg')
を追記するだけでした。
1分でできる再現方法
test.py
from flask import Flask, request
import numpy as np
import pandas as pd
app = Flask(__name__)
@app.route('/')
def index():
tmp = (np.random.rand(100)*100).tolist()
tmp2 = map(int, tmp)
df = pd.DataFrame(tmp2, columns=["age"])
df.plot.hist(bins=5).figure.savefig('static/tmp.png')
return "hello, world"
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=8000)
を
python test.py
で立ち上げた後、
curl localhost:8000
をすると、私の環境で(MacOS)
Terminating app due to uncaught exception
'NSInternalInconsistencyException',
reason: 'NSWindow drag regions should only be invalidated on the Main Thread!
となりました。
解決策
test.py
from flask import Flask, request
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('agg')
app = Flask(__name__)
@app.route('/')
def index():
tmp = (np.random.rand(100)*100).tolist()
tmp2 = map(int, tmp)
df = pd.DataFrame(tmp2, columns=["age"])
df.plot.hist(bins=5).figure.savefig('static/tmp.png')
return "hello, world"
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=8000)
として、
import matplotlib
matplotlib.use('agg')
を追記してください。
まとめ
Mac環境でこのエラーとなった時は試してみてください。
今回はこの辺で。