I downloaded Flask on my Windows system using
pip install flask
it says
Requirement already satisfied.
which makes sense cause i already installed it once before using easy_install.
The official Flask website says, i just need to do this to install. Yet i get the error
ImportError: cannot import name Flask
The code i used is:
from flask import Flask
app = flask.Flask(__name__)
app.debug = True
app.run()
How can i fix this
Not sure if this is the problem, but this code should throw a NameError. If you import the Flask class like this from flask import Flask, then make your app like this app = flask.Flask(__name__), the interpreter will throw a NameError. You never imported flask, only the Flask class. The code should be changed to app = Flask(__name__) since Flask is already in the namespace.
Related
When deploying a flask application on heroku im getting the error above. The problem on heroku is that it installs dependencies and Iam not able to overwrite them then, or?
On my local server i just went to flask_uploads.py and change the imports to:
from werkzeug.utils import secure_filename
from werkzeug.datastructures import FileStorage
and this works fine.
but when deploying the flask app to heroku, how can I change the the content of flask_uploads.py after it had been installed?
flask-uploads is no longer properly maintained and has not released a fix to the updated Werkzeug API change, thus you see this error.
Just swap flask-uploads with flask-reuoloaded in your dependency list, eg requirements.txt or similar. You don't have to change your imports!
See https://github.com/jugmac00/flask-reuploaded
I've followed different tutorials to learn flask, and lately I've been trying do build something more substantial. I run my flask app with flask run. I have a app.py but no __init__.py. FLASK_APP is not set. I understand that because there's no FLASK_APP, flask looks for app.py by default. Here's the entirety of app.py:
from flask import Flask, redirect, url_for
from os import getenv
from dotenv import load_dotenv
from extensions import db, mail
from projects import por
from requests import requests
load_dotenv()
app = Flask(__name__)
def create_app():
print ('IN CREATE APP')
#SQL Alchemy
app.config['SQLALCHEMY_DATABASE_URI'] = getenv('SQLALCHEMY_DATABASE_URI', None)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = getenv('SQLALCHEMY_TRACK_MODIFICATIONS', False)
# WT-Forms
app.config['SECRET_KEY'] = 'Temporary secret key'
app.config['WTF_CSRF_TIME_LIMIT'] = None
#######
db.init_app(app)
mail.init_app(app)
app.register_blueprint(por)
app.register_blueprint(requests)
#app.route('/', methods=['GET'])
def index():
return redirect(url_for('por.por_no_sm'))
# if __name__ == "__main__":
# create_app().run()
I have 3 specific questions:
If I try to start the app with python app.py, I get ModuleNotFoundError: No module named 'flask'. But Flask is installed, and I'm running that in my virtual environment from the same directory as app.py. Why won't it run when I try it that way? Is there any advantage to using flask run rather than python app.py or vice versa?
One of the things I want to do is put the config & setup code inside an app factory. However, when I run with flask run, create_app doesn't run. What's going on there? I can make it run by uncommenting out the last 2 lines & looking for app instead of __main__, but shouldn't it run automatically?
Is there any advantage to adding a root-level __init__.py file? I tried briefly, but then none of the imports at the top of app.py worked. I kept getting a bunch of "No module named extensions", etc. errors. I can fix those by prefacing the names with dots, (e.g., from .extensions import db, mail), but what do I gain by doing that?
Thank you!
If you have a virtual env and you are getting the error ModuleNotFoundError: No module named 'flask', then you have to activate the virtual environment before you can run python app.py
If you're going to use create_app(), then the rest of your code should go under it i.e. app = Flask(__name__) and all of the app variable initializations and your route should go under it. As the name 'create app' says, you are creating the app
Upon trying to run my code on AWS Lambda, I am getting the error "Unable to import module 'lambda_function': No module named Flask"
I have already installed python and python flask in the virtual environment and all other required libraries
import Flask
from flask import Flask
from flask import jsonify
from flask import request
from flask_pymongo import PyMongo
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'users'
app.config['MONGO_URI'] = 'mongodb://127.0.:27017/users'
mongo = PyMongo(app)
#app.route('/user', methods=['POST'])
def get_userdetail():
user = mongo.db.users
output = []
for s in user.find():
output.append({'Firstname' : s['Firstname'], 'Lastname' :
s['Lastname']})
return jsonify({'result' : output})
if __name__ == '__main__':
app.run(debug=True)
I just expected the code to run but instead I am getting this error
You need first to do some steps, so the dependencies will be installed automatically when you deploy to AWS Lambda. For example to use "serverless-python-requirements" to install the requriments.txt file. For more details, you can check this: https://medium.com/#Twistacz/flask-serverless-api-in-aws-lambda-the-easy-way-a445a8805028
I also noticed that your MONGO_URI is pointing to your local folder, and that's will not work when you deploy online. Check how to make a config file with two classes, one for production and one for development. So when you deploy, you just change to Production.
I hope that will help.
I am writing a flask application with PyCharm. But Pycharm couldn't recognize Flask module. Flask installed globally on my computer as seen on screenshot. I tried virtualenv also but nothing change. Still can't find Flask. I can run Flask anywhere except Pycharm succesfully. My operating system is Windows by the way.
Here is my code snippet
from flask import Flask, render_template, url_for
app = Flask(__name__)
#app.route("/")
#app.route("/home")
def home():
return render_template("home.html")
if __name__ == "__main__":
app.run(debug=True)
Change the name of your file from flask.py to something else and it will work. Naming your file flask.py causes Python to look in your file for the Flask class, and it fails.
Naming a file site.py causes this issue.
It looks like a module named "site" is involved in importing the installed libraries, so by creating a module of the same name I prevent flask from being discovered.
Renaming my file from site.py to something else fixed the issue for me.
I have a Flask app with the following (typical, I think) structure.
repo_name
config.py
requirements.txt
run.py
/service
__init__.py
models.py
schemas.py
views.py
The run.py script has the following content
from service import app
app.run(debug=False, port=8080, host='0.0.0.0')
Inside service.__init__.py I create the Flask app, and at the end, import views.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
ma = Marshmallow(app)
import service.views
The models.py, schemas.py, and views.py are all pretty standard for simple Flask apps, and they also call from service import app or from service import models as needed.
My problem is that PyLint is throwing the error "E0401: Unable to import 'service'" for all these import calls. This is not really a "legitimate" error because I can run the code just fine.
One thing that makes the error go away is changing the import calls to from repo_name.service import .... However, this is undesirable for two reasons
The repo_name is not really related to the app. If I were to go this route, I would probably end up moving everything down a directory. Further, there's no requirement that people name the directory the same way (e.g., someone might clone it as git clone <url> foobar instead of git clone <url> repo_name, which would break code.
More importantly, this doesn't even work. When I make those changes and try to run the server, I get ModuleNotFoundError: No module named 'repo_name'.
How can I make reconcile PyLint and Flask here? Ideally I'd like to fix the issue in the "correct" way, instead of just adding a # pylint: disable= call in front of each import.