【问题标题】:Cannot connect to cleardb from flask app running on heroku无法从在 heroku 上运行的烧瓶应用程序连接到 cleardb
【发布时间】:2019-12-04 12:55:26
【问题描述】:

我正在学习烧瓶等,并在本地创建了一个简单的应用程序。 xammp 中的本地 mysql 数据库一切正常。我将其导出并导入到 heroku 上的 clearDB 并部署了我的应用程序。该应用程序运行,但每当我尝试访问依赖于日志中数据库的页面时,我都会看到此错误。

pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection denied)")

我在本地运行应用程序,但使用 clearDB 数据库,它能够检索数据没有问题。文件中的所有内容都配置为根据 heroku 中的 URL 详细信息进行访问。

代码如下。我敢肯定还有很多其他问题,但正如我所说,我正在学习并从教程中获得所有这些。

#instaniation
app = Flask(__name__)
app.secret_key= 'secret123'

#config
app.config['MYSQL_HOST'] = 'us-cdbr-iron-east-02.cleardb.net'
app.config['MYSQL_USER'] = 'redacted'
app.config['MYSQL_PASSWORD'] = 'redacted'
app.config['MYSQL_DB'] = 'heroku_0c6326c59d8b6e9'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor' #a cursor is a connection to let us run methods for queries. We set is as a dictionary

#init MySQL
mysql = MySQL(app,cursorclass=DictCursor)

#url endpoint
@app.route('/')

#function for starting app
def index():
    #can directly return HTML
    return render_template('index.html')

@app.route('/about')
def about():
    return render_template('about.html')

#many articles
@app.route('/articles')
def articles():
    #create Cursor
    cur = mysql.get_db().cursor() #to execute commands
    cur.execute("USE myflaskapp")

    #get articles
    result = cur.execute("SELECT * FROM articles")
    #should retrieve all as a dictionary
    articles = cur.fetchall()
    if result > 0:
        return render_template('articles.HTML', articles=articles)
    else:
        msg= 'No Articles Found'
        return render_template('articles.HTML', msg=msg)
    cur.close()

【问题讨论】:

    标签: python mysql heroku flask cleardb


    【解决方案1】:

    从错误中可以看出:pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)") MySQL 尝试连接到localhost 服务器,这意味着它不会加载您的配置变量。

    如果您使用来自 https://flask-mysql.readthedocs.io/en/latest/# 的烧瓶扩展来加载 MySQL,那么您可能忘记初始化您的应用程序 (pip install flask-mysql)

    mysql.init_app(app)
    

    你的代码的头部现在应该是这样的

    并注意配置变量名称,扩展使用略有不同的约定

    from flask import Flask
    from flaskext.mysql import MySQL
    
    #instaniation
    app = Flask(__name__)
    app.secret_key= 'secret'
    
    #config
    app.config['MYSQL_DATABASE_USER'] = 'user'
    app.config['MYSQL_DATABASE_PASSWORD'] = 'password'
    app.config['MYSQL_DATABASE_DB'] = 'db'
    app.config['MYSQL_DATABASE_HOST'] = 'host'
    
    #init MySQL
    mysql = MySQL()
    mysql.init_app(app)
    

    【讨论】:

    • 非常感谢,解决了这个问题。现在我可以为其他人工作,但你现在给了我一些东西可以继续。
    猜你喜欢
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    相关资源
    最近更新 更多