Advertisement
Guest User

Untitled

a guest
Sep 13th, 2018
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. import os
  2.  
  3. import MySQLdb
  4. import webapp2    
  5.  
  6. CLOUDSQL_CONNECTION_NAME = os.environ.get('CLOUDSQL_CONNECTION_NAME')
  7. CLOUDSQL_USER = os.environ.get('CLOUDSQL_USER')
  8. CLOUDSQL_PASSWORD = os.environ.get('CLOUDSQL_PASSWORD')
  9.  
  10. DB_NAME='test-db'
  11.  
  12. def connect_to_cloudsql():
  13.     # When deployed to App Engine, the `SERVER_SOFTWARE` environment variable
  14.     # will be set to 'Google App Engine/version'.
  15.     if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'):
  16.         # Connect using the unix socket located at
  17.         # /cloudsql/cloudsql-connection-name.
  18.         cloudsql_unix_socket = os.path.join(
  19.             '/cloudsql', CLOUDSQL_CONNECTION_NAME)
  20.  
  21.         db = MySQLdb.connect(
  22.             unix_socket=cloudsql_unix_socket,
  23.             user=CLOUDSQL_USER,
  24.             passwd=CLOUDSQL_PASSWORD)
  25.  
  26.     # If the unix socket is unavailable, then try to connect using TCP. This
  27.     # will work if you're running a local MySQL server or using the Cloud SQL
  28.     # proxy, for example:
  29.     #
  30.     #   $ cloud_sql_proxy -instances=your-connection-name=tcp:3306
  31.     #
  32.     else:
  33.         db = MySQLdb.connect(
  34.             host='127.0.0.1', user=CLOUDSQL_USER, passwd=CLOUDSQL_PASSWORD, db=DB_NAME)
  35.  
  36.     return db
  37.  
  38. class MysqlPage(webapp2.RequestHandler):
  39.     def get(self):
  40.         """Simple request handler that shows all of the MySQL variables."""
  41.         self.response.headers['Content-Type'] = 'text/plain'
  42.  
  43.         db = connect_to_cloudsql()
  44.         """ Your db statement would go their later on."""
  45.        
  46.         self.response.write('It worked')
  47.  
  48.  
  49. app = webapp2.WSGIApplication([
  50.     ('/mysql', MysqlPage),
  51. ], debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement