I want to type the CallId in the URL and get the information of the row from my database in Json Format. For example typing: http://127.0.0.1:5000/caller/?CallId=123456 and then get the OriginationName and OriginationNumber.
I think there is a mistake in my for loop. i would be very grateful for any help. Here is my code:
from flask import Flask, render_template, request
from flask_mysqldb import MySQL
import yaml
anrufe = Flask(__name__)
datenbank = yaml.load(open('datenbank.yaml'))
anrufe.config['MYSQL_HOST'] = datenbank['mysql_host']
anrufe.config['MYSQL_USER'] = datenbank['mysql_user']
anrufe.config['MYSQL_PASSWORD'] = datenbank['mysql_password']
anrufe.config['MYSQL_DB'] = datenbank['mysql_db']
mysql = MySQL(anrufe)
@anrufe.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
userDetails = request.form
CallId = userDetails['CallId']
OriginationNumber = userDetails['OriginationNumber']
OriginationName = userDetails['OriginationName']
cur = mysql.connection.cursor()
cur.execute("INSERT INTO caller(CallId,OriginationNumber,OriginationName) VALUES(%s, %s, %s)",
(CallId, OriginationNumber, OriginationName))
mysql.connection.commit()
cur.close()
return 'Der Anrufer wurde registriert'
return render_template('index.html')
@anrufe.route('/caller/all')
def caller():
cur = mysql.connection.cursor()
resultValue = cur.execute("SELECT * FROM caller")
if resultValue > 0:
userDetails = cur.fetchall()
return render_template('caller.html', userDetails=userDetails)
@anrufe.route('/caller/", methods=['GET'])
def api_caller():
if 'CallId' in request.args:
CallId = int(request.args['CallId'])
print(CallId)
else:
return "Error: No CallId field provided. Please specify a CallId."
results = []
for caller in datenbank:
if caller['CallId'] == ['CallId']:
results.append(caller)
return jsonify(results)
if __name__ == '__main__':
anrufe.run(debug=True)
Step1: let's get all results by callerid:
from flask import jsonify
@anrufe.route('/caller/CallId=<id>', methods = ['GET'])
def api_caller(id):
cur = mysql.connection.cursor()
resultValue = cur.execute("SELECT * FROM caller WHERE CallId = (%s)",(id,))
if resultValue > 0:
user_by_id = cur.fetchall()
return jsonify(user_by_id)
else:
return "Called ID does not exist!"