The Flask official website says that we can run a Flask application by
$ export FLASK_APP=hello.py
$ flask run
The second command doesn't work for me.
$ flask run
Command 'flask' not found, but can be installed with:
sudo apt install python3-flask
Instead this works
python3 -m flask run
How can I make the second command works? If I run sudo apt install python3-flask, will I get two installations of flask?
Can the two commands be combined into one command without using environment variable?
Bear with me as I will try to explain the different pieces and how they all interconnect. export FLASK_APP=hello.py is setting an operating system environment variable called FLASK_APP and is simply pointing to the entry file to start your flask application. This is no different than setting any other environment variable on your operating system. Now the flask team has provided everyone with a command called flask run which can be used to start up your flask application and this command will use the value set within your FLASK_APP environment variable when it attempts to start your flask server. So the reason why your python3 -m flask run command works is because you're telling your operating system's install of python to run the flask run command as a script, which is how this command is intended to be invoked.
For reference:
-m mod : run library module as a script (terminates option list)
Additionally, python attempts to resolve modules from it's sys.path environment variable and it looks in the following order of directories to resolve the requested module:
The current directory where the script has been invoked. This is why you can always import modules contained in the same directory as one another.
The value of your PYTHONPATH environment variable
The standard library directory on your path
Lastly, the site packages directory, i.e. your third party packages like flask
Now the reason your flask run command didn't initially work is because python couldn't find flask within any of the four locations listed above. However, once you gave the -m python knew to look in your site-packages directory for flask and was able to find said module.
For reference you can see where python is looking to resolve modules by printing out the sys.path variable to the console:
import sys
print(sys.path)
Ok so that answers the first part of your first question, now as for the second part of your first question:
"If I run sudo apt install python3-flask, will I get two installations of flask?"
Yes, this would install flask globally on your system and I would highly advise against this as you can mess up your system pretty badly if you're not careful. So how do I avoid messing with my system level python configurations?
Virtualenv to the rescue, Virtual environments allow you to have a sandboxed area to play around with libraries. With the worst case scenario being you blow them away and start fresh if you screwed something up, without affecting your Operating System's install of python. You should have a one to one relationship between each python project and virtual environment. If you use virtualenv I highly suggest looking into Virtualenvwrapper which wraps virtualenv with easier to remember commands. Although I think all the cool kids are using pipenv now so you may want to look into that as well, I will leave that decision up to you. What's nice is once you've activated your virtual environment and are developing you can just use flask run since your virtual environment will be on your python path.
As for your second question: "Can the two commands be combined into one command without using environment variable?"
No you would still need to set the FLASK_APP environment variable to use flask run since it looks for the value of that environment variable to start your flask server. Perhaps you could try something like:
FLASK_APP=hello.py flask run
on the command line and see if that helps you, but you're still setting the FLASK_APP environment variable. Alternatively, you could just start the entry file for your flask server directly, with a:
python hello.py
I know that was a lot, but hopefully that helps clarify things for you!
Related
Basically I am writing a script to reset a django webapp completely. In this script, I want to reset the database, and there is a command to do it from django extensions. Unfortunately, I haven't been able to run it programatically. It works fine when I run it via command line, but it just won't execute when I try programatically.
I have tried using os.system and subprocess.
I have also tried using management.call_command('reset_db'), but it keeps saying that there isn't a command called reset_db. I have checked to make sure the django_extensions is in my installed apps, so I have no idea why that isn't working.
Does anyone know how I could fix this? Thank you!
Also I am using python3, the most recent version of django I believe, and it is a MYSQL server that I am trying to delete.
I can't know without seeing your way of invocation directly, but my guess is the script's not running in the virtualenv. Here are some debug notes:
./manage.py --help | grep reset_db: Does this output anything?
./manage.py shell_plus
Then try:
from django.core.management import call_command
call_command('reset_db', '--help')
Anything then?
Also within ./manage.py shell_plus, try import django_extensions
Outside of the shell, try this: pip show django, pip django-extensions.
If it doesn't show those (e.g. WARNING: Package(s) not found: django-extension) and you think they're already installed, try this:
which python, which pip. Are you using venv, virtualenv, virtualenvwrapper, pipenvorpoetry`?
Try env | grep VIRT, do you see a VIRTUAL_ENV? If not you may need to make one.
When you run the script, you need to have your environmental variables set so you hook in to your site packages. In poetry we can do poetry run ./manage.py ourscript or poetry run ./ourscript.py without needing to be sourced. But we can also easily drop into virtualenv via poetry shell.
If you created an environment like virtualenv -ppython3.8 .venv, you can either do:
source .venv/bin/activate, ./myscript.py, rr you can try .venv/bin/python ./myscript.py
I want to debug an application using Python and Flask in VSCode. I have installed Flask and the app runs perfectly fine through cmd. But, when I try to debug it through VSCode, it gives the following error:
cd 'c:\Users\Aditi\CleanHandymanApp';
${env:FLASK_APP}='NewApp'; ${env:PYTHONIOENCODING}='UTF-8';
${env:PYTHONUNBUFFERED}='1'; & 'C:\Users\Aditi\envs\CleanHandymanApp\Scripts\python.exe'
'c:\Users\Aditi\.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd_launcher.py' '--client' '--host'
'localhost' '--port' '63143' '-m' 'flask' 'run' '--no-debugger' '--no-reload'
No module named flask
Can you please help me.
This error message can occur if you installed the python3 version of flask but Visual Studio Code tries to run your project with python2.
Make sure to select the correct version of python in the editor. This can be done by running the command Python: Select Interpreter from the Command Palette (Ctrl+Shift+P).
Activate your virtualenv and run
pip3 install -r requirements.txt
to reinstall all packages inside the venv.
For some reason VS Code thought I was missing all my packages the first time I debugged even though the app was running fine locally.
Sometimes you can get this error if you loaded Flask into a folder which has sub-files. For instance, if you loaded flask into the parent folder with the virtual shell instance but you're running your code in the child file (let's say parent is called crypto_files and inside that is a python source code file called blockchain.py ), then in order to get flask to run properly you'd have to run the file like this:
python crypto_files/blockchain.py
This allows your machine to see Flask running inside crypto_files but also run blockchain.py .
OR, it's possibly you could just reload Flask into the sub(child)file... blockchain.py and then you'd run it from within the subfile.
This complication is mainly due to modern "virtual instances" and shells which are basically like creating a virtual computer-machine inside your ACTUAL hard machine. Flask does this to avoid running everywhere, and since Flask is modular it allows each of your projects to run different modular configurations of Flask to suit each project precisely. The alternative would be awful: you'd have to load the fattest version of Flask with dozens of add-ons for each project, and so all your git and all your projects would have tons of extra code. Flask is built to be very small at the core to avoid this problem (too verbose!).
If you have installed flask in virtual environment, you should have activated it first.
source /path to env dir/bin/activate #in linux
workon 'name of env' #windows
Another option is add sys.path.append('d:/programas/anaconda3/lib/site-packages') in c:\Users\Aditi.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd_launcher.py
Being that "d:/programas/anaconda3/lib/site-packages" should be modified by your local python packages.
Use this command in the terminal instead of selecting run code:
python3 "insert your file name here without the quotes"
e.g.: python3 example.py
I had a variant of the issue mentioned by #confusius. I had installed both Python 3.9 and Python 3.10. I had added Flask to Python 3.10. I had been using one vscode workspace which had selected Python 3.10. I started another project in a different vscode workspace and it had selected Python 3.9 by default, which I didn't notice because I thought it would select the same Python I had already selected in the other workspace.
I need to run a script inside a Popen inside a packaged project (with pyinstaller). The command NEEDS to run in python3 and I (obviously) need it to be portable, which means that I can't rely on the config (python/python3 notation) used on the machine I've used to generate the package neither the one where I am using it (I can't also guarantee that there will be any python in the deployment machine...).
I have computers where python is already the correct version, and others where the correct one is python3. I tried to insert #!/usr/bin python3 in the beginning of the file and then run as python but it didn't work.
subprocess.Popen(['python', 'internal.py', arg1, arg2], universal_newlines=True)
In the non-frozen environment I am able to run using sys.executable instead of python. I tried to "pyinstall" the internal.py then, "pyinstall" the rest copying the internal folder to the new folder and then call:
subprocess.Popen(['./internal/internal', arg1, arg2], universal_newlines=True)
But this doesn't work... In the console (moving to the bigger project folder) it does, but when running the package, it doesn't...
Any idea?
Ps. I can't just import the script as a class or whatever. I can't modify system environment vars (except the ones inside the pyinstaller thing...)
I saw something about the PyInstaller.compat that has a exec_python and a __wrap_python, but I couldn't use it I get errors when trying to run the package due to pkg_resources.DistributionNotFound: The 'PyInstaller' distribution was not found and is required by the application, I tried to create a hook, to add as hidden import... None worked (but the hook part maybe I got it wrong...)
I'm trying to deploy a flask application to an ec2 instance using (1) nginx (2) gunicorn, (3) git, and (4) supervisor. I've set up nginx, git, gunicorn, but I've having trouble writing the supervisor script.
I'm unable to get supervisor to launch gunicorn within the context of the virtualenv.
When I run gunicorn run:app outside of the virtualenv it returns
ImportError: No module named flask
When I run the same command within the virtualenv it works just fine.
When I run the same command outside of the virtualenv but specify the gunicorn in the virtual env (i.e /var/www/sitename/env/bin/gunicorn run:app) it works just fine again.
That's a problem that I couldn't figure out, but I figured if I could just have supervisor run gunicorn inside the virtualenv it wouldn't be a problem, but I'm not able to do that either.
I've tried adding two programs in the supervisor script, one to launch the virtual environment and the other for gunicorn, added the two commands together using quotes which one similar SO answer suggested, using && to combine activating the virtualenv and launching gunicorn, declaring an environment=PATH= variable, and a number of other options; I just can't get it to work.
I have no idea what I'm doing wrong or what else to try; does anyone know what I can do at this point?
I'm running python3 - I read that supervisor is limited to v2 but someone else mentioned in an answer that it's just a task manager and it shouldn't matter.
You were on the right track, but it's simpler than you were making it. To run a Flask app named run with entry point app via gunicorn under supervisor with the path you gave:
/etc/supervisor/conf.d/run.conf
[program:run]
command = /var/www/sitename/env/bin/gunicorn run:app -b localhost:8000
directory = /var/www/sitename
user = siteuser
You can provide the environment argument to set stuff like production mode or whatever, but this is all you need to have the virtual environment version of gunicorn, running python 3 if it's a python 3 venv, run your flask app in the same virtual environment.
I have an account to a computing cluster that uses Scientific Linux. Of course I only have user access. I'm working with python and I need to run python scripts, so I need to import some python modules. Since I don't have root access, I installed a local python copy on my $HOME with all the required modules. When I run the scripts on my account (hosting node), they run correctly. But in order to submit jobs to the computing queues (to process on much faster machines), I need to submit a bash script that has a line that executes the scripts. The computing cluster uses SunGrid Engine. However when I submit the bash script, I get an error that the modules I installed can't be found! I can't figure out what is wrong. I hope if you can help.
You could simply call your python program from the bash script with something like: PYTHONPATH=$HOME/lib/python /path/to/my/python my_python_script
I don't know how SunGrid works, but if it uses a different user than yours, you'll need global read access to your $HOME. Or at least to the python libraries.
First, whether or not this solution works for you depends heavily on how the cluster is set up. That said, the general solution to your problem is below. If the compute cluster has access to the same files as you do in your home directory, I see no reason why this would not work.
You need to be using a virtualenv. Install your software inside that virtualenv along with any additional python packages you need. Then in your batch bash script, provide the full path to the python interpreter within that virtualenv.
Note: to install python packages inside your virtualenv, you need to use the pip instance that is in your virtualenv, not the system pip.
Example:
$ virtualenv foo
$ cd foo
$ ./bin/pip install numpy
Then in your bash script:
/path/to/foo/bin/python /path/to/your/script.py
Have you tried to add these in your python code:
import sys
sys.path.append("..")
from myOtherPackage import myPythonFile
This works very well for my code when I run it on Cluster and I wanted to call my "myPythonFile" from other package "myOtherPackage"