[英]How to connect to SQL instance in Google Cloud Platform using Python3 in App Engine
I am trying to connect to an SQL instance from the Google Cloud platform on a Google cloud app engine app I am creating using python3.我正在尝试在我使用 python3 创建的谷歌云应用引擎应用程序上从谷歌云平台连接到 SQL 实例。 My main.py code is as follows (using a test database) and my aim is to display the full table of results when the app is directed to the 'queries' page.
我的 main.py 代码如下(使用测试数据库),我的目标是在应用程序被定向到“查询”页面时显示完整的结果表。 However running the app causes a '502 Bad Gateway nginx' error.
但是,运行该应用程序会导致“502 Bad Gateway nginx”错误。 What am I doing wrong?
我究竟做错了什么? Thanks very much in advance.
首先十分感谢。
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
My app.yaml file:我的 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
I wrote a detailed tutorial on how to connect to Cloud SQL from App Engine using python.我写了一篇关于如何使用 python 从 App Engine 连接到 Cloud SQL 的详细教程。 I hope it helps!
我希望它有帮助!
https://github.com/mvladoi/GCS-python/blob/master/Connect%20from%20App%20Engine%20to%20Cloud%20Sql%20using%20TCP%20and%20Unix%20domani%20sockets https://github.com/mvladoi/GCS-python/blob/master/Connect%20from%20App%20Engine%20to%20Cloud%20Sql%20using%20TCP%20and%20Unix%20domani%20sockets
I would recommed to specify an entrypoint:我建议指定一个入口点:
entrypoint: uwsgi --http-socket :8080 --wsgi-file main.py --callable app --master --processes 1 --threads 2
Also check for any deployment errors:还要检查任何部署错误:
gcloud app logs read
The connection code that you posted is ok, but I think the query should be SELECT * FROM studentlist
您发布的连接代码是可以的,但我认为查询应该是
SELECT * FROM studentlist
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.