How to Use a MySQL Database with an App Engine Application

How to connect Google App Engine to External Mysql db using Python

from flask import Flask, jsonify, request
import pymysql.cursors

app = Flask(_name_)

# Annotation that direct app engine to / route.
@app.route('/')
def home():
connection = pymysql.connect(host='XXXXXX',
database='XXXX',
user='XXXX',
password='XXXXX',
port=XXXX,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)

print ("connect successful!!")

try:

with connection.cursor() as cursor:
# SQL
sql = "select * from songs"

# Execute query.
cursor.execute(sql)
print ("cursor.description: ", cursor.description)

print()

for row in cursor:
print(row)

finally:
# Close connection.
connection.close()

return "Connection Sucessful"
if _name_ == '_main_':
# This is used when running locally. Gunicorn is used to run the
# application on Google App Engine. See entry point in app.yaml.
app.run()

Here code will run only if it is not imported from other modules as you are checking for name = 'main'.

Connect our Google App Engine Python API to an external MySQL database on Digital Ocean

AppEngine can connect to internet but with a pool of IP address. You can't define one and use always the same. If your Database has to authorize only one IP it's not yet supported.

However, you could cheat by plugging a serverless VPC Connector to your AppEngine and using a VM as proxy but the solution is ugly and I don't guaranty good response time, which is critical for a database...



Related Topics



Leave a reply



Submit