AssertionError AssertionError:处理完第一个请求后,调用了设置函数。这通常表示应用程序中的错误,其中未导入模块,并且装饰器或其他功能的调用为时已晚。要解决此问题,请确保在应用程序开始为请求提供服务之前,将所有视图模块,数据库模型以及所有相关内容都导入一个中央位置。 追溯(最近一次通话) resposta_insert中的文件“ C:\ Users \ joaog \ Documents \ tryflask \ app.py”第240行 如果request.method =='POST'和form.validate():
尝试:
mysql = MySQL(app)
cur = mysql.connection.cursor()
除了错误e:
print("Error while connecting to MySQL", e)
print()
最后:
mysql = MySQL(app)
cur = mysql.connection.cursor()
方法代码:
@app.route('/respostas/<int:pergunta_id>/<int:aluno_id>', methods=["POST"])
def resposta_insert(pergunta_id, aluno_id):
form = RespostaForm(request.form)
if request.method == 'POST' and form.validate():
# VERIFICA SE OS FORMULARIOS ESTAO BEM FEITOS
resposta_sql = request.form["resposta_sql"]
# INSERE NA BASE DE DADOS A NOVA RESPOSTA
try:
mysql = MySQL(app)
cur = mysql.connection.cursor()
except Error as e:
print("Error while connecting to MySQL", e)
print()
finally:
mysql = MySQL(app)
cur = mysql.connection.cursor()
query = "INSERT INTO resposta (pergunta_id, aluno_id, resposta_sql) VALUES (%s,%s,%s);"
cur.execute(query, (pergunta_id, aluno_id, resposta_sql))
mysql.connection.commit()
# SELECIONA O ULTIMO INDEX INSERIDO
cur.execute("SELECT LAST_INSERT_ID();")
data_last_inserted_id = cur.fetchall()
last_inserted_id = data_last_inserted_id[0][0]
# PREPARA ESTRUTURA PARA COMPARACAO DE TABELAS VIA MYSQL AND DATASETS
# PESQUISA O QUERY MYSQL DA PERGUNDA DO PROFESSOR
query = "SELECT PERGUNTA_SQL,QUERY_ID FROM PERGUNTA WHERE PERGUNDA_ID = %s"
cur.execute(query,(pergunta_id,))
data = cur.fetchall()
sqlquery = data[0][0]
sqlquery.upper()
# PESQUISA O QUERY MYSQL DA RESPOSTA DO ALUNO
sqlqueryal = resposta_sql
sqlqueryal.upper()
#sqlparsed = sqlparse.parse(sqlquery)
sqlquerykey = data[0][1]
# print()
import mysql.connector
try:
print("Cria a connexão!")
print()
connection = mysql.connector.connect(host='localhost',
database='jg_teste',
user='root',
password='user')
if connection.is_connected():
# ACRESCENTAR O ID
def acrescentar_id(query, id_):
queryparsed = sqlparse.parse(query)
# print(queryparsed[0])
lista = list()
for each in queryparsed[0]:
if each.value == "SELECT":
lista.append(each.value)
lista.append(" ")
lista.append(id_+",")
else:
lista.append(each.value)
lista = ''.join(lista)
# print(lista)
return lista
print("IMPRIME A DATA_FRAME_KEY")
print(sqlquerykey)
# ACRESCENTAR O ID A QUERY #
############################
print()
print("CHAVE:")
print(sqlquerykey)
print()
print("SQL QUERYS")
sqlqueryprof = acrescentar_id(sqlquery, sqlquerykey)
print(sqlqueryprof)
sqlqueryalun = acrescentar_id(sqlqueryal, sqlquerykey)
print(sqlqueryalun)
# EXECUTAR CADA UMA DAS QUERYS
cursor_prof = connection.cursor()
cursor_prof.execute(sqlqueryprof)
records_prof = cursor_prof.fetchall()
data_frame_prof = pandas.DataFrame(records_prof)
# print(data_frame_prof)
cursor_alun = connection.cursor()
cursor_alun.execute(sqlqueryalun)
records_query = cursor_alun.fetchall()
data_frame_alun = pandas.DataFrame(records_prof)
print()
# COMPARACAO DOS DATA FRAMES
data_prof = pandas.read_sql(sqlqueryprof, con=connection)
data_alun = pandas.read_sql(sqlqueryalun, con=connection)
# datacompy
compare = datacompy.Compare(
data_prof,
data_alun,
join_columns=sqlquerykey)
# IMPRIMIR RESULTADOS DA COMPARACAO ##
######################################
print("#######################################################################################################")
print("Colunas que intreceptaram", len(compare.intersect_columns()))
print("Linhas que intreceptaram", compare.intersect_rows.shape[0])
print()
print("Linha unicas no DataFrame 1:", len(compare.df1_unq_rows))
print("Linha unicas no DataFrame 2:", len(compare.df2_unq_rows))
print()
print("Colunas unicas de Dataframe 1 :", compare.df1_unq_columns())
print("Colunas unicas de Dataframe 2 :", compare.df2_unq_columns())
cursor_prof.rowcount
numero_linhas_totais = len(compare.df1_unq_rows)
numero_linhas_iguais = compare.intersect_rows.shape[0]
colunas_totais = compare.df1_unq_columns()
colunas_iguais = len(compare.intersect_columns())
table_prof = extract_tables(sqlqueryprof)
table_alun = extract_tables(sqlqueryalun)
campos_totais = len(table_prof)
campos_iguais = len(table_prof & table_alun)
query = "INSERT INTO RESULTADO (numero_linhas_totais, numero_linhas_iguais, colunas_totais,colunas_iguais,campos_totais,campos_iguais, pergunta_pergunta_id) VALUES (%s,%s,%s,%s,%s,%s,%s);"
cur.execute(query,(numero_linhas_totais,numero_linhas_iguais,colunas_totais,colunas_iguais,campos_totais,campos_iguais,pergunta_id))
# print(data_frame_prof)
except Error as e:
print("Error while connecting to MySQL", e)
print()
finally:
# closing database connection.
if(connection.is_connected()):
cursor_prof.close()
cursor_alun.close()
connection.close()
print("MySQL connection is closed")
# SELECIONA A RESPOSTA ANTERIORMENTE INSERIDA
query = "SELECT RESPOSTA_SQL FROM RESPOSTA WHERE RESPOSTA_ID = %s;"
cur.execute(query, (last_inserted_id,))
data = cur.fetchall()
cur.close()
js = json.dumps(data)
resp = Response(js, status=200, mimetype='application/json')
resp.headers['Links'] = 'http://127.0.0.1/respostas/'
return resp
elif request.method == 'POST' and not form.validate():
resp = Response(status=400)
resp.headers['Links'] = 'http://127.0.0.1/respostas/'
return resp
答案 0 :(得分:0)
问题出在这里
query = "INSERT INTO resposta (pergunta_id, aluno_id, resposta_sql) VALUES (%s,%s,%s);"
cur.execute(query, (pergunta_id, aluno_id, resposta_sql))
mysql.connection.commit()
列名错误