[英]Flask module not found even though it's installed
我正在關注 flask 上的python 教程,我已經創建了虛擬環境並且代碼運行良好沒有問題。 但是當我在虛擬環境中打開交互式 shell 並鍵入:
from app import db
我收到此錯誤:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Repo\flask todo app\app.py", line 1, in <module>
from flask import Flask, render_template
ModuleNotFoundError: No module named 'flask'
當我嘗試安裝 flask 時,它說它已經安裝,我不確定我做錯了什么?
完整控制台 output:
(venv) C:\Repo\flask todo app>python3
Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from app import db
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Repo\flask todo app\app.py", line 1, in <module>
from flask import Flask, render_template
ModuleNotFoundError: No module named 'flask'
app.py
中的代碼:
from email.policy import default
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
completed = db.Column(db.Boolean, default=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return '<Task {}>'.format(self.id)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
注:我在這個路徑下可以看到flask.exe
:
C:\Users\username\AppData\Local\Programs\Python\Python39\Scripts
但是好像我在shell中使用的是python 3.10.2版本,不確定這里是否相關。
編輯:我看到你在你的控制台中運行python3
......就是這樣。 請記住,您必須打開 select 程序。 您應該改為運行python3 <your_program_name>
。
不過,使用flask shell
會更容易。 要使用它,請在虛擬環境中從您的項目目錄運行flask shell
命令。
要使用flask shell
訪問您的項目變量,您必須創建一個shell_context_processor
,如下所示:
# Insert this between your route definitions and the run statement
@app.shell_context_processor
def make_shell_context_processor():
# The dictionary below will include any variable you want to access from the flask shell. Eventually you'll want to include here, for example, your database models
return dict(db = db )
Miguel Grinberg(一本優秀的 Flask 書籍和幾門課程的作者) 在他的博客中有一個很好的條目,他在其中詳細解釋了 shell 上下文處理器請看一看(轉到“ Shell 上下文”部分,在標題為“玩弄數據庫”)如果您對 Flask 有任何其他疑問,請隨時查看他的其他條目。
你確定安裝沒問題嗎? 如果沒有,請檢查並確保。 在 windows 上安裝 flask
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.