如何让SQLAlchemy使用mysql与现有数据库

时间:2018-04-21 09:25:06

标签: python mysql json flask flask-sqlalchemy

我在使用sqlalchemy在mysql中运行现有数据库时遇到问题,因为我需要它来构建Flask RESTful api。

我在这里得到有关循环依赖的有趣错误:

from flask import Flask, request, jsonify, make_response
from flaskext.mysql import MySQL
from flask_sqlalchemy import SQLAlchemy

#from webapi import models

# mysql = MySQL()
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secretkey' #for use later
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://user:password@127.0.0.1/mydb'

db = SQLAlchemy(app)

class Extensions(db.Model):

    __tablename__ = "Extensions"

    extnbr = db.Column(db.Integer, primary_key=True, default="NULL")
    authname = db.Column(db.String(256), nullable=True, default="@nobody")
    extpriority = db.Column(db.Integer, nullable=True, default=0)
    callaccess = db.Column(db.Integer, nullable=True, default=0)
    extlocation = db.Column(db.String, nullable=True, default="NULL")
    display = db.Column(db.String, nullable=True, default="NULL")

@app.route("/")
def hello():
    return "Welcome to Python Flask App!"

@app.route("/extensions", methods=["GET"])
def get_all_extensions():
    users = Extensions.query.all()

    output = []

    for user in users:
      user_data = {}
      user_data['extnbr'] = user.extnbr
      user_data['authname'] = user.authname
      user_data['extpriority'] = user.extpriority
      user_data['callaccess'] = user.callaccess
      user_data['extlocation'] = user.extlocation
      user_data['display'] = user.display
      output.append({'extensions' : output})

    return jsonify({'users' : output})

if __name__ == "__main__":
    app.run(debug=True)

我得到关于循环依赖的错误:

调试和跟踪:

https://dpaste.de/F3uX

2 个答案:

答案 0 :(得分:1)

问题是:

output = []

for user in users:
  ...
  output.append({'extensions' : output})  # here you are adding output to the output

检查这个例子:

out = []
for i in range(2):
    out.append({'ext': out})
# output
[{'ext': [...]}, {'ext': [...]}]

你有相同的输出。我确信这不是你想要的。因此,将有问题的行更改为:output.append({'extensions' : user_data})

答案 1 :(得分:1)

这与您的output有关。您正在将包含output的字典附加到output本身,从而创建一个导致json错误的时髦数据结构。

尝试更改

 output.append({'extensions' : output})

到此:

output.append({'extensions' : user_data })

(这是我认为你想要的东西)