TypeError:cursor()使用flaskext.mysql获得了意外的关键字参数'dictionary' [英] TypeError: cursor() got an unexpected keyword argument 'dictionary' using flaskext.mysql

查看:130
本文介绍了TypeError:cursor()使用flaskext.mysql获得了意外的关键字参数'dictionary'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用flask框架和MySQL数据库连接器.

我做了以下事情:

从flaskext.mysql

 导入MySQLmysql = MySQL()## app.config数据库配置代码mysql.init_app(应用程序)conn = mysql.connect()cursor = conn.cursor();cursor.execute('选择*来自客户的电子邮件=(%s)',(用户名,))用户= cursor.fetchone() 

我可以使用 user [8] 这样的索引访问用户列(我需要执行一次查询并检查列号),但是当我尝试指定

  conn = mysql.connect(dictionary = True) 

我收到错误

'TypeError:cursor()得到了意外的关键字参数'dictionary'

使用flask-MySQL时是否可以以字典格式获取查询结果?

解决方案

您可以按照以下答案进行操作:

I'm using flask framework and MySQL database connector.

I did the below:

from flaskext.mysql import MySQL
mysql = MySQL()
## app.config database configuration code
mysql.init_app(app)
conn = mysql.connect()
cursor = conn.cursor();
cursor.execute(
        'SELECT * FROM customer WHERE email = (%s)', (username,)
    )
user = cursor.fetchone()

I can access the user columns using index like user[8] (which I need to execute the query once and check the column number), but when I try to specify

conn = mysql.connect(dictionary=True)

I get the error

'TypeError: cursor() got an unexpected keyword argument 'dictionary''

Is there a way to get the results of the query in dictionary format when using flask-MySQL?

解决方案

You can follow this answer: https://stackoverflow.com/a/41388992/3129414

Existing code modification:

  • use DictCursor in MySQL initialization
  • remove dictionary=True from cursor
  • use json package to convert dictionary items to json format

app.py:

import json
from flask import Flask
from flaskext.mysql import MySQL
from pymysql.cursors import DictCursor

app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = '123'
app.config['MYSQL_DATABASE_DB'] = 'practice_db'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql = MySQL(cursorclass=DictCursor)
mysql.init_app(app)
conn = mysql.connect()

@app.route("/", methods=['GET'])
def home():
    email_address = 'dummy@example.com'
    cursor = conn.cursor();
    cursor.execute(
            'SELECT * FROM user_table WHERE email = (%s)', (email_address,)
        )
    users = cursor.fetchall()
    return json.dumps(users)

app.run(debug=True)

Screenshot:

这篇关于TypeError:cursor()使用flaskext.mysql获得了意外的关键字参数'dictionary'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆