将flask项目从python2更新为python3

时间:2015-07-06 07:23:08

标签: python python-3.x flask

我的小瓶子项目在python2上正常运行,但是当我升级到python3时,遇到了一些问题:

首先,我的文件'树:

.
├── app
│   ├── app1
│   │   ├── app1.py
│   │   ├── __init__.py
│   ├── __init__.py
│   ├── templates
│        ├── base.html
│        └── index.html
├── config.py
├── README.md
├── requirements.txt
├── run.py
├── shell.py
└── test.db

run.py:

from app import app
app.run(debug=True)

应用程序/ __ INIT __ PY:

from flask import Flask, url_for, render_template
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask.ext.sqlalchemy import SQLAlchemy
from flask_login import LoginManager

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)

login_manager = LoginManager()
login_manager.init_app(app)

from app1.app1 import mod as app1

当我使用python2运行时:

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat

没问题,但是在python3上:

Traceback (most recent call last):
  File "run.py", line 4, in <module>
    from app import app
  File "/home/chenhj/flask/multiapp/app/__init__.py", line 18, in <module>
    from app1.app1 import mod as app1
ImportError: No module named 'app1'
谁知道为什么?新手到python3并需要帮助:)

1 个答案:

答案 0 :(得分:6)

您正在使用隐式相对导入(Python 2模型);您需要使用绝对引用或显式相对导入:

from .app1.app1 import mod as app1

其中前导.表示其余部分相对于当前包,或

from app.app1.app1 import mod as app1

请参阅PEP 328 - Imports: Multi-Line and Absolute/Relative

然而,您可能会遇到其他问题。移植并不是那么简单,请阅读Porting to Python 3 book中的问题。这个问题是a common migration problem