I am learning to build an API with Python and Flask. I don't know why, but sometimes and I get response which is multipled. Now I have 67 records in my database, but the response from API has much more items. Here's the api code:
from flask import Flask, jsonify
from flaskext.mysql import MySQL
from flask_restful import Resource, Api
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
#Create an instance of MySQL
mysql = MySQL()
#Create an instance of Flask RESTful API
api = Api(app)
#Set database credentials in config.
app.config['MYSQL_DATABASE_USER'] = 'xxx'
app.config['MYSQL_DATABASE_PASSWORD'] = 'xxx'
app.config['MYSQL_DATABASE_DB'] = 'xxx'
app.config['MYSQL_DATABASE_HOST'] = 'xxx'
#Initialize the MySQL extension
mysql.init_app(app)
keys_dict = ["id", "link", "title", "date", "image", "description", "tag"]
final_dict = []
class PostList(Resource):
def get(self):
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute("""SELECT * from table ORDER BY date """)
rows = cursor.fetchall()
for m in rows:
final_dict.append(dict(zip(keys_dict, m)))
return jsonify(final_dict)
cursor.close()
conn.close()
api.add_resource(PostList, '/', endpoint='')
if __name__ == '__main__':
app.run(debug=True)
The response sometimes looks normal, but usually is much bigger than it should be: I'd prefer not to post an endpoint here for obvious reasons, but I think the problem is in the above code. I appreciate any help, thank you!
CodePudding user response:
Try the following portion of code as below:
#Initialize the MySQL extension
mysql.init_app(app)
keys_dict = ["id", "link", "title", "date", "image", "description", "tag"]
class PostList(Resource):
def get(self):
final_dict = []
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute("""SELECT * from table ORDER BY date """)
rows = cursor.fetchall()
for m in rows:
final_dict.append(dict(zip(keys_dict, m)))
return jsonify(final_dict)
cursor.close()
conn.close()
change: define final_dict
assignment in the get
function of the class PostList