(优发娱乐wwwyoufa8) flask的工厂函数无法启用

提示错误如下

C:Documents and SettingsAdministratorPycharmProjectsflaskr>python manage.py runserver
Traceback most recent call last: File "manage.py", line 7, in <module> from app import create_app File "C:Documents and SettingsAdministratorPycharmProjectsflaskrapp\__init__.py", line 9, in <module> from .views import init_views File "C:Documents and SettingsAdministratorPycharmProjectsflaskrappviews.py", line 8, in <module> from .models import User File "C:Documents and SettingsAdministratorPycharmProjectsflaskrappmodels.py", line 4, in <module> from . import db
ImportError: cannot import name db

代码如下所示

__init__.py

from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
import os
from .views import init_views basedir = os.path.abspathos.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.joinbasedir,data.sqlite #app.config[SQLALCHEMY_DATABASE_URL] = sqlite://// + os.path.joinbasedir,data.sqlite app.config[SQLALCHEMY_COMMIT_ON_TEARDOWN] = True #app.config[SQLALCHEMY_COMMIT_ON_TEARDOWN] = True bootstrap.init_appapp db.init_appapp init_viewsapp return app

models.py

from . import db #定义模型
class Roledb.Model: __tablename__ = roles id = db.Columndb.Integer,primary_key=True name = db.Columndb.String64,unique=True users = db.relationshipUser,backref=role,lazy=dynamic def __repr__self: return <Role %r> % self.name class Userdb.Model: __tablename__ = users id = db.Columndb.Integer,primary_key=True username = db.Columndb.String64,unique=True,index=True role_id = db.Columndb.Integer,db.ForeignKeyroles.id def __repr__self: return <User %r> %self.username

views.py

from flask import render_template,make_response,redirect,session,abort
from .forms import NameForm
from .models import User
from . import db def init_viewsapp: #视图函数 @app.route/,methods=[GET,POST] def index: ##在视图函数中操作数据库 form = NameForm if form.validate_on_submit: user = User.query.filter_byusername=form.name.data.first if user is None: user = Userusername = form.name.data db.session.adduser session[known]=False else: session[known]=True session[name] = form.name.data form.name.data= return redirectindex return render_templateindex.html,form=form,name=session.getname,known=session.getknown,False @app.route/make_response def make_request: response = make_response<h1>Hello!!!</h1> response.set_cookieanswer,42 return response @app.route/user/<name> def username: return render_templateuser.html,name=name @app.route/test/ def test_get: return render_templatetest.html #重定向 @app.route/redirect def redirect_test: return redirecthttp://www.baidu.com @app.route/abort/<id> def get_abortid: user = load_userid if not user: abort404 return <h1>Hello,%s</h1>%user.name @app.errorhandler404 def page_not_founde: return render_template404.html,404 @app.errorhandler500 def internal_server_errore: return render_template500.html,500

forms.py

from flask_wtf import Form
from wtforms import StringField,SubmitField
from wtforms.validators import Required ##表单类
class NameFormForm: name=StringFieldwhat is you name?,validators=[Required] submit =SubmitFieldSubmit

我也在学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进来,也看不出继承哪里了。

把__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.abspathos.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.joinbasedir,data.sqlite app.config[SQLALCHEMY_COMMIT_ON_TEARDOWN] = True app.config[SQLALCHEMY_TRACK_MODIFICATIONS] = True bootstrap.init_appapp db.init_appapp ###下面的就是修改内容### from .views import init_views init_viewsapp return app

发表评论

电子邮件地址不会被公开。 必填项已用*标注