技術メモ

メモ代わりに使います!

GAE-PythonでPHPMyAdminに接続するソースをデプロイ

①main.py作成

# -*- coding: utf-8 -*-
import random
import json
import cgi

import os

import MySQLdb
import webapp2

# These environment variables are configured in app.yaml.
CLOUDSQL_CONNECTION_NAME = os.environ.get('CLOUDSQL_CONNECTION_NAME')
CLOUDSQL_USER = os.environ.get('CLOUDSQL_USER')
CLOUDSQL_PASSWORD = os.environ.get('CLOUDSQL_PASSWORD')


def connect_to_cloudsql():
    # When deployed to App Engine, the `SERVER_SOFTWARE` environment variable
    # will be set to 'Google App Engine/version'.
    if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'):
        # Connect using the unix socket located at
        # /cloudsql/cloudsql-connection-name.
        cloudsql_unix_socket = os.path.join(
            '/cloudsql', CLOUDSQL_CONNECTION_NAME)

        db = MySQLdb.connect(
            unix_socket=cloudsql_unix_socket,
            user=CLOUDSQL_USER,
            passwd=CLOUDSQL_PASSWORD)

    # If the unix socket is unavailable, then try to connect using TCP. This
    # will work if you're running a local MySQL server or using the Cloud SQL
    # proxy, for example:
    #
    #   $ cloud_sql_proxy -instances=your-connection-name=tcp:3306
    #
    else:
        db = MySQLdb.connect(
            host='127.0.0.1', user=CLOUDSQL_USER, passwd=CLOUDSQL_PASSWORD)

    return db


class MainPage(webapp2.RequestHandler):
    def get(self):
        """Simple request handler that shows all of the MySQL variables."""
        self.response.headers['Content-Type'] = 'text/plain'

        db = connect_to_cloudsql()
        cursor = db.cursor()
        cursor.execute('select * from test.user;')

        for r in cursor.fetchall():
            self.response.write('{}\n'.format(r))
            self.response.write(cgi.escape(self.request.get('test')))

class TainPage(webapp2.RequestHandler):
    def post(self):
        self.response.write(self.request.get_all('value'))

app = webapp2.WSGIApplication([
    ('/', MainPage),
    ('/user', TainPage),
], debug=True)

②app.yamlファイル作成

service: python-rest
#application: python-rest
runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /
  script: main.app
- url: /user
  script: main.app

libraries:
- name: MySQLdb
  version: "latest"

# [START env_variables]
env_variables:
    CLOUDSQL_CONNECTION_NAME: 【インスタンス接続名】
    CLOUDSQL_USER: 【接続ユーザ名】
    CLOUDSQL_PASSWORD: 【パスワード】
# [END env_variables]

③deploy