Skip to content

Commit

Permalink
using SQL (#10)
Browse files Browse the repository at this point in the history
* using SQL

* add new line

* add new line

* add the CORS back

* move CORS back
  • Loading branch information
z6wdc authored and dwi2 committed Jul 31, 2019
1 parent 5ae70fe commit 928fa8d
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 137 deletions.
23 changes: 6 additions & 17 deletions app.yaml
Original file line number Diff line number Diff line change
@@ -1,18 +1,7 @@
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT main:app

runtime_config:
python_version: 3

# This sample incurs costs to run on the App Engine flexible environment.
# The settings below are to reduce costs during testing and are not appropriate
# for production use. For more information, see:
# https://cloud.google.com/appengine/docs/flexible/python/configuring-your-app-with-app-yaml
manual_scaling:
instances: 1
resources:
cpu: 1
memory_gb: 0.5
disk_size_gb: 10
runtime: python37

env_variables:
CLOUD_SQL_CONNECTION_NAME: your-connection-name
DB_USER: USER
DB_PASS: PASSWORD
DB_NAME: DATABASE
120 changes: 27 additions & 93 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,105 +1,39 @@
#!/usr/bin/env python3
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# [START app]
import datetime
import logging
import psycopg2
import os
import json

from flask import Flask
from flask import jsonify
from flask_cors import CORS

# DB Connection
conn = psycopg2.connect("host=34.97.189.196 dbname=photo user=root password=yori1234")
cur = conn.cursor()


# test data
dummy0 = {
"photo_group": "乃木坂46",
"photo_member": "樋口日奈",
"photo_costume": "2019 summer concert 1",
"photo_type": "ヨリ",
"photo_number": 1,
"photo_folder": "summer concert",
"photo_tag": []
}

dummy1 = {
"photo_group": "乃木坂46",
"photo_member": "樋口日奈",
"photo_costume": "2019 summer concert 1",
"photo_type": "チュウ",
"photo_number": 3,
"photo_folder": "summer concert",
"photo_tag": []
}

dummy2 = {
"photo_group": "乃木坂46",
"photo_member": "樋口日奈",
"photo_costume": "2019 summer concert 1",
"photo_type": "ヒキ",
"photo_number": 1,
"photo_folder": "summer concert",
"photo_tag": []
}

photos = [dummy0, dummy1, dummy2]
import sqlalchemy

app = Flask(__name__)
CORS(app)
app.config["JSON_AS_ASCII"] = False

@app.route('/')
def hello():
"""Return a friendly HTTP greeting."""
return 'Hello World!'


@app.route('/photos/all', methods=['GET'])
def photos_all():
return jsonify(photos)


@app.route('/create/photo', methods=['POST', 'GET'])
def create_photo(): #生写真の追加
if request.method == 'POST':
cur.execute("SELECT COUNT(id) FROM photo")
rows = cur.fetchall()
for row in rows:
ids = rows[0] + 1
cur.execute("INSERT INTO photos (photo_group, photo_member, photo_costume, photo_type, photo_number, photo_folder, photo_tag) VALUES (%s, %s, %s, %s, %d, %s, %s)", request.form['group'], request.form['member'], request.form['costume'], request.form['type'], request.form['number'], request.form['folder'], request.form['tag'])
cur.commit()
return redirect(url_for('display'))
else:
return render_template('add.html')


@app.errorhandler(500)
def server_error(e):
logging.exception('An error occurred during a request.')
return """
An internal error occurred: <pre>{}</pre>
See logs for full stacktrace.
""".format(e), 500

logger = logging.getLogger()

db_user = os.environ.get("DB_USER")
db_pass = os.environ.get("DB_PASS")
db_name = os.environ.get("DB_NAME")
cloud_sql_connection_name = os.environ.get("CLOUD_SQL_CONNECTION_NAME")

db = sqlalchemy.create_engine(
sqlalchemy.engine.url.URL(
drivername='mysql+pymysql',
username=db_user,
password=db_pass,
database=db_name,
query={
'unix_socket': '/cloudsql/{}'.format(cloud_sql_connection_name)
}
)
)

@app.route('/photo', methods=['GET'])
def index():
result = db.execute("select * from photos")
return json.dumps([dict(data) for data in result])

if __name__ == '__main__':
# This is used when running locally. Gunicorn is used to run the
# application on Google App Engine. See entrypoint in app.yaml.
app.run(host='127.0.0.1', port=8080, debug=True)
# [END app]

24 changes: 0 additions & 24 deletions main_test.py

This file was deleted.

6 changes: 3 additions & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Flask>=1.0.0
Flask==1.0.2
flask-cors>=3.0.8
gunicorn==19.7.1

SQLAlchemy==1.2.17
PyMySQL==0.9.3

0 comments on commit 928fa8d

Please sign in to comment.