先日cloudsql上のMysqlにpymysql経由で接続するFlask製のWebアプリケーションを作成していた際に以下のようなエラーに遭遇しました
エラーメッセージ
pymysql.err.InterfaceError: (0, ”)
<コード>
import pymysql
from flask import Flask, render_template,jsonify,redirect, url_for
connection = pymysql.connect(host='xxxx', port=1111, user='xxxx', password='xxxx', db='db_name') sql = "SELECT * FROM price_data.crypto_price7"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@app.route("/test")
def test():
sql = "SELECT * FROM youtube_live_data2.vtuber_channel_info LIMIT 10"
cursor = connection.cursor()
cursor.execute(sql)
res = cursor.fetchall()
print(res)
data = {'test':0,'test2':1}
return jsonify(data)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
原因
権限の問題もあるみたいですが基本的にはスコープの問題みたいです。自分の場合はFLASK起動時にコネクションを定義し、それをルーティングの関数内で使用しようとした場合に上記のエラーに遭遇しました、なので接続とexeのスコープを以下のように関数内で処理するように統一した結果エラーは解決しました。
import pymysql
from flask import Flask, render_template,jsonify,redirect, url_for
~~~~~~
@app.route("/test")
def test():
connection = pymysql.connect(host='xxxx', port=1111, user='xxxx', password='xxxx', db='db_name')
sql = "SELECT * FROM table LIMIT 10"
cursor = connection.cursor()
cursor.execute(sql)
res = cursor.fetchall()
print(res)
cursor.close()
connection.close()
data = {'test':0,'test2':1}
return jsonify(data)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

コメント