首页 > 解决方案 > ModuleNotFoundError:没有名为“第一个”的模块

问题描述

我正在尝试在我的终端中创建一个数据库,但是当我尝试它时,我总是在使用时遇到此错误from first import db

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'first'

这是我的代码

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
db = SQLAlchemy(app)

class BlogPost(db.Model):
    id = db.Column(db.Integer, primary_key= True)
    Title = db.Column(db.String(100), nullable= False)
    Content = db.Column(db.Text, nullable= False)
    Date_posted = db.Column(db.DateTime, nullable= False, default=datetime.utcnow)

    def __repr__(self):
        return "Blog Post" + str(self.id)


all_posts = [

    {
        'Title': 'Post 1',
        'Content': "This is the first content"

     },
    {
        'Title': 'Post 2',
        'Content': 'This is the second content'
    }
]

@app.route('/')
def index():
    return render_template("index.html")

@app.route('/blog-posts')
def blog_posts():
    return render_template("posts.html", posts = all_posts)


@app.route('/home')
def hello():
    return "My first python website"


if __name__ == '__main__':
    app.run(debug= True)

我只安装了 python 3.8。

可能是什么问题呢?我已经搜索了互联网并在其他平台上使用了所有建议,但没有解决方案。Flask 和 flask-sqlalchemy 已正确安装。

这是我在创建此项目时用作指南的 youtube 视频: https ://www.youtube.com/watch?v=3mwFC4SHY-Y

标签: python-3.xflaskflask-sqlalchemy

解决方案


好吧,我假设您已经创建了一个名为first. 我列出了可能出错的地方:

  1. 您在错误的目录中。
  2. 您尚未安装必要的软件包。(不太可能)
  3. 根据教程,文件名是app.py他在那里执行from app import db的。只需确保您的文件名正确。

我想不出任何其他可能的原因,除非first您创建了一个包来存储项目的 python 文件,如routes.py,models.py等。在这种情况下,您需要__init__.py在包目录中有文件并初始化appdb__init__.py文件中


推荐阅读