Pip installed dependencies not available to application file - python

I'm having problems getting dependencies installed on Heroku. I have a Python app that I want to deploy but every time I try and load the site I get ImportError's for both flask and sqlalchemy. I get these same errors if I run: heroku run python and try and import the modules interactively. I'm very puzzled and can't seem to solve this issue I was hoping someone else would know a solution. The details of the relevant files are down below.
Profile:
web: python app.py
requirements.txt:
Flask==0.9
Jinja2==2.6
SQLAlchemy==0.7.9
Werkzeug==0.8.3
app.py:
import os, flask, sqlalchemy
from gateway import server
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
server.app.run(host='0.0.0.0', port=port)
EDIT: I ended up restarting my application by following the Heroku instructions step-by-step and then copying over all my old code. This seemed to fix the problem for me so my problems seem to be a weird edge case.

I think your error may be in the "from gateway import server". It's not clear to me what that line's doing, and that code doesn't work when I try to run it locally on my machine.
Here's similar code, but in a format that's more familiar to me - I've deployed this to Heroku successfully in the past:
import os
from flask import Flask
from flask import render_template
app = Flask (__name__)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)

Can you run this code locally?
Check the Heroku Flash tutorial
https://devcenter.heroku.com/articles/python

Related

Error launching Flask app with error "Failed to find Flask application"

I'm new to Flask. To launch the flask app, I did python -m flask run but I repeatedly get the error:
Failed to find Flask application or factory in module "app". Use "FLASK_APP=app:name to specify one.
I am using a virtualenv on a Windows 10 machine
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return "Hello, World!"
if __name__ == '__main__':
app.run(debug=True)
I expected a web server to start and to be able to navigate to localhost http://127.0.0.1:5000/ where I could view Hello, World! on my browser, but that never happened.
Instead of just "flask" use FLASK_APP=theflaskapp.py, like what Marco suggested:
env FLASK_APP=theflaskapp.py python -m flask run
This should fix it, if not, make sure you are executing the command to run the script in the same directory as it. You should also check if the problem is in flask or not by running "python theflaskapp.py" (In the same directory as the flask app still) and see if it works at all.
Reproducing the problem, and fixing it
Hello, I have reproduced the problem
This is the error code:
Error: Failed to find Flask application or factory in module
"src.app". Use "FLASK_APP=src.app:name to specify one.
Steps of reproducing the error:
Create a file called app.py
inside app.py put this code:
from flask import Flask
def create_app():
app = Flask("abc")
#app.route('/')
def hello_world():
return 'Hello, World!'
Or let the file be empty, like this:
# This is an empty file
# There is no flask application here
Inside CLI run these commands:
export FLASK_APP=app.py
flask run
watch the error appear on the screen
Solution 1 :
make the function return the app
Clearly create a variable called app and make it equal to the return value of the function, like this:
from flask import Flask
def create_app():
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello, World!'
return app
app = create_app()
Solution 2: Get the app outside of the function:
from flask import Flask
app = Flask("abc")
#app.route('/')
def hello_world():
return 'Hello, World!'
solution for flask 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.
on windows when you tried set FLASKAPP=appname.py if your using PowerShell and if get the above error try this 👇👇
$env:FLASK_APP = "filename"
$env:FLASK_ENV = "development"
Flask run
try it if your having trouble launching the flask app.
You need to specify what file you want to work with. Try this.
For Windows:
set FLASK_APP=app.py
python -m flask run
For Mac OS and Linux:
export FLASK_APP=app.py
python -m flask run
I had a similar problem. It seems to work fine from the command prompt with python app.py. However, it would fail to launch with VS Code Debug.
The trick was to add:
server = app.server
before calling the app.run_server() portion
super simple in my case, and almost stupid...I had forgotten to save the file (CTRL+S), and I got exactly the same error. Once I saved the file, it worked directly!
Instead of providing a super straightforward "try this" suggestion, I'd recommend going straight to the flask source code to where this exception gets thrown, and reverse engineer from there. https://github.com/pallets/flask/blob/main/src/flask/cli.py#L78-L82
You can open this in your editor by going to the site-packages/flask/cli.py file and setting breakpoints around where this error gets thrown, and poke around from there.
Another working option is executing this command instead of flask run :
flask run --host=0.0.0.0
I had the same issue and I tried all the mentioned answers here but couldn't work finally this did the trick.
I'm getting the same error. The problem is you have to set the environment variable FLASK_APP in current project.
However, I have easiest way to solve this problem. Instead of using flask run command you can use python app.py.
"app.py" is your application entry point.
The simplest way to run your app without getting any issue is to create the app then run python app.py
from flask import (
Flask,
jsonify
)
# Function that create the app
def create_app(test_config=None ):
# create and configure the app
app = Flask(__name__)
# Simple route
#app.route('/')
def hello_world():
return jsonify({
"status": "success",
"message": "Hello World!"
})
return app # do not foget to return the app
APP = create_app()
if __name__ == '__main__':
# APP.run(host='0.0.0.0', port=5000, debug=True)
APP.run(debug=True)
On venv and my Windows10 only this syntax works:
set FLASK_APP=name_of_file:name_of_var_app
If file is application.py and 'app = Flask(__name__)',
run:
set FLASK_APP=application:app
You should change the name of the file, I have the same problem. So, I changed the name of the app file and It works for me. At first my app file name is 'socket.py' and I change it to 'app.py'.
My problem was that the python file didn't have execute permissions:
chmod a+x app.py
Similar issue! I was running the code in vs code. Installed python extension and after selecting a different python interpreter( in my case 3.10.5 64 bit), got a play button on the top right corner of my vs code interface.
That solved the issue for me.
In my case was a very simple issue, the activate.bat file was setup as Macintosh (CR) I changed to Windows (CR LF) and that worked for me.
Explanation: In windows OS, for the instruction to take effect, for example [set FLASK_ENV = development] a strong carriage return is needed, such as the (CR LF), that is what I could verify in my case. You can try to run the SET instruction in the console, cmd, and check if the FLASK settings are reflected. I understand that it is more a problem of the configuration of the environment and not of the application itself.
Try removing the spaces from this line of code, this is what fixed it for me when I had this error:
app=Flask(__name__)

Python import from a virtual environment when run in apache

I am new in python. I am trying to deploy python code on apache server for i.e i have created flask api. So for apache i have installed XAMPP and changed my httpd.conf to execute python on apache. It works well!! Here is code example which is working
Code working:
#!C:\Users\test.lab\AppData\Local\Continuum\anaconda3\envs\myproject\python.exe
# enable debugging
print("Content-type: text/html\n")
print ("Hello Python Web Browser!! This is cool!!")
But when I tried to import that through 500 Error, Here is the code
#!C:\Users\test.lab\AppData\Local\Continuum\anaconda3\envs\myproject\python.exe
# enable debugging
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'testing'
if __name__ == '__main__':
app.run(debug = True)
flask is installed on my environment (myproject). When I run through command like python test.py and it works.
Flask has it's own development web server.
Using python myfile.py which will work properly as a webserver (no need for apache on development).
If you still want do deploy on Apache, Flask have some info on how to do so, docs: http://flask.pocoo.org/docs/1.0/deploying/mod_wsgi/
Special attention to this: http://flask.pocoo.org/docs/1.0/deploying/mod_wsgi/#creating-a-wsgi-file

Flask at first run: Do not use the development server in a production environment

I installed the Flask plugin in PyCharm Community Edition and I just have this simple code in my flask app:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return '<h1>Hello!</h1>'
if __name__ == "__main__":
app.run(debug=True)
And I get this message:
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead
* Restarting with stat
* Debugger is active!
* Debugger PIN: 123-456-789
* Running on http://127.0.0.1:5000/
Why am I getting this error when I run Flask?
A previous version of the message read "Do not use the development server in a production environment."
For deploying an application to production, one option is to use Waitress, a production WSGI server.
Here is an example of using waitress in the code.
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "<h1>Hello!</h1>"
if __name__ == "__main__":
from waitress import serve
serve(app, host="0.0.0.0", port=8080)
Running the application:
$ python hello.py
Waitress also provides a command line utility waitress-serve. To use that, you can modify the code to the following:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "<h1>Hello!</h1>"
def create_app():
return app
Then we can use waitress-serve as the following:
waitress-serve --port=8080 --call hello:create_app
And BTW, 8080 is the default port.
To validate the deployment, open a separate window:
% curl localhost:8080
<h1>Hello!</h1>%
Or directly in your browser http://localhost:8080/.
Other alternatives to deploy your app include Gunicorn and uWSGI. For more details, please refer to the flask deploy doc.
As of Flask 2.2, the development server always shows this warning, it is not possible to disable it. The development server is not intended for use in production. It is not designed to be particularly efficient, stable, or secure. Use a production WSGI server instead. See the deployment docs from Flask for more information.
That warning is just a warning though, it's not an error preventing your app from running. If your app isn't working, there's something else wrong with your code.
That warning applies to the development server, not Flask itself. The Flask framework is appropriate for any type of application and deployment.
To avoid these messsages, inside the CLI (Command Line Interface), run these commands.
export FLASK_APP=app.py
export FLASK_ENV=development
export FLASK_DEBUG=0
flask run
If for some people (like me earlier) the above answers don't work, I think the following answer would work (for Mac users I think)
Enter the following commands to do flask run
$ export FLASK_APP=hello.py
$ export FLASK_ENV=development
$ flask run
Alternatively you can do the following (I haven't tried this but one resource online talks about it)
$ export FLASK_APP=hello.py
$ python -m flask run
source: For more
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
This worked for me on windows:
$env:FLASK_APP="flask_project.py"
$env:FLASK_ENV="development"
flask run
flask_project.py is on the same path as my virtual environment.

running python+flask on heroku, without gunicorn [duplicate]

I'm trying to develop my first "large" app with Flask on Heroku and I'm attempting to combine the basic tutorial here: https://devcenter.heroku.com/articles/python with the instructions here: http://flask.pocoo.org/docs/patterns/packages/#larger-applications. It works locally with "foreman start" but when I push to Heroku I get an error that the wrong port is in use:
Starting process with command python run.py
2012-12-04T23:45:18+00:00 app[web.1]: * Running on
http://127.0.0.1:5000/ 2012-12-04T23:45:18+00:00 app[web.1]: *
Restarting with reloader 2012-12-04T23:45:23+00:00 heroku[web.1]:
Error R11 (Bad bind) -> Process bound to port 5000, should be 33507
(see environment variable PORT)
I'm new to all this, but it looks like it's trying to run "locally" on Heroku. I've tried all sorts of combinations, but can't get it to work. My very simple code right now is (the app is called "pml"):
directory: /pml
Procfile:
web: python run.py
run.py:
from pml import app
app.run(debug=True)
directory: /pml/pml/
__init__.py
from flask import Flask
app = Flask(__name__)
import pml.views
view.py
from pml import app
#app.route('/')
def index():
return 'Hello World!'
I haven't used Heroku, but to me, it looks like they have a reserved port for Flask, specifically 33507. It looks like it will try to use an environment variable, which I am not sure how to set in Heroku. The good news is you can tell Flask which port to use.
try this:
app.run(debug=True, port=33507)
and it looks like adding the PORT to the env in heroku is done like this:
heroku config:add PORT=33507
You should only have to do one of these. I would try the first as it, to me, is the straight forward way to fix the issue.
EDIT
After reading the article from your post, I see where the issue comes in.
port = int(os.environ.get('PORT', 5000))
That line says, get the value of PORT from the environment if it is set, otherwise use 5000. I am not sure why they wouldn't allow it to run from 5000 if that's what is in their docs, but I would try this change:
port = int(os.environ.get('PORT', 33507))

Deploying Flask app to Heroku

I'm trying to develop my first "large" app with Flask on Heroku and I'm attempting to combine the basic tutorial here: https://devcenter.heroku.com/articles/python with the instructions here: http://flask.pocoo.org/docs/patterns/packages/#larger-applications. It works locally with "foreman start" but when I push to Heroku I get an error that the wrong port is in use:
Starting process with command python run.py
2012-12-04T23:45:18+00:00 app[web.1]: * Running on
http://127.0.0.1:5000/ 2012-12-04T23:45:18+00:00 app[web.1]: *
Restarting with reloader 2012-12-04T23:45:23+00:00 heroku[web.1]:
Error R11 (Bad bind) -> Process bound to port 5000, should be 33507
(see environment variable PORT)
I'm new to all this, but it looks like it's trying to run "locally" on Heroku. I've tried all sorts of combinations, but can't get it to work. My very simple code right now is (the app is called "pml"):
directory: /pml
Procfile:
web: python run.py
run.py:
from pml import app
app.run(debug=True)
directory: /pml/pml/
__init__.py
from flask import Flask
app = Flask(__name__)
import pml.views
view.py
from pml import app
#app.route('/')
def index():
return 'Hello World!'
I haven't used Heroku, but to me, it looks like they have a reserved port for Flask, specifically 33507. It looks like it will try to use an environment variable, which I am not sure how to set in Heroku. The good news is you can tell Flask which port to use.
try this:
app.run(debug=True, port=33507)
and it looks like adding the PORT to the env in heroku is done like this:
heroku config:add PORT=33507
You should only have to do one of these. I would try the first as it, to me, is the straight forward way to fix the issue.
EDIT
After reading the article from your post, I see where the issue comes in.
port = int(os.environ.get('PORT', 5000))
That line says, get the value of PORT from the environment if it is set, otherwise use 5000. I am not sure why they wouldn't allow it to run from 5000 if that's what is in their docs, but I would try this change:
port = int(os.environ.get('PORT', 33507))

Categories

Resources