Skip to content

Update functions/sql example to use more clear connection logic. #2486

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 18, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions functions/sql/mysql_sample.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,16 @@
from os import getenv

import pymysql
from pymysql.err import OperationalError

# TODO(developer): specify SQL connection details
CONNECTION_NAME = getenv('MYSQL_INSTANCE', '<YOUR INSTANCE CONNECTION NAME>')
DB_USER = getenv('MYSQL_USER', '<YOUR DB USER>')
DB_PASSWORD = getenv('MYSQL_PASSWORD', '<YOUR DB PASSWORD>')
DB_NAME = getenv('MYSQL_DATABASE', '<YOUR DB NAME>')

# set to true to test locally using Cloud SQL proxy listening on a TCP port
DEBUG = False

mysql_config = {
'user': DB_USER,
'password': DB_PASSWORD,
Expand Down Expand Up @@ -56,12 +58,14 @@ def mysql_demo(request):
# GCF instance. Doing so minimizes the number of active SQL connections,
# which helps keep your GCF instances under SQL connection limits.
if not mysql_conn:
try:
mysql_conn = pymysql.connect(**mysql_config)
except OperationalError:
# If production settings fail, use local development ones
mysql_config['unix_socket'] = f'/cloudsql/{CONNECTION_NAME}'
mysql_conn = pymysql.connect(**mysql_config)
if DEBUG:
# try to connect using localling running Cloud SQL proxy
# (local development only)
mysql_conn = pymysql.connect(
**mysql_config, host='127.0.0.1', port=3306)
else:
mysql_conn = pymysql.connect(
**mysql_config, unix_socket=f'/cloudsql/{CONNECTION_NAME}')

# Remember to close SQL resources declared while running this function.
# Keep any declared in global scope (e.g. mysql_conn) for later reuse.
Expand Down