flask的工厂函数无法启用
提示错误如下
C:\Documents and Settings\Administrator\PycharmProjects\flaskr>python manage.py runserverTraceback (most recent call last):
File "manage.py", line 7, in <module>
from app import create_app
File "C:\Documents and Settings\Administrator\PycharmProjects\flaskr\app\__init__.py", line 9, in <module>
from .views import init_views
File "C:\Documents and Settings\Administrator\PycharmProjects\flaskr\app\views.py", line 8, in <module>
from .models import User
File "C:\Documents and Settings\Administrator\PycharmProjects\flaskr\app\models.py", line 4, in <module>
from . import db
ImportError: cannot import name db
代码如下所示
__init__.py
from flask import Flaskfrom flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
import os
from .views import init_views
basedir = os.path.abspath(os.path.dirname(__file__))
bootstrap = Bootstrap()
db = SQLAlchemy()
#定义create_app函数
def create_app():
app = Flask(__name__)
#设置密匙
app.config['SECRET_KEY'] = 'hard to guess string'
#配置数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////' + os.path.join(basedir,'data.sqlite')
#app.config['SQLALCHEMY_DATABASE_URL'] = 'sqlite:////' + os.path.join(basedir,'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
#app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
bootstrap.init_app(app)
db.init_app(app)
init_views(app)
return app
models.py
from . import db#定义模型
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(64),unique=True)
users = db.relationship('User',backref='role',lazy='dynamic')
def __repr__(self):
return '<Role %r>' % self.name
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(64),unique=True,index=True)
role_id = db.Column(db.Integer,db.ForeignKey('roles.id'))
def __repr__(self):
return '<User %r>' %self.username
views.py
from flask import render_template,make_response,redirect,session,abortfrom .forms import NameForm
from .models import User
from . import db
def init_views(app):
#视图函数
@app.route('/',methods=['GET','POST'])
def index():
##在视图函数中操作数据库
form = NameForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.name.data).first()
if user is None:
user = User(username = form.name.data)
db.session.add(user)
session['known']=False
else:
session['known']=True
session['name'] = form.name.data
form.name.data=''
return redirect('index')
return render_template('index.html',form=form,name=session.get('name'),known=session.get('known',False))
@app.route('/make_response')
def make_request():
response = make_response('<h1>Hello!!!</h1>')
response.set_cookie('answer','42')
return response
@app.route('/user/<name>')
def user(name):
return render_template('user.html',name=name)
@app.route('/test/')
def test_get():
return render_template('test.html')
#重定向
@app.route('/redirect')
def redirect_test():
return redirect('http://www.baidu.com')
@app.route('/abort/<id>')
def get_abort(id):
user = load_user(id)
if not user:
abort(404)
return '<h1>Hello,%s</h1>'%user.name
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'),404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'),500
forms.py
from flask_wtf import Formfrom wtforms import StringField,SubmitField
from wtforms.validators import Required
##表单类
class NameForm(Form):
name=StringField('what is you name?',validators=[Required()])
submit =SubmitField('Submit')
回答:
把__init__.py修改一下就可以了
#!/usr/bin/env python# coding=utf-8
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
import os
# from .views import init_views
basedir = os.path.abspath(os.path.dirname(__file__))
bootstrap = Bootstrap()
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////' + os.path.join(basedir,'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
bootstrap.init_app(app)
db.init_app(app)
###下面的就是修改内容###
from .views import init_views
init_views(app)
return app
回答:
我也在学flask,可惜工作中用的是PHP。
你import 那句用的有问题。 from . Import db
这句尝试引用自己、也就是python禁止使用的循环引用,当然会报错了。尝试把db的初始化放在另一个文件中、如果在同一个package里面、用from .database import db
是OK的。
另外flask_sqlalchemy这个包是第三方开发的,进行了一些封装,但貌似和最新版flask不太兼容。学习阶段尽量减少第三方库的使用,建议直接读Sqlalchemy的官方文档。
其实还是Django的ORM最好用、可惜Django的坑太多,而且灵活性较低
回答:
from . import db 没错的,它会在__init__里找到它。
它无法导入应该是根本没有初始化,我看你没用配置文件直接写在初始化函数create_app()下面,那下面的的init_app()的方法你在哪里导入来的?没有import进来,也看不出继承哪里了。
以上是 flask的工厂函数无法启用 的全部内容, 来源链接: utcz.com/p/157651.html