I am following this python tutorial on flask, I have created the virtual environment and the code runs fine without issues. But when I open an interactive shell inside the virtual environment and type:
from app import db
I get this error:
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'
When I try to install flask it says it's already installed, I am not sure what I am doing wrong?
The full console 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'
The code in 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)
Note: I can see flask.exe under this path:
C:\Users\username\AppData\Local\Programs\Python\Python39\Scripts
But it seems like I am using python 3.10.2 version in the shell, not sure if it's relevant here.
EDIT: I see that you are running python3 in your console... and that's it! Remember that you have to select a program to open. You should run python3 <your_program_name> instead.
Still, it will be easier for you to use the flask shell instead. To use it, run the flask shell command from your project directory while inside the virtual environment.
To access your project variables using the flask shell you have to create a shell_context_processor as follows:
# 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 (the author of an excellent Flask book and several courses) has an excellent entry in his blog where he explains the shell context processor in detail Do take a look at it (go to the "Shell Context" part, after the one titled "Playing with the database") and feel free to check his other entries if you have any other doubts with Flask.
Do you ensure the installation is ok? If not, please check it and ensure it.install flask on windows
Related
So I've been following along a course which deals with web services and I've encountered an issue with flask dependencies.
my requirements.txt looks like this:
PyMySQL==1.0.2
cryptography==37.0.4
Flask==2.2.2
flask_sqlalchemy==2.5.1
sqlalchemy < 1.4.0
flask_migrate==2.7.0
flask_script==2.0.6
sqlalchemy_utils==0.38.3
And my manage.py which I run with python manage.py db init
looks like this
from flask import Flask
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from configuration import Configuration
from models import database
from sqlalchemy_utils import database_exists, create_database
application = Flask(__name__)
application.config.from_object(Configuration)
migrate = Migrate(application, database)
manager = Manager(application)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
if(not database_exists(Configuration.SQLALCHEMY_DATABASE_URI)):
create_database(Configuration.SQLALCHEMY_DATABASE_URI)
manager.run()
When I use flask 2.2.2 I get this error:
Traceback (most recent call last):
File "/home/remax/PycharmProjects/V3/manage.py", line 3, in <module>
from flask_script import Manager
File "/home/remax/PycharmProjects/V3/venv/lib/python3.10/site-packages/flask_script/__init__.py", line 15, in <module>
from flask._compat import text_type
ModuleNotFoundError: No module named 'flask._compat'
But when I go back to flask 1.1.2 I get this
ImportError: cannot import name 'escape' from 'jinja2'
I honestly don't know how to deal with this, I've been trying to find a solution all morning
flask-script has been obsolete since Flask 0.11 added command support. It hasn't been updated to work with Flask 2, so if you want to use Flask 2, you'll need to get rid of it (and use Flask's native command support instead).
If you have upgraded Flask to 2.x and decide to downgrade to 1.x, you will need to install compatible versions of supporting packages (werkzeug, itsdangerous, jinja2). It might be easiest to just uninstall all packages from your virtualenv (you're using one, right?) and reinstall the correct versions, but you can also do it by hand.
I am new to the python and flask. I am watching a you tube tutorial and i am stuck at 20:05 where he run the code "from app import db". I follow exactly the step he taught but yet I still face this problem.Below are the program I type and at the terminal there it shows the error.
The Program:
from flask import Flask, render_template, url_for
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) #This is to set the character the person input
date_created = db.Column(db.DateTime, default=datetime.utcnow) #This is to set the time
def __repr__(self):
return '<Task %r>' % self.id
#app.route('/')
def index():
return render_template('index.html')
if __name__ =="__main__":
app.run(debug=True)
The Program I type In Terminal:
from app import db
The Respond After Typing The Command At Terminal:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Visual Studio Code Project\app.py", line 1, in <module>
from flask import Flask, render_template, url_for
ModuleNotFoundError: No module named 'flask'
The You Tube Link: https://www.youtube.com/watch?v=Z1RJmh_OqeA&t=335s
The Program
Can anyone help me please?
"flask" is used as a Python module in VSCode, we need to install it in the current Python environment: please use "pip install flask" (or "pip3 install flask") in the VSCode terminal.
In addition, the module "flask_sqlalchemy" also needs to be installed. (pip install flask_sqlalchemy)
For more information about the use of "flask" in VSCode, please refer to Flask Tutorial in Visual Studio Code.
Update:
I am taking a webdev with python class and the current lecture involves creating databases with sqlalchemy. I have attached the script. In order for lines 7 and 10 to work, the "models" module needs to be installed. However, when I try to install the module, I get the following error:
Collecting models
Using cached https://files.pythonhosted.org/packages/92/3c/ac1ddde60c02b5a46993bd3c6f4c66a9dbc100059da8333178ce17a22db5/models-0.9.3.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\nikol\AppData\Local\Temp\pip-install-_om8dbe7\models\setup.py", line 25, in <module>
import models
File "C:\Users\nikol\AppData\Local\Temp\pip-install-_om8dbe7\models\models\__init__.py", line 23, in <module>
from base import *
ModuleNotFoundError: No module named 'base'
I have found that models has a newer version called doqu, but I can't seem to get doqu to work with this code. I tried manually installing models but didn't succeed.
from flask import Flask, render_template, request
from models import *
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = ""
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
def main():
db.create_all()
if __name__ == "__main__":
main()
You are misunderstanding what your class is asking of you. You are not asked to install the models project (which is a project that was last released in 2010, and as you found, broken, since renamed several times, and is indeed now called Doqu).
You are supposed to create your own models.py module, to store your SQLAlchemy models in; it is a common pattern to use that name in your projects.
This is my microblog.py file, environment, centos7.
from app import app,db
from app.models import User,Post
#app.shell_context_processor
def make_shell_context():
return {'db':db,'User':User,'Post':Post}
when I input flask shell, and want to add User:
Python 3.6.5 (default, Apr 10 2018, 17:08:37)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
App: app [production]
Instance: /root/code/microblog/instance
>>> User
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'User' is not defined
>>>
This is what happens if you run flask shell (or venv/bin/flask shell) without first setting FLASK_APP=microblog.py.
FLASK_APP=microblog.py flask shell
Should get you going.
You need to import User from app.models. To do this, in terminal type:
>>> from app.models import User
>>> User
Then, user should be defined. Let me know if this works for you!
I am new to python and I am following "Learn Python the Hard Way" by Zed Shaw. In chapter 50, he asks you to download the lpthw.web framework and run the following the program I listed on the bottom. However, when I try to do so, I get the following error. The book recommended using Python 2 but I decided to try Python 3. I am on a windows 7 computer. If the problem is that I am using Python 3, is there a way to make that framework Python 3 friendly or which other one is recommended for someone learning. Thank you very much for the help.
Error:
Traceback (most recent call last):
File "app.py", line 1, in <module>
import web
File "C:\Python33\lib\site-packages\web\__init__.py", line 14, in <module>
import utils, db, net, wsgi, http, webapi, httpserver, debugerror
ImportError: No module named 'utils'
Program:
import web
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
greeting = "Hello World"
return greeting
if __name__ == "__main__":
app.run()
pip install utils would solve your problem :)