我正在尝试创建一个Flask Web应用程序,该应用程序从用户那里获取输入并将其保存到数据库(sqlite3)中。我为“航班”表定义了一个“航班”类,以注册客户将要旅行的航班。还有一个用于存储乘客姓名的“乘客”表。
================================================ =====================
我正在Windows 7 OS的Visual Studio 2019中运行代码。
================================================ =====================
这是我的模型课。
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db=SQLAlchemy()
class Flight(db.Model):
"""Flight class"""
__tablename__ = "flights"
id = db.Column(db.Integer, pimary_key=True)
origin = db.Column(db.String, nullable=False)
destination = db.Column(db.String, nullable=False)
duration = db.Column(db.Integer, nullable=False)
class Passenger(db.Model):
"""Passenger class"""
__tablename__ = "passengers"
id = db.Column(db.Integer, pimary_key=True)
name = db.Column(db.String, nullable=False)
flight_id = db.Column(db.String, db.Foreignkey("flights.id"), nullable=False)
这是我的Flask代码:
import csv
import os
from datetime import datetime
from flask import Flask, render_template, request
from models import *
app = Flask(__name__)
@app.route('/')
def index():
flights = Flight.query.all()
return render_template("index.html", flights=flights)
@app.route('/book', methods=["POST"])
def book():
"""Book a flight"""
#Get form information
name=request.form.get("name")
try:
flight_id=int(request.form.get("flight_id"))
except Value_Error:
return render_template('error.html', message='Invalid flight number')
#Make sure flight exists:
flight=Flight.query.get(flight_id)
if flight is None:
return render_template("error.html", message="No such flight with that id.")
#Add Passenger
passenger=Passenger(name=name, flight_id=flight_id)
db.session.add(passenger)
db.session.commit()
return render_template("success.html")
@app.route("/flights")
def flights():
"""List all flights"""
flights=Flight.query.all()
return render_template("flights.html", flights=flights)
@app.route("/flights/<int:flight_id>")
def flight(flight_id):
"""List details about a single flight"""
#Make sue flight exists
flight=Flight.query.get(flight_id)
if flight is None:
return render_template("error.html", message="No such flights")
#Get all passengers
passengers=Passenger.query.filter.by(flight_id=flight_id).all()
return render_template("flight.html", flight=flight, passengers=passengers)
if __name__=="__main__":
app.run(debug=True, port=5000)
这是我得到的错误:
C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\sql\base.py:299: SAWarning: Can't validate argument 'pimary_key'; can't locate any SQLAlchemy dialect named 'pimary'
% (k, dialect_name)
Traceback (most recent call last):
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\ptvsd_launcher.py", line 119, in <module>
vspd.debug(filename, port_num, debug_id, debug_options, run_as)
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\debugger.py", line 41, in debug
run(address, filename, *args, **kwargs)
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_local.py", line 80, in run_file
run(argv, addr, **kwargs)
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_local.py", line 140, in _run
_pydevd.main()
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\pydevd.py", line 2329, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\pydevd.py", line 1664, in run
return self._exec(is_module, entry_point_fn, module_name, file, globals, locals)
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\pydevd.py", line 1671, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\_pydev_imps\_pydev_execfile.py", line 25, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:\Users\Master 1TB\source\repos\final_python_dbflask\final_python_dbflask\final_python_dbflask.py", line 10, in <module>
from models import *
File "C:\Users\Master 1TB\source\repos\final_python_dbflask\final_python_dbflask\models.py", line 16, in <module>
class Flight(db.Model):
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask_sqlalchemy\model.py", line 67, in __init__
super(NameMetaMixin, cls).__init__(name, bases, d)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask_sqlalchemy\model.py", line 121, in __init__
super(BindMetaMixin, cls).__init__(name, bases, d)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\ext\declarative\api.py", line 75, in __init__
_as_declarative(cls, classname, cls.__dict__)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 131, in _as_declarative
_MapperConfig.setup_mapping(cls, classname, dict_)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 160, in setup_mapping
cfg_cls(cls_, classname, dict_)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 194, in __init__
self._early_mapping()
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 199, in _early_mapping
self.map()
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 696, in map
self.cls, self.local_table, **self.mapper_args
File "<string>", line 2, in mapper
File "<string>", line 2, in __init__
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\util\deprecations.py", line 130, in warned
return fn(*args, **kwargs)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\orm\mapper.py", line 716, in __init__
self._configure_pks()
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\orm\mapper.py", line 1397, in _configure_pks
% (self, self.persist_selectable.description)
sqlalchemy.exc.ArgumentError: Mapper mapped class Flight->flights could not assemble any primary key columns for mapped table 'flights'
The thread 0x1 has exited with code 0 (0x0).
The program 'python.exe' has exited with code 0 (0x0).
我没有在同一张表中定义两个primary_key,但仍然出现此错误映射器映射类Flight-> flights无法为映射表'flights'组装任何主键列。我是一名学生,试图使用SQLAlchemy学习数据库。请帮助我。
答案 0 :(得分:0)
在您的Flight
和Passenger
类中,您拼错了primary_key
:
id = db.Column(db.Integer, pimary_key=True)
# ^ Note lack of 'r' here