· 5 years ago · Oct 06, 2020, 11:30 AM
1from flask import Flask, jsonify, request
2from flask_cors import CORS, cross_origin
3import mysql.connector
4from flask_sqlalchemy import SQLAlchemy
5
6app = Flask(__name__)
7cors = CORS(app)
8app.config['CORS_HEADERS'] = 'Content-Type'
9app.config['SGQALCHEMY_DATABASE_URI'] = 'sqlite:///tmp/test.db'
10db = SQLAlchemy(app)
11
12class Recipes(db.Model):
13 recipe_id =db.Column(db.Integer, primary_key = True)
14 category = db.Column(db.String(15), nullable = False)
15 name = db.Column(db.String(60), nullable = False)
16 link = db.Column(db.String(150), nullable = False)
17
18 def __repr__(self):
19 return '<Recipes %r>' % self.name
20
21
22cnx = mysql.connector.connect(
23 user='root', password='admin',
24 host='127.0.0.1', database='example_app',
25)
26cursor = cnx.cursor()
27
28create_table_statement = (
29 "CREATE TABLE IF NOT EXISTS `recipes` ("
30 " `recipe_id` int(11) NOT NULL AUTO_INCREMENT,"
31 " category varchar(14) NOT NULL,"
32 " name varchar(32) NOT NULL,"
33 " link varchar(32) NOT NULL,"
34 " PRIMARY KEY (`recipe_id`)"
35 ") ENGINE=InnoDB"
36)
37select_recipe_statement = "SELECT * FROM recipes"
38insert_recipe_statement = (
39 "INSERT INTO recipes "
40 "(category, name, link) "
41 "VALUES (%s, %s, %s)"
42)
43
44{
45 "categories": ["dinner"],
46 "name": "rosol",
47 "link": "blebleble"
48}
49
50@app.route('/recipes', methods=['GET'])
51def recipes():
52 cursor.execute(select_recipe_statement)
53 all_recipes = [{
54 "id" : recipe[0],
55 "category" : recipe[1],
56 "name" : recipe[2],
57 "link" : recipe[3],
58 } for recipe in cursor]
59 return jsonify(all_recipes)
60
61
62@app.route('/recipe', methods=['POST'])
63def add_recipe():
64 body = request.get_json()
65 category = body['categories'][0]
66 name = body['name']
67 link = body['link']
68 cursor.execute(insert_recipe_statement, (category, name, link,))
69 return ('', 204)
70
71@app.route('/calculate-volume', methods=['GET'])
72def calculate-volume():
73 body = request.get_json()
74 typeOfVolume = body['typeOfVolume'][0]
75 volume = body['volume']
76 switch (typeOfVolume) {
77 case 1:
78 }
79
80
81 outputVolume
82
83@app.route('/')
84def root():
85 cursor.execute(create_table_statement)
86 return jsonify({"result": "Success"})
87
88if __name__ == '__main__':
89 app.run(host='0.0.0.0', debug=True)