Python: "Cannot import flask" - python

I tried everything but couldn't import app.py. It gives me the following error
set FLASK_APP = "C:\Users\Hp\PycharmProjects\sakshi.py\app.py"
(env) C:\Users\Hp\Documents\flask_app>flask run
Serving Flask app " app.py"
Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
Debug mode: off
Usage: flask run [OPTIONS]
Error: Could not import " app".
Your help would be much appreciated!

Change the sever environment to development env.
export FLASK_APP=yourapp
export FLASK_ENV=development
and then start the server with:
flask run
If you still get error try this way:
set FLASK_ENV=development
flask run
And then run your python file.

At least one problem: spaces in the set command. From the syntax in the microsoft doc:
set [<Variable>=[<String>]]
set [/p] <Variable>=[<PromptString>]
set /a <Variable>=<Expression>
There is no space on either side of the = in the set command.
And, the path name "C:\Users\Hp\PycharmProjects\sakshi.py\app.py" is questionable. It is, at the very least, a bad idea to name a directory sakshi.py.

I could see the problem is with space between the variable and value in set command,
In windows,
set var=value
In *nix family,
export var=value
Your script name is app.py which by default flask recognizes as entry point for the app.
You only have to explicitly set the FLASK_APP variable when you are running from another directory (which you are) or the name of the script is something other than app.py. You can directly run the flask run command from the project base directory itself.

Related

Trying to run a python file in flask

I am trying to learn flask. I created a venv and installed flask. I set the flaskblog.py as FLASK_APP. But it says serving flask app 'app.py' and it fails. why is this?
I'm not sure if the image is visible. So, I'll write what I've tried below,
In the windows powershell, I cd to the directory where my venv and python script is, then
$ . vnev\Scripts\activate
$ pip install flask
$ set FLASK_APP=flaskblog.py
$ flask run
it gives me the error saying,
Serving Flask app 'app.py' (lazy loading)
Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
Debug mode: off
Usage: flask run [OPTIONS]
Try 'flask run --help' for help.
Error: Could not import 'app'.
What is wrong here? I have also tried $ setx FLASK_APP "flaskblog.py and still get the same result. I think i created this app.py using pycharm's virtual environment and now, I cannot set other files to FLASK_APP.
What should I do?

Error: Could not locate a Flask application in VSCode

I am trying to learn Flask using VScode.
The tutorial that I am following is: Python Flask Tutorial: Full-Featured Web App Part 1 - Getting Started.
I did the following things:
Created a new virtualenv in a folder using: virtualenv venv
activated it as: venv\Scripts\activate (I am on Windows 10)
After that, I created a new directory named Flask_Blog using mkdir Flask_Blog and in it, I created a new flaskblog.py file containing the following code:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello():
return 'Hello'
Then, in the terminal of VScode, I changed my working directory in order to be in the Flask_Blog directory using cd Flask_Blog.
Now, when I am doing set FLASK_APP=flaskblog.py followed by flask run, I am getting the following error:
(venv) PS C:\Users\kashy\OneDrive\Desktop\Flask\Flask_Blog> flask run
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
Usage: flask run [OPTIONS]
Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.
But
When I do the same in the cmd prompt, the code runs and I get to see the output.
I am completely new to this. Can anyone please tell me what is the mistake I am doing in VSCode and why is it working in the cmd?
Issue raised in VsCode
Under Powershell, you have to set the FLASK_APP environment variable as follows:
$env:FLASK_APP = "webapp"
Then you should be able to run "python -m flask run" inside the hello_app folder. In other words, PowerShell manages environment variables differently, so the standard command-line "set FLASK_APP=webapp" won't work.
Try Set FLASK_APP = Full path of the folder/filename.py.
This worked for me
This worked for me on the VSCode:
$env:FLASK_APP= 'C:\Python\ex003\main:app'

Set Flask environment to development mode as default?

Every time I start up my flask app the environment variable is set to production. I want to have it set to development mode by default. Otherwise every time I start my app i have to run ..
export FLASK_ENV=development
How can I set environment's default value as development in every startup?
EDIT: I am using flask in a virtual environment on a raspberry pi.
You can edit your main flask app file and add these lines:
if __name__ == '__main__':
app.run(debug=True)
Using this method you have to run your flask app with Python interpreter like this => python app.py
Best Practice:
Install python-dotenv package inside your working environment =>pip install python-dotenv
Create a file named .env, put your environment variables in it, for your case it's FLASK_ENV=development
Then add this code to your config.py or some file that will get loaded before Flask main App
from dotenv import load_dotenv
dotenv_path = join(dirname(__file__), '.env') # Path to .env file
load_dotenv(dotenv_path)
Note that: If you are using flask command to run your application, you don't need to do the third step, flask will find .env files in the project directory by itself.
Using this method, it will only set Environment variable for the project that you have added this code to.
On Linux distro, like "Raspberry pi o.s", specify the environment on the terminal with the code below.
Unless you specify the environment, flask will assume production.
export FLASK_ENV=development
flask run
Like the first answer and instead of adding the variable to a .env file which can be forgotten, do this instead.
This way, if you try to run the file in production, you'll get an assertion error to remind you to actually use a dedicated web server (which "imports" the app). If you run locally, not only will you be reminded to use a .env file, but in the case no environment file is needed, the flask env is set to development to avoid any production conflicts.
import os
app = Flask(__name__)
IS_DEV = app.env == 'development' # FLASK_ENV env. variable
# code
if __name__ == '__main__':
# guaranteed to not be run on a production server
assert os.path.exists('.env') # for other environment variables...
os.environ['FLASK_ENV'] = 'development' # HARD CODE since default is production
app.run(debug=True)

Warning message while running Flask

While I am running Flask code from my command line, a warning is appearing:
Serving Flask app "hello_flask" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
What does this mean?
As stated in the Flask documentation:
While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well and by default serves only one request at a time.
Given that a web application is expected to handle multiple concurrent requests from multiple users, Flask is warning you that the development server will not do this (by default). It recommends using a Web Server Gateway Interface (WSGI) server (numerous possibilities are listed in the deployment docs with further instructions for each) that will function as your web/application server and call Flask as it serves requests.
Try gevent:
from flask import Flask
from gevent.pywsgi import WSGIServer
app = Flask(__name__)
#app.route('/api', methods=['GET'])
def index():
return "Hello, World!"
if __name__ == '__main__':
# Debug/Development
# app.run(debug=True, host="0.0.0.0", port="5000")
# Production
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
Note: Install gevent using pip install gevent
As of Flask 1.x, the default environment is set to production.
To use the development environment, create a file called .flaskenv and save it in the top-level (root) of your project directory. Set the FLASK_ENV=development in the .flaskenv file. You can also save the FLASK_APP=myapp.py.
Example:
myproject/.flaskenv:
FLASK_APP=myapp.py
FLASK_ENV=development
Then you just execute this on the command line:
flask run
That should take care of the warning.
To remove the "Do not use the development server in a production environment." warning, run:
export FLASK_ENV=development
before flask run.
I was typing flask run and then saw this message after that I solve this issue with these:
1- Add this text in your myproject/.flaskenv :
FLASK_APP=myapp.py
FLASK_ENV=development
also you should type "pip3 install python-dotenv" for using this file .flaskenv
2-in your project folder type in terminal your flask command which one you use :
flask-3 run
First, try to the following :
set FLASK_ENV=development
then run your app.
I have been using flask for quite some time now, and today, suddenly this warning turned up. I found this.
As mentioned here, as of flask version 1.0 the environment in which a flask app runs is by default set to production. If you run your app in an older flask version, you won't be seeing this warning.
New in version 1.0.
Changelog
The environment in which the Flask app runs is set by the FLASK_ENV environment variable. If not set it defaults to production. The other recognized environment is development. Flask and extensions may choose to enable behaviors based on the environment.
in configurations or config you can add this code :
ENV = ""
same as if you try to add debug set to true like this
DEBUG = True
for more detail you can check this http://flask.pocoo.org/docs/1.0/config/#ENV
It means the programe is run on production mode even in developing environment.so to avoid that warning, you need to define this is development environment.for that,Type and run below command in project directory on terminal(linux).
export FLASK_ENV=development
if you are windows user then run,
set FLASK_ENV=development
To disable the message I use:
app.env = "development"
You have to put this in the Python-Script before you run the app with:
app.run(host="localhost")
If you encounter NoAppException and you see lazy loading the following seemed to fix the issue:
cd <project directory>
export FLASK_APP=.
export FLASK_ENV=development
export FLASK_DEBUG=1
You can begin your main script like this :
import os
if __name__ == '__main__':
os.environ.setdefault('FLASK_ENV', 'development')

Difference between run the Flask and Django application

I don't understand why if I want to run Flask application I need
(venv) $ export FLASK_APP=microblog.py
(venv) $ flask run
But if I want to run Django application I only
(venv) $ python manage.py runserver
without export DJANGO_APP=microblog.py
Why? Why I need the export app in the first case, but in the second case I don't need?
Firstly, Django and Flask are different frameworks. There's no reason why the commands to start them should be the same.
You need to export FLASK_APP to tell flask which app to run.
Doing export FLASK_APP=microblog.py sets an environment variable FLASK_APP. The flask application can then read this variable from the environment and use it to run the application.
In Python you can access environment variables from os.environ, or use the os.getenv method:
import os
flask_app = os.getenv('FLASK_APP')
If you use the django-admin command, you need to export DJANGO_SETTINGS_MODULE in a similar way:
$ export DJANGO_SETTINGS_MODULE=yourproject.settings
$ django-admin runserver
However with Django, you usually use runserver with manage.py instead of django-admin. The manage.py is specific to your project and sets the DJANGO_SETTINGS_MODULE environment variable if it hasn't been set already:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yourproject.settings")
Therefore you don't need to export DJANGO_SETTINGS_MODULE when using manage.py.
From a source code prospective, seems that the FLASK_APP variabile is used for understand which flask app run in a 'multi-flask-app' environment.
Is necessary only if the app_name from the source is not present.
The FLASK_APP env variable is used only into the find_best_app method of the cli.py file of the flask framework.
Simply in your project, you don't need something like export FLASK_APP=microblog.py unless you want environment variables
from flask import jsonify,Flask
app = Flask(__name__)
#app.route("/<Your Route>/<string:<Your Param>>")
def main(<Your Param>):
//DO LOGIC HERE
data =[{'TestData1' : "" ,<YOUR OUTPUT>}]
return jsonify(data), 200
app.run(debug=False,host="0.0.0.0",port=<PORT YOU WANT TO HOST>)
Problem: When you write the command flask run in the console, how does flask know which file to run?
Solution: Thats why we use export FLASK_APP=microblog.py
It is setting the FLASK_APP (an internal flask variable) value to microblog.py
It tells flask to use microblog.py as start-up file for the application when you run flask via flask run command.
If you decide not to do so, then when you run flask run, then there is no way for flask to know which file to run. Now you could run the application using python filename.py instead of flask run
So python microblog.py in your case.

Categories

Resources