【发布时间】:2020-08-03 00:02:07
【问题描述】:
我想在 URL 中输入 CallId 并以 Json 格式从我的数据库中获取该行的信息。 例如键入:http://127.0.0.1:5000/caller/?CallId=123456,然后获取 OriginationName 和 OriginationNumber。
我认为我的 for 循环中有一个错误。 我将非常感谢任何帮助。 这是我的代码:
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)
【问题讨论】:
-
@anrufe.route('/caller/", methods=['GET'])你有不同的'和"来电。只需使用一种类型("/caller/"或'/caller/')。 -
谢谢,但还是不行。 “TypeError:字符串索引必须是整数,而不是 str。”这就是我得到的。
-
那么这意味着您的(所需)列表切片之一 - userDetails['CallId'] 或 userDetails['OriginationNumber'] 等实际上是一个字符串;又名 userDetails 或 userDetails 是一个字符串而不是一个列表(上面提到的只是示例) - 将完整的错误添加到问题中或在此处发布,它应该说明错误的触发位置
-
文件“/home/omid/.local/lib/python2.7/site-packages/flask/app.py”,第 1936 行,在 dispatch_request 返回 self.view_functions[rule.endpoint]( **req.view_args) 文件“/home/omid/flaskapp/anrufe.py”,第 54 行,在 api_caller if caller['CallId'] == ['CallId']: TypeError: string indices must be integers, not str
-
如果你在 if 之前添加了一个 print(caller),那么 print 是什么意思?该错误表明
caller是一个字符串,而不是预期的字典。如果您显示调用者(来自打印),我们将深入了解。
标签: python json api routes getmethod