|
14 | 14 |
|
15 | 15 | """
|
16 | 16 | Sample App Engine application demonstrating how to connect to Google Cloud SQL
|
17 |
| -using App Engine's native unix socket. |
| 17 | +using App Engine's native unix socket or using TCP when running locally. |
18 | 18 |
|
19 | 19 | For more information, see the README.md.
|
20 | 20 | """
|
21 | 21 |
|
22 | 22 | # [START all]
|
23 |
| - |
24 | 23 | import os
|
25 | 24 |
|
26 | 25 | import MySQLdb
|
27 | 26 | import webapp2
|
28 | 27 |
|
29 | 28 |
|
30 |
| -CLOUDSQL_PROJECT = '' |
31 |
| -CLOUDSQL_INSTANCE = '' |
| 29 | +# These environment variables are configured in app.yaml. |
| 30 | +CLOUDSQL_CONNECTION_NAME = os.environ.get('CLOUDSQL_CONNECTION_NAME') |
| 31 | +CLOUDSQL_USER = os.environ.get('CLOUDSQL_USER') |
| 32 | +CLOUDSQL_PASSWORD = os.environ.get('CLOUDSQL_PASSWORD') |
| 33 | + |
| 34 | + |
| 35 | +def connect_to_cloudsql(): |
| 36 | + # When deployed to App Engine, the `SERVER_SOFTWARE` environment variable |
| 37 | + # will be set to 'Google App Engine/version'. |
| 38 | + if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'): |
| 39 | + # Connect using the unix socket located at |
| 40 | + # /cloudsql/cloudsql-connection-name. |
| 41 | + cloudsql_unix_socket = os.path.join( |
| 42 | + '/cloudsql', CLOUDSQL_CONNECTION_NAME) |
| 43 | + |
| 44 | + db = MySQLdb.connect( |
| 45 | + unix_socket=cloudsql_unix_socket, |
| 46 | + user=CLOUDSQL_USER, |
| 47 | + passwd=CLOUDSQL_PASSWORD) |
| 48 | + |
| 49 | + # If the unix socket is unavailable, then try to connect using TCP. This |
| 50 | + # will work if you're running a local MySQL server or using the Cloud SQL |
| 51 | + # proxy, for example: |
| 52 | + # |
| 53 | + # $ cloud_sql_proxy -instances=your-connection-name=tcp:3306 |
| 54 | + # |
| 55 | + else: |
| 56 | + db = MySQLdb.connect( |
| 57 | + host='127.0.0.1', user=CLOUDSQL_USER, passwd=CLOUDSQL_PASSWORD) |
| 58 | + |
| 59 | + return db |
32 | 60 |
|
33 | 61 |
|
34 | 62 | class MainPage(webapp2.RequestHandler):
|
35 | 63 | def get(self):
|
| 64 | + """Simple request handler that shows all of the MySQL variables.""" |
36 | 65 | self.response.headers['Content-Type'] = 'text/plain'
|
37 | 66 |
|
38 |
| - # When running on Google App Engine, use the special unix socket |
39 |
| - # to connect to Cloud SQL. |
40 |
| - if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'): |
41 |
| - db = MySQLdb.connect( |
42 |
| - unix_socket='/cloudsql/{}:{}'.format( |
43 |
| - CLOUDSQL_PROJECT, |
44 |
| - CLOUDSQL_INSTANCE), |
45 |
| - user='root') |
46 |
| - # When running locally, you can either connect to a local running |
47 |
| - # MySQL instance, or connect to your Cloud SQL instance over TCP. |
48 |
| - else: |
49 |
| - db = MySQLdb.connect(host='localhost', user='root') |
50 |
| - |
| 67 | + db = connect_to_cloudsql() |
51 | 68 | cursor = db.cursor()
|
52 | 69 | cursor.execute('SHOW VARIABLES')
|
53 | 70 |
|
|
0 commit comments