最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Flask中递归import

Flask crifan 2430浏览 0评论

Flask中,出现了递归的import错误

代码:

/Users/crifan/dev/dev_root/daryun/Projects/RunningFast/sourcecode/RunningFast-Server/runningfast/resources/Task.py

from User import location_fields, user_fields
location_fields = {
}
user_fields = {
}

/Users/crifan/dev/dev_root/daryun/Projects/RunningFast/sourcecode/RunningFast-Server/runningfast/resources/User.py

from Task import task_fields
bill_fields = {
}
task_fields = {
}

错误:

Traceback (most recent call last):
  File “db_manager.py”, line 4, in <module>
    from runningfast.app import db, app, gLog
  File “/root/RunningFast/staging/runningfast/app.py”, line 116, in <module>
    from runningfast.resources.RegisterLogin import *
  File “/root/RunningFast/staging/runningfast/resources/RegisterLogin.py”, line 16, in <module>
    from User import user_fields
  File “/root/RunningFast/staging/runningfast/resources/User.py”, line 14, in <module>
    from Task import task_fields
  File “/root/RunningFast/staging/runningfast/resources/Task.py”, line 15, in <module>
    from User import location_fields, user_fields
ImportError: cannot import name location_fields

flask recursive import

python – What is the correct way to solve this circular import error with a Flask blueprint? – Stack Overflow

http://stackoverflow.com/questions/30761303/what-is-the-correct-way-to-solve-this-circular-import-error-with-a-flask-bluepri

Circular import of db reference using Flask-SQLAlchemy and Blueprints – Stack Overflow

http://stackoverflow.com/questions/22929839/circular-import-of-db-reference-using-flask-sqlalchemy-and-blueprints

python – How to fix circular import in Flask project using blueprints MySQL w/o SQLAlchemy? – Stack Overflow

【总结】

最后,去直接的把对应的模块内的全局变量定义,全部移动到一个文件内,然后上述两个文件都引用同一个文件,就可以解决递归import的问题了:

/Users/crifan/dev/dev_root/daryun/Projects/RunningFast/sourcecode/RunningFast-Server/runningfast/resources/User.py

from runningfast.models import *

/Users/crifan/dev/dev_root/daryun/Projects/RunningFast/sourcecode/RunningFast-Server/runningfast/resources/Task.py

from runningfast.models import *

/Users/crifan/dev/dev_root/daryun/Projects/RunningFast/sourcecode/RunningFast-Server/runningfast/models/__init__.py

bill_fields = {
}
task_fields = {
}
location_fields = {
}
user_fields = {
}

转载请注明:在路上 » 【已解决】Flask中递归import

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.192 seconds, using 22.11MB memory