python 培养瓶应用

2lpgd968  于 2022-12-28  发布在  Python
关注(0)|答案(1)|浏览(107)

我已经开始学习Python的后端开发,特别是在Flask中.但是总是遇到新的问题
项目结构

|
 |
  -- blog
 |     -- templates
 |      |
 |       -- *html files*
 |     -- __init__.py
 |     -- DataBase.py
 |     -- routes.py
 |     -- users.db
 |     -- user.sql
 |
  -- run.py
  • 内部运行. py:*
from blog import app

if __name__ == '__main__':
    app.run(debug=True)
  • 在__***初始化__. py:**内部
from flask import Flask
from blog import routes

app = Flask(__name__)
  • 内部数据库. py:*
import sqlite3

class DataBase:
    def __init__(self, db, schema):
        self.db = db
        self.schema = schema

    # Connect
    def get_connection(self):
        conn = sqlite3.connect(self.db)
        conn.row_factory = sqlite3.Row
        return conn

    # Initialize
    def init_db(self):
        conn = sqlite3.connect(self.db)
        with open(self.schema, 'r') as s:
            conn.executescript(s.read())

        conn.commit()
        conn.close()
    
    # Get All Data from database
    def getAllData(self):
        conn = self.get_connection()
        users = conn.execute("""SELECT * FROM users""").fetchall()

        conn.close()
        return users
  • 路线内。py:*
from blog import app
from DataBase import DataBase
from flask import render_template

data = DataBase('users.db', 'user.sql')

@app.route('/', methods=["GET"])
@app.route('/home', methods=["GET"])
def about():
    users = data.getAllData()
    return render_template('home.html', users=users)

@app.route('/team/<int:user_id>', methods=["GET"])
def members(user_id):
    if user_id == 1:
        return render_template('mirshod.html')

    elif user_id == 2:
        return "Hello World"

@app.route('/team', methods=["GET", "POST"])
def team():
    users = data.getAllData()
    return render_template('home.html', users=users)

在重组我的项目之前一切都很好,但重组后,我得到错误时,试图运行我的项目

Try 'python -m flask run --help' for help.

Error: While importing 'run', an ImportError was raised:

Traceback (most recent call last):
File "D:\\flaskMarket\\lib\\site-packages\\flask\\cli.py", line 218, in locate_app
__import__(module_name)
File "D:\\fastApiProject\\flaskProject\\run.py", line 1, in \<module\>
from blog import app
File "D:\\fastApiProject\\flaskProject\\blog\__init_\_.py", line 2, in \<module\>
from blog import routes
File "D:\\fastApiProject\\flaskProject\\blog\\routes.py", line 1, in \<module\>
from blog import app
ImportError: cannot import name 'app' from partially initialized module 'blog' (most likely due to a circular import) (D:\\fastApiProject\\flaskProject\\blog\__init_\_.py)

Process finished with exit code 2
2g32fytz

2g32fytz1#

你并没有问问题,所以我会解释为什么你会得到这个错误。

  1. run.py正在尝试从blog导入app
    1.执行此操作时,__init__.py文件尝试从blog导入routes
    1.在routes.py内部,它尝试从blog导入app
    ......因此我们回到第2步。这意味着这将无限循环。谢天谢地,Python意识到了这一点,并立即崩溃。
    要解决此问题,您需要设置导入,使app在导入时已经加载,或者设置为不递归导入app(例如将app对象直接放入routes.py):
app = Flask(__name__)
data = DataBase('users.db', 'user.sql')

@app.route('/', methods=["GET"])
@app.route('/home', methods=["GET"])
...

相关问题