|
| 1 | +# Copyright 2018 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the 'License'); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an 'AS IS' BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# [START functions_sql_mysql] |
| 16 | +from os import getenv |
| 17 | + |
| 18 | +import pymysql |
| 19 | + |
| 20 | +is_production = getenv('SUPERVISOR_HOSTNAME') is not None |
| 21 | + |
| 22 | +# TODO(developer): specify SQL connection details |
| 23 | +CONNECTION_NAME = getenv( |
| 24 | + 'INSTANCE_CONNECTION_NAME', |
| 25 | + '<YOUR INSTANCE CONNECTION NAME>') |
| 26 | +DB_USER = getenv('MYSQL_USER', '<YOUR DB USER>') |
| 27 | +DB_PASSWORD = getenv('MYSQL_PASSWORD', '<YOUR DB PASSWORD>') |
| 28 | +DB_NAME = getenv('MYSQL_DATABASE', '<YOUR DB NAME>') |
| 29 | + |
| 30 | +mysql_config = { |
| 31 | + 'user': DB_USER, |
| 32 | + 'password': DB_PASSWORD, |
| 33 | + 'db': DB_NAME, |
| 34 | + 'charset': 'utf8mb4', |
| 35 | + 'cursorclass': pymysql.cursors.DictCursor, |
| 36 | + 'autocommit': True |
| 37 | +} |
| 38 | + |
| 39 | +if is_production: |
| 40 | + mysql_config['unix_socket'] = \ |
| 41 | + '/cloudsql/' + CONNECTION_NAME |
| 42 | + |
| 43 | +# Create SQL connection globally to enable reuse |
| 44 | +# PyMySQL does not include support for connection pooling |
| 45 | +mysql_conn = pymysql.connect(**mysql_config) |
| 46 | + |
| 47 | + |
| 48 | +def __get_cursor(): |
| 49 | + """ |
| 50 | + Helper function to get a cursor |
| 51 | + PyMySQL does NOT automatically reconnect, |
| 52 | + so we must reconnect explicitly using ping() |
| 53 | + """ |
| 54 | + try: |
| 55 | + return mysql_conn.cursor() |
| 56 | + except Exception: |
| 57 | + mysql_conn.ping(reconnect=True) |
| 58 | + return mysql_conn.cursor() |
| 59 | + |
| 60 | + |
| 61 | +def mysql_demo(request): |
| 62 | + # Remember to close SQL resources declared while running this function. |
| 63 | + # Keep any declared in global scope (e.g. mysql_conn) for later reuse. |
| 64 | + with __get_cursor() as cursor: |
| 65 | + cursor.execute('SELECT NOW() as now') |
| 66 | + results = cursor.fetchone() |
| 67 | + return str(results['now']) |
| 68 | +# [END functions_sql_mysql] |
0 commit comments