Heim > Fragen und Antworten > Hauptteil
#!/usr/bin/python
#coding=utf-8
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
class News(db.Model):
""" 新闻模型 """
__tablename__ = 'news'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(200), nullable=False)
content = db.Column(db.String(2000), nullable=False)
is_valid = db.Column(db.Boolean, default=True)
created_at = db.Column(db.DateTime)
updated_at = db.Column(db.DateTime)
comments = db.relationship('Comments', backref='news',
lazy='dynamic')
def __repr__(self):
return '<News %r>' % self.title
class Comments(db.Model):
""" 新闻评论 """
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(2000), nullable=False)
is_valid = db.Column(db.Boolean, default=True)
created_at = db.Column(db.DateTime)
updated_at = db.Column(db.DateTime)
new_id = db.Column(db.Integer, db.ForeignKey('news.id'))
def __repr__(self):
return '<News %r>' % self.content
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:123456@127.0.0.1/flask_test'
if __name__ == '__main__':
app.run(debug=True)
打算学习创建数据库的,但是提示报错,
>>> from test_orm import db
D:\mycodes\virtual\flask-test\lib\site-packages\flask_sqlalchemy\__init__.py:819
: UserWarning: SQLALCHEMY_DATABASE_URI not set. Defaulting to "sqlite:///:memory:".
'SQLALCHEMY_DATABASE_URI not set. Defaulting to '
>>>
我去看了一下源码
if 'SQLALCHEMY_DATABASE_URI' not in app.config:
warnings.warn(
'SQLALCHEMY_DATABASE_URI not set. Defaulting to '
'"sqlite:///:memory:".'
)
上面说。。。SQLALCHEMY_DATABASE_URI不在app.config里面。。。但是我上面的编码。。确实在这个里面。。我崩溃。。。求助大神们。。。哪出错了。。
大家讲道理2017-04-18 10:30:11
找到问题点了,第一个
app.config 要在 db = SQLAlchemy(app) 之前
第二个在python3中的url使用是
mysql+pymysql://
PHPz2017-04-18 10:30:11
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:123456@127.0.0.1/flask_test'
将这两句调换顺序,应该是需要在初始化 db 前设置URI
另 URI 格式是不是有问题,官网文档