Skip to content

Instantly share code, notes, and snippets.

@jitunayak
Last active March 30, 2020 21:21
Show Gist options
  • Save jitunayak/eb1b8218d2f7b528eb5f13889a4d00d3 to your computer and use it in GitHub Desktop.
Save jitunayak/eb1b8218d2f7b528eb5f13889a4d00d3 to your computer and use it in GitHub Desktop.
CREATE DATABASE IF NOT EXISTS anychart_db;
USE anychart_db;
DROP PROCEDURE IF EXISTS init;
DELIMITER //
CREATE PROCEDURE init ()
LANGUAGE SQL
BEGIN
DECLARE user_exist, data_present INT;
SET user_exist = (SELECT EXISTS (SELECT DISTINCT user FROM mysql.user WHERE user = "anychart_user"));
IF user_exist = 0 THEN
CREATE USER 'anychart_user'@'localhost' IDENTIFIED BY 'anychart_pass';
GRANT ALL PRIVILEGES ON anychart_db.* TO 'anychart_user'@'localhost';
FLUSH PRIVILEGES;
END IF;
CREATE TABLE IF NOT EXISTS fruits (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(64),
value INT
);
SET data_present = (SELECT COUNT(*) FROM fruits);
IF data_present = 0 THEN
INSERT INTO fruits (name, value) VALUES
('apples', 10),
('oranges', 20),
('bananas', 15),
('lemons', 5),
('pears', 3),
('apricots', 7),
('kiwis', 9),
('mangos', 12),
('figs', 4),
('limes', 8);
END IF;
END;//
DELIMITER ;
CALL init();
mport mysql.connector
import flask
from flask import request, jsonify
app = flask.Flask(__name__)
app.config["DEBUG"] = True
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="******",
database="anychart_db"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM fruits")
myresult = mycursor.fetchall()
#for x in myresult:
# print(x)
@app.route('/', methods=['GET'])
def home():
return '''<h1>Distant Reading Archive</h1>
<p>A prototype API for distant reading of science fiction novels.</p>'''
@app.route('/fruits', methods=['GET'])
def api_all():
mycursor = mydb.cursor()
query_parameters = request.args
if(query_parameters):
name = query_parameters.get('name')
value = query_parameters.get('value')
print(name)
print(value)
query= "INSERT INTO fruits (name,value) VALUES (%s, %s)"
values = (name,value)
mycursor.execute(query,values)
mydb.commit()
print("Data inserted")
mycursor.execute("SELECT * FROM fruits")
row_headers=[x[0] for x in mycursor.description] #this will extract row headers
myresult = mycursor.fetchall()
json_data=[]
for result in myresult:
json_data.append(dict(zip(row_headers,result)))
#custom json key names
payload = []
content = {}
for result in myresult:
content = {'id': result[0], 'fruitname': result[1], 'quantity': result[2]}
payload.append(content)
content = {}
return jsonify(payload)
@app.errorhandler(404)
def page_not_found(e):
return "<h1>404</h1><p>The resource could not be found.</p>", 404
app.run()
#running example
## http://localhost:5000/fruits?name=Banana&value=30 --to put data
## http://localhost:5000/fruits --to fetch all data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment