from flask import Flask from flask_sqlalchemy import SQLAlchemy from datetime import datetime app = Flask(__name__) HOSTNAME = '127.0.0.1' PORT = '3306' DATABASE = 'new' USERNAME = 'root' PASSWORD = '123456' DB_URI = 'mysql+pymysql://{username}:{password}@{host}:{port}/{database}?charset=utf8'.format( username=USERNAME, password=PASSWORD, host=HOSTNAME, port=PORT, database=DATABASE) app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI db = SQLAlchemy(app) class News(db.Model): __tablename__ = 'news' id = db.Column(db.Integer, autoincrement=True, primary_key=True) title = db.Column(db.String(50), nullable=False) content = db.Column(db.Text) time = db.Column(db.DateTime, default=datetime.now) author = db.Column(db.String(50), nullable=False) def __repr__(self): return '<News(title:%s,content:%s,time:%s,author:%s)>'%(self.title, self.cntent, self.time, self.author) with app.app_context(): db.drop_all() db.create_all() with app.app_context(): news1 = News(title='web开发', content='基于python的web开发技术', author='flask') news2 = News(title='web前端', content='Bootstrap前端开发框架', author='bootstrap') db.session.add_all([news1,news2]) db.session.commit() with app.app_context(): news = db.session.query(News).filter(News.author=='bootstrap').all() print(news)这段代码为什么print没有输出成功
时间: 2024-02-28 16:55:50 浏览: 74
根据你提供的代码,似乎有一个语法错误。在类News中的__repr__方法中,self.cntent应该改为self.content才能正确输出。修改后的代码如下:
```
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'new'
USERNAME = 'root'
PASSWORD = '123456'
DB_URI = 'mysql+pymysql://{username}:{password}@{host}:{port}/{database}?charset=utf8'.format(
username=USERNAME, password=PASSWORD, host=HOSTNAME, port=PORT, database=DATABASE)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
db = SQLAlchemy(app)
class News(db.Model):
__tablename__ = 'news'
id = db.Column(db.Integer, autoincrement=True, primary_key=True)
title = db.Column(db.String(50), nullable=False)
content = db.Column(db.Text)
time = db.Column(db.DateTime, default=datetime.now)
author = db.Column(db.String(50), nullable=False)
def __repr__(self):
return '<News(title:%s,content:%s,time:%s,author:%s)>'%(self.title, self.content, self.time, self.author)
with app.app_context():
db.drop_all()
db.create_all()
with app.app_context():
news1 = News(title='web开发', content='基于python的web开发技术', author='flask')
news2 = News(title='web前端', content='Bootstrap前端开发框架', author='bootstrap')
db.session.add_all([news1,news2])
db.session.commit()
with app.app_context():
news = db.session.query(News).filter(News.author=='bootstrap').all()
print(news)
```
请检查代码中是否存在其他语法错误或配置错误,例如数据库连接配置是否正确。同时,建议使用try-except语句来捕获异常并输出错误信息,以便更好地排查问题。
阅读全文