sqlite flask automap_base中的SQLAlchemy不Map类?

ssgvzors  于 2023-03-13  发布在  SQLite
关注(0)|答案(1)|浏览(170)

长时间的侦听器第一次调用。我正在制作一个flask应用程序来创建一个小型的SQLite数据库API。就像世界上最简单的事情一样。我可以很好地查询数据库模式,所以我知道引擎正在工作。但是当我用一个绝对的类名声明一个类对象时,我得到了一个AttributeError: 'function' object has no attribute 'WarID'。这个错误太常见了,我无法找到任何东西。帮帮我,Obi-Wan Kenobi。

这里是app.py

import numpy as np

import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func

from flask import Flask, jsonify

#################################################
# Database Setup
#################################################
try:
    engine = create_engine("sqlite:///static/data/iWars.sqlite")

    # reflect an existing database into a new model
    Base = automap_base()
    # reflect the tables
    Base.prepare(autoload_with=engine)
    print("All about that base")
    print(Base)
    # # Save reference to the table
    # tribes = Base.classes.Tribes
    wars = Base.classes.Wars
    print("yes no maybe")
except Exception as e:
    print("Hey what's up looks like something gnarly happened")
    print(e)

#################################################
# Flask Setup
#################################################
app = Flask(__name__)

#################################################
# Flask Routes
#################################################

@app.route("/")
def welcome():
    """List all available api routes."""
    return (
        f"Available Routes:<br/>"
        # f"/api/v1.0/tribes<br/>"
        f"/api/v1.0/wars<br/>"
    )

@app.route("/api/v1.0/wars")
def wars():
    # Create our session (link) from Python to the DB
    session = Session(engine)

    # Query all
    results = session.query(wars.WarID).all()

    session.close()

    # Create a dictionary from the row data and append to a list of all_passengers
    all_passengers = []
    for id in results:
        wars_dict = {}
        wars_dict["id"] = id
        all_passengers.append(wars_dict)

    return jsonify(all_passengers)

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

这是跑步

请注意,一旦它到达对象声明,它就会进入except代码块,其中只有Wars作为异常,然后当我打开路由时,我会看到所显示的错误。

(mlenv) ianmacsmacbook:USIndigenousWars ianmacmoore$ python app.py
All about that base
<class 'sqlalchemy.ext.automap.Base'>
Hey what's up looks like something gnarly happened
Wars
 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with watchdog (fsevents)
All about that base
<class 'sqlalchemy.ext.automap.Base'>
Hey what's up looks like something gnarly happened
Wars
 * Debugger is active!
 * Debugger PIN: 955-667-953
127.0.0.1 - - [11/Mar/2023 09:54:49] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [11/Mar/2023 09:54:56] "GET /api/v1.0/wars HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/opt/anaconda3/envs/mlenv/lib/python3.7/site-packages/flask/app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "/opt/anaconda3/envs/mlenv/lib/python3.7/site-packages/flask/app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "/opt/anaconda3/envs/mlenv/lib/python3.7/site-packages/flask/app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/opt/anaconda3/envs/mlenv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/opt/anaconda3/envs/mlenv/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/opt/anaconda3/envs/mlenv/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/opt/anaconda3/envs/mlenv/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/opt/anaconda3/envs/mlenv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/opt/anaconda3/envs/mlenv/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/opt/anaconda3/envs/mlenv/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/ianmacmoore/Documents/BluePlusRed/USIndigenousWars/app.py", line 89, in wars
    results = session.query(wars.WarID).all()
AttributeError: 'function' object has no attribute 'WarID'
127.0.0.1 - - [11/Mar/2023 09:54:56] "GET /api/v1.0/wars?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [11/Mar/2023 09:54:56] "GET /api/v1.0/wars?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [11/Mar/2023 09:54:56] "GET /api/v1.0/wars?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
127.0.0.1 - - [11/Mar/2023 09:54:56] "GET /api/v1.0/wars?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -

以下是最初写入数据库时使用的类定义

class Against(Base):
    __tablename__ = 'Against'
    TribeID = Column(Integer, primary_key=True)
    AgainstCode = Column(Integer)
    WarID = Column(Integer)

class Tribes(Base):
    __tablename__ = 'Tribes'
    TribeID = Column(Integer, primary_key=True)
    TribeName = Column(String(255))
    TribeName2 = Column(String(255))
    TribeName3 = Column(String(255))

class Wars(Base):
    __tablename__ = 'Wars'
    WarID = Column(Integer, primary_key=True)
    WarName = Column(String(255))
    StartYear = Column(Integer)
    EndYear = Column(Integer)
    WikiLink = Column(String(255))
    LengthYears = Column(Integer)

class YearSum(Base):
    __tablename__ = 'YearSum'
    Year = Column(Integer, primary_key=True)
    SumWars = Column(Integer)
    y = Column(Integer)

下面是从同一数据库上的Jupyter Notebook创建的表对象

一个三个三个一个

这是我正在运行的

conda list '^(python|flask|sqlal)'
# packages in environment at /opt/anaconda3/envs/mlenv:
#
# Name                    Version                   Build  Channel
flask                     1.1.2              pyhd3eb1b0_0  
python                    3.7.13               hdfd78df_0  
python-dateutil           2.8.2              pyhd3eb1b0_0  
python-fastjsonschema     2.16.2           py37hecd8cb5_0  
python-libarchive-c       2.9                pyhd3eb1b0_1  
python-lsp-black          1.2.1            py37hecd8cb5_0  
python-lsp-jsonrpc        1.0.0              pyhd3eb1b0_0  
python-lsp-server         1.5.0            py37hecd8cb5_0  
python-slugify            5.0.2              pyhd3eb1b0_0  
python-snappy             0.6.0            py37h23ab428_3  
python.app                3                py37hca72f7f_0  
sqlalchemy                1.4.39           py37hca72f7f_0

感谢您的时间和关注。

czq61nw1

czq61nw11#

自动Map类wars和route函数wars的声明都是在模块的顶级命名空间中声明的,因此route函数的声明会覆盖自动Map类。
错误消息
“function”对象没有属性“WarID”
指的是路由函数,* 而不是 * 自动Map的类。
请为其中一个选择其他名称,该名称不与命名空间中的任何其他名称冲突。

相关问题