【问题标题】:How to connect to SQL instance in Google Cloud Platform using Python3 in App Engine如何在 App Engine 中使用 Python3 连接到 Google Cloud Platform 中的 SQL 实例
【发布时间】:2020-07-27 00:14:12
【问题描述】:

我正在尝试在我使用 python3 创建的谷歌云应用引擎应用程序上从谷歌云平台连接到 SQL 实例。我的 main.py 代码如下(使用测试数据库),我的目标是在应用程序被定向到“查询”页面时显示完整的结果表。但是,运行该应用程序会导致“502 Bad Gateway nginx”错误。我究竟做错了什么?提前非常感谢。

from flask import Flask, render_template, redirect, url_for, request
import sqlalchemy

# If `entrypoint` is not defined in app.yaml, App Engine will look for an app
# called `app` in `main.py`.
app = Flask(__name__)

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


@app.route('/queries/', methods=['GET', 'POST'])
def queries():
    # The SQLAlchemy engine will help manage interactions, including automatically
    # managing a pool of connections to your database
    db = sqlalchemy.create_engine(
    # Equivalent URL:
    # mysql+pymysql://<db_user>:<db_pass>@/<db_name>?unix_socket=/cloudsql/<cloud_sql_instance_name>
    sqlalchemy.engine.url.URL(
        drivername="mysql+pymysql",
        username='admin',
        password='admin',
        database='studentlist',
        query={"unix_socket": "/cloudsql/{}".format('PROJECTNAME:europe-west1:student')},
    ),
    # ... Specify additional properties here.
    # ...
    )

    with db.connect() as conn:
        all_results = conn.execute(
            "SELECT * FROM student.studentlist"
        ).fetchall()

    return all_results

我的 app.yaml 文件:

runtime: python37

# [START handlers]
handlers:
- url: /static
  static_dir: static

env_variables:
    MYSQL_DSN: mysql:unix_socket=/cloudsql/INSTANCE_CONNECTION_NAME;dbname=student
    MYSQL_USER: admin
    MYSQL_PASSWORD: admin

【问题讨论】:

  • 能否请您发布 app.yaml 文件
  • @marian.vladoi 添加
  • @marian.vladoi 抱歉文件错误,现在添加正确的 .yaml 文件
  • 如果 project_name 和 project_id 之间存在差异,请检查项目的主页,确保使用 project_id... PROJECT_ID:REGION:INSTANCE_ID 您的代码似乎使用了 project_name ... "'PROJECTNAME:europe-west1:student"...app.yaml 中的 unix 套接字也应该是 ...beta_settings: cloud_sql_instances: ,或者对于多个实例 beta_settings: cloud_sql_instances: ,

标签: sql python-3.x google-app-engine google-cloud-platform sqlalchemy


【解决方案1】:

我写了一篇关于如何使用 python 从 App Engine 连接到 Cloud SQL 的详细教程。希望对你有帮助!

https://github.com/mvladoi/GCS-python/blob/master/Connect%20from%20App%20Engine%20to%20Cloud%20Sql%20using%20TCP%20and%20Unix%20domani%20sockets

我建议指定一个入口点:

 entrypoint: uwsgi --http-socket :8080 --wsgi-file main.py --callable app --master --processes 1 --threads 2

同时检查是否有任何部署错误:

  gcloud app logs read

你贴的连接码没问题,但我觉得查询应该是SELECT * FROM studentlist

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 2022-03-09
    • 2022-07-26
    • 2014-02-17
    相关资源
    最近更新 更多