Python mysql服务器sqlalchemy上未提交更新
我能够对我的Mysql数据库执行“选择”查询。 但是,“insert”不会更改数据库,只会更改python对象。因此,当我重新启动flask应用程序时,所有提交的(?)版本都消失了 观点:Python mysql服务器sqlalchemy上未提交更新,python,mysql,flask,sqlalchemy,flask-sqlalchemy,Python,Mysql,Flask,Sqlalchemy,Flask Sqlalchemy,我能够对我的Mysql数据库执行“选择”查询。 但是,“insert”不会更改数据库,只会更改python对象。因此,当我重新启动flask应用程序时,所有提交的(?)版本都消失了 观点: from flask import Flask, render_template, request, redirect, url_for, flash, Response from sqlalchemy import exc from models import * app = Flask(__name__
from flask import Flask, render_template, request, redirect, url_for, flash, Response
from sqlalchemy import exc
from models import *
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'kjhS7usfHGJHDez78'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqldb://admin:admin@127.0.0.1:3306/grenier'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)
db.create_all()
@app.route('/ajax/submit_edition', methods=['POST'])
def submit_edition():
if request.method == 'POST':
given_id=1
show = Shows.query.filter_by(id=given_id).first()
show.short_description = "Hello"
try:
db.session.commit()
db.session.flush()
return "ok"
except exc.SQLAlchemyError:
return "Error in commiting the edition"
没有发现特别的异常。路线始终返回“ok”
型号:
from sqlalchemy import Column, ForeignKey
from sqlalchemy.dialects.mysql import LONGTEXT, YEAR
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Shows(db.Model):
__tablename__ = "shows"
id = Column(db.Integer, ForeignKey("programmation.id"), primary_key=True)
date = Column(db.DATETIME)
title = Column(db.VARCHAR(50))
short_description = Column(db.VARCHAR(200))
type = Column(db.VARCHAR(20))
background_image = Column(db.VARCHAR(150))
content = Column(LONGTEXT)
def serialize(self, whatTo):
result = {}
if 'id' in whatTo:
result['id'] = self.id
if 'date' in whatTo:
result['date'] = str(self.date)
if 'title' in whatTo:
result['title'] = self.title
if 'short_description' in whatTo:
result['short_description'] = self.short_description
if 'type' in whatTo:
result['type'] = self.type
if 'background_image' in whatTo:
result['background_image'] = self.background_image
if 'content' in whatTo:
result['content'] = self.content
return result
class Programmation(db.Model):
__tablename__ = "programmation"
id = Column(db.Integer, primary_key=True)
semester = Column(db.Integer)
year = Column(YEAR)
当我查看日志时,会为select创建sql请求。但是对于insert commit(),没有任何内容
谢谢大家! 问题在于使用两个不同的
SQLAlchemy
实例。当您调用db.create_all()
方法时,它会创建从db.Model
继承的所有表,但在您的视图中,您没有从db=SQLAlchemy(app)
继承的任何模型。您的所有模型都继承自其他SQLAlchemy实例。要解决此问题,请将db
对象从视图导入模型模块,并将其用作继承的父类:
#models.py
from views import db
#db = SQLAlchemy() #remove this line
class Show(db.Model):
...