Flask-Migrate command 'flask db init' can't find app file - python

Firstly, I'm following the Python Flask tutorial posted here: https://scotch.io/tutorials/build-a-crud-web-app-with-python-and-flask-part-one.
Everything was working smoothly up to the 'Migration' section where executing:
$ flask db init
... failed with the following error:
Usage: flask db init [OPTIONS]
Error: The file/path provided (run) does not appear to exist. Please verify the path is correct. If app is not on PYTHONPATH, ensure the extension is .py
I know the $FLASK_APP env variable is set because this command executes fine:
$ flask run
Can anyone suggest why this executes fine when running the app, but not when trying to create the migration repository?
The closest I can find elsewhere on the subject is here: Flask can't find app file, but pre-pending with python -m isn't working in either case for me here.

In my case I had to do
python3 -m flask db init
Without mentioning python3 -m, it shows
zsh: command not found: flask

The command flask run started the app successfully.
The command flask db init failed with the error reported in the question.
So I tried python run.py and this failed to start the app by reporting an unmet dependency in models.py which was in fact a typo in an import. Fixing the typo and rerunning python run.py was successful.
Then I tried flask run again, still fine. Then flask db init... finally success.
It appears the error reported that it could not find run.py is either misleading or masking the true root cause of why it could execute.

In my case my app name was different, and in the directory, I had two flask apps app.py and app_async.py
And I was also getting the same migrate key error, so this is how I solved it:
FLASK_APP=app_async.py flask db init
Here I mentioned the app name, and then ran the command.

This worked for me:
pip install flask-migrate --upgrade

I had same problem occuring,after sometime i noticed that the set FLASK_APP=my_app,but i had a function handling creaion and initializing app so i changed set FLASK_APP=my_app:crate_flask_app,finally it's working for me.
for example:In my_app/init.py
migrate=Migrate()
db=Sqlalchemy()
defcreate_flask_app():
app=Flask(__name__)
db.init_app(app)
migrate.init_app(app,db)
return app
solution for windows is while declaring FLASK_APP environmental variable if any function is part of creating app then the function should be given after the colon i,e:set FLASK_APP:create_flask_app

Related

Setting flask environment variables in a shell script

all
As flask-script document said they are no longer to maintain it,
thus I am trying to use flask cli (Command Line Interface) to activate my flask app.
When I run the following flask cli commands one by one at my terminal, they worked fine for me.
$ export PYTHONPATH=$PWD:flask_api/
$ export FLASK_APP=flask_api/app
$ export FLASK_RUN_PORT=8000
$ flask run
The problem is that it seems not that efficient every time I tried to start my flask app.
so I came up with writing them into a shell scripts (that said run_flask.sh)
the content in run_flask.sh is:
export PYTHONPATH=$PWD:flask_api/
export FLASK_APP=flask_api/app
export FLASK_RUN_PORT=8000
flask run
and I simply run source run_flask.sh
and the result showed and did not start to run flask:
"* Serving Flask app "flask_api/app
* 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]
".ror: Could not import "src.flask_api.app
I am not sure what's happening,
could any one tell me why flask could not import my flask app while I tried to run it with shell scripts? Great Thanks!
ps. I declare flask app instance in flask_api/base_api/init.py,
and app.py is in flask_api/ folder, app.py would import the app instance from base_api
(I used CentOS7 as the OS)

Problem with flask using Python 3.7.6 with vscode on mac

I have a weird problem with some code I want to run. The code itself should not be the problem since it is downloaded from a Udemy class and not modified:
# coding=utf-8
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/")
def hello():
items = ["Apfel", "Birne", "Banane"]
return render_template("start.html", name="Max Mustermann", items=items)
#app.route("/test")
def test():
name = request.args.get("name")
return render_template("test.html", name=name)
I found online that, to start the emulated webserver(?) I have to rund the following temrinal commands before I can see the output:
(base) Christophs-MBP:13-23 chris$ export FLASK_APP=run.py run flask
(base) Christophs-MBP:13-23 chris$ export FLASK_APP=run.py run flask
(base) Christophs-MBP:13-23 chris$ export FLASK_APP=run.py
(base) Christophs-MBP:13-23 chris$ run flask
bash: run: command not found
No reaction to my terminal commands
Basically there is no reaction to the command to start the server(?).It should reply with "Running on 127.0.0.1:5000" as soon as I've run the command once.
If I go to my browser, there is no page when I address http://127.0.0.1:5000. What am I doing wrong? I am pretty new to Python and an absolute rookie regarding the terminal. Not sure if I broke something there, since trying to install pyenv to manage my Python installs better as recommended by a friend does not work either (I cannot update the SDK headers as described on RealPython
What are the export statements?
On Mac, export key=value creates a new (or updates an existing one) environment variable - the tutorial most likely simply asked you to provide one where key is FLASK_APP and value is a path to your app.
To verify it's been saved correctly, you can list the variables by just typing export in the terminal and finding out what's inside each of the environment variables on your system (if you want to only view FLASK_APP you can type export | grep FLASK_APP).
Why do you need FLASK_APP?
When you call flask run in your terminal, you will see the following message:
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.
I presume your file is called run.py, therefore none of the conditions are met. You could rename run.py to app.py and simply type flask run in the terminal, but you can also type export FLASK_APP=<path-to-run.py>. It seems the tutorial author decided to do the latter. Keep in mind that if you rename your file to app.py you will need to run flask run within the directory that file lives in. You can change directory in the terminal using cd command.
Why do you get bash: run: command not found?
bash is a language running inside your terminal, and it only knows of a few commands - it is not aware of any run commands. It does however know about flask command once you have installed it on your machine. Within the command's output there is a part which includes a run command:
Commands:
routes Show the routes for the app.
run Run a development server.
shell Run a shell in the app context.
Therefore, what you want to do is type flask run instead of just run in your terminal.

Flask can't run in development mode, can't find flask module [duplicate]

This question already has an answer here:
Flask reloader crashes with "no module named Scripts\flask" on Windows
(1 answer)
Closed 3 years ago.
I'm on Windows, using git bash.
I'm able to run Flask if it's not in development mode. If I set FLASK_ENV to "development" to try to trigger debugging and other helpful things, then flask run fails.
The error message is pretty peculiar.
$ flask run
* Serving Flask app "Neuroethics_Behavioral_Task" (lazy loading)
* Environment: development
* Debug mode: on
* Restarting with stat
d:\miniconda3\python.exe: No module named D:\miniconda3\Scripts\flask
What's weird is that... in the directory D:\miniconda3\Scripts, there is a flask.exe or flask application file.
By typing "where flask", I get returned D:\miniconda3\Scripts\flask.exe. So this executable definitely exists in the location that they're trying to look for, but even then Flask can't seem to find it when I try doing flask run.
How do I approach this?
Edit: some more info. This seems to have to do with the fact that I had Flask previously installed in Anaconda, removed it from anaconda using conda uninstall flask, then I had it installed with pip.
where flask gives D:\miniconda3\Scripts\flask.exe
but pip show flask gives Location: d:\miniconda3\lib\site-packages. The location offered by pip however DOES NOT contain any flask.exe file whatsoever.
The flask run command is recommended, but there's currently an issue with Werkzeug on Windows. See Flask reloader crashes with "no module named Scripts\flask" on Windows for the workaround until the bug is fixed.
If you don't want to use that workaround, you can add an if __name__ == "__main__" block and call app.run(debug=True) directly, running it as python app.py. Again, this is not the recommended way to run Flask and there is another workaround to the bug.
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(debug=True)

'flask run' or 'python run' which to use?

Reading http://flask.pocoo.org/docs/1.0/quickstart/ describes using 'flask run' to start flask based app.
I've been using python run.py myconfig.conf as there does not appear to be an option to set config file 'myconfig.conf' as part of flask startup.
my run code :
if __name__ == '__main__':
app.config.from_pyfile(sys.argv[1]))
app.run(host='0.0.0.0', port=app.config["PORT"])
Can see myconfig.conf is registered with sys.argv[1]
Should I use flask mechanism instead of python for executing flask server ? If so how to pass myconfig.conf to main method ?
As using :
flask run myconfig.py
returns error :
Usage: flask run [OPTIONS]
Error: Got unexpected extra argument (myconfig.py)
You can use flasks custom commands (http://flask.pocoo.org/docs/1.0/cli/#custom-commands) which will help you to define your own flask command line options. There you can set app.config.from_pyfile(confige_file). Then run flask run to execute flask server.
#app.cli.command()
#click.argument('config_file')
def set_config(config_file):
app.config.from_pyfile(confige_file)
To run the application you can either use the flask command or python’s -m switch with Flask. Before you can do that you need to tell your terminal the application to work with by exporting the FLASK_APP environment variable:
$ export FLASK_APP=hello.py
$ flask run
Running on http://127.0.0.1:5000/
from the above link itself. you have to set FLASK_APP environmet variable to your script

Create Django Superuser on AWS Elastic Beanstalk

I have a custom user class called MyUser. It works fine locally with registrations, logins and so on. I'm trying to deploy my application to AWS Elastic Beanstalk and I'm running into some problems with creating my superuser.
I tried making a script file and run it as the official AWS guide suggests. Didnt work well so I decided to try a secondary method suggested here and create a custom manage.py command to create my user.
When I deploy I get the following errors in the log.
[Instance: i-8a0a6d6e Module: AWSEBAutoScalingGroup ConfigSet: null] Command failed on instance. Return code: 1 Output: [CMD-AppDeploy/AppDeployStage0/EbExtensionPostBuild] command failed with error code 1: Error occurred during build: Command 02_createsu failed.
[2015-03-10T08:05:20.464Z] INFO [17937] : Command processor returning results:
{"status":"FAILURE","api_version":"1.0","truncated":"false","results":[{"status":"FAILURE","msg":"[CMD-AppDeploy/AppDeployStage0/EbExtensionPostBuild] command failed with error code 1: Error occurred during build: Command 02_createsu failed","returncode":1,"events":[]}]}
[2015-03-10T08:05:20.463Z] ERROR [17937] : Command execution failed: [CMD-AppDeploy/AppDeployStage0/EbExtensionPostBuild] command failed with error code 1: Error occurred during build: Command 02_createsu failed (ElasticBeanstalk::ActivityFatalError)
at /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.1.0/gems/beanstalk-core-1.1/lib/elasticbeanstalk/activity.rb:189:in `rescue in exec'
...
caused by: command failed with error code 1: Error occurred during build: Command 02_createsu failed (Executor::NonZeroExitStatus)
The code looks like the following:
This is my mysite.config file in .ebextensions/
01_syncdb and 03_collectstatic works fine.
container_commands:
01_syncdb:
command: "django-admin.py migrate --noinput"
leader_only: true
02_createsu:
command: "manage.py createsu"
leader_only: true
03_collectstatic:
command: "django-admin.py collectstatic --noinput"
option_settings:
- namespace: aws:elasticbeanstalk:container:python
option_name: WSGIPath
value: treerating/wsgi.py
- option_name: DJANGO_SETTINGS_MODULE
value: treerating.settings
This is my /profiles/management/commands/createsu.py file:
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from profiles.models import MyUser
class Command(BaseCommand):
def handle(self, *args, **options):
if MyUser.objects.count() == 0:
MyUser.objects.create_superuser("admin", "treerating", "password")
And I have __init__.py files in both /management/ and /commands/ folders.
I tried this command locally from command line and it works fine and creates the user without errors. So there shouldnt be any issue with the command itself or the MyUser.objects.create_superuser().
EDIT: I tried changing my def handle(): function to only set a variable to True and I still get the same errors. So it seems like the problem is not related to the create_superuser function or the handle, but more something with using manage.py.
Any ideas?
EDIT 2:
I tried executing the command by SSH and failed. I then followed the instructions in this post and set the Python Path's manually with:
source /opt/python/run/venv/bin/activate
and
source /opt/python/current/env
I was then able to successfully create my user.
The official AWS Django Deployment guide does not mention anything about this. But I guess you are suppose to set your Python Path's in the .config file somehow. I'm not sure exactly how to do this so if someone still want to answer that, I will test it and accept it as answer if that will solve the deployment errors.
Double-check the link to your secondary method. You can set the python path in the option settings (.ebextensions/02_python.config) that you've created:
option_settings:
"aws:elasticbeanstalk:application:environment":
DJANGO_SETTINGS_MODULE: "iotd.settings"
"PYTHONPATH": "/opt/python/current/app/iotd:$PYTHONPATH"
"ALLOWED_HOSTS": ".elasticbeanstalk.com"
However, I've done this and am still experiencing the issue you've described, so you'll have to see if it fixes it.
EDIT: It turns out my issue was a file structure issue. I had the management directory in the project directory, when it should have been placed one level deeper in the directory of one of my apps.
This placed it one level deeper beneath my manage.py and settings.py than is shown in the example, but it is working fine now.
I know this could be late but I just wanted to share that I solved this issue by adding the file /profiles/management/commands/createsu.py into the app folder you are using.
In my case was:
easy/easyapp/management/commands/createsu.py
where easy is my project and easyapp my app.
Another alternative that worked for me is to just go directly into the config.yml file and change the wsgi path there. You can get access with the eb config command and just go down 50 lines or so, make your changes, escape and save. This is only an environment-specific solution though.

Categories