Python: Flask loading venv with sh - python

I'm trying to launch a server and load a venv with modules installed. So basically I did a start.sh file which is:
export FLASK_APP=wsgi.py
export SECRET_KEY=test
export FLASK_DEBUG=1
export APP_CONFIG_FILE=config.py
export FLASK_RUN_PORT=80
which python3
flask run
which python3 - usr/bin/python3
And my config.py file which is:
"""Set Flask configuration vars from .env file."""
# General Config
SECRET_KEY = os.environ.get('SECRET_KEY')
FLASK_APP = os.environ.get('FLASK_APP')
FLASK_ENV = os.environ.get('FLASK_ENV')
FLASK_DEBUG = os.environ.get('FLASK_DEBUG')
PERMANENT_SESSION_LIFETIME = timedelta(minutes=30)
SQLALCHEMY_DATABASE_URI = os.environ.get('SQLALCHEMY_DATABASE_URI')
SQLALCHEMY_TRACK_MODIFICATIONS = os.environ.get('SQLALCHEMY_TRACK_MODIFICATIONS')
So basically I launch my server with sudo sh start.sh, but when I'm trying to connect to the server it says that modules are not found, so that means it is using the other interpreter. When I do sudo pip3 install hello-world, then I pass one module not found error. btw I have a .env folder with all the modules installed in my application.

You need to activate VENV
#!/bin/bash
cd $(dirname $0)
. venv/bin/activate
export FLASK_APP=wsgi.py
export SECRET_KEY=test
export FLASK_DEBUG=1
export APP_CONFIG_FILE=config.py
export FLASK_RUN_PORT=80
which python3
flask run
^ Try this, you can run it from any directory.

Related

Could not locate a Flask application when creating a Docker Image

I hope someone can help me with this. The following error code comes up when I try and run docker run todolist-docker.
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
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.
My folder directory is here:
Folder name: todoflaskappfinal
__pycache__
static
templates
venv
App.py
Dockerfile
requirements.txt
todo.db
ToDoList.db
within the todoflaskappfinal folder, I have a Dockerfile file:
# syntax=docker/dockerfile:1
FROM python:3.7.8
WORKDIR /tododocker
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY . .
CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]
And within App.py, I've set up everything (I assume) correctly, obviously with more code between this.
#Website Configuration
app = Flask(__name__)
if __name__ == "__main__":
app.run(debug=True, port=5000, host='0.0.0.0')
I've set FLASK_APP as App.py, made the virtual environment with venv, etc. When I type in flask run in the terminal it loads the website up correctly and displays it on 127.0.0.01. However, when I try and use the docker build --tag todolist-docker command and then docker run todolist-docker, the error message appears above. Can anyone see what I'm doing wrong?
Is FLASK_APP defined in the docker container? There's no ENV statement in the Dockerfile, and you didn't mention using docker's -e or --env command option. Your container won't inherit your environment variables from the hosting environment.
# syntax=docker/dockerfile:1
FROM python:3.7.8
WORKDIR /tododocker
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY . .
# Add this:
ENV FLASK_APP=App.py
CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]

Crontab Launches Python Script but SystemD Does Not?

I can log into my AWS EC2 server via ssh and type:
cd /opt/myWebApp
sudo python3 /opt/myWebApp/manage.py myCronJob
...and it runs.
I can also launch the same script via crontab:
0 */6 * * * sudo python3 /opt/myWebApp/manage.py myCronJob --settings=server.settings.production
But when I try to run it in SystemD, with .service file:
ExecStart='/usr/bin/python3.7' /opt/myWebApp/manage.py myCronJob --settings=server.settings.production
...I get:
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
$PYTHONPATH and $VIRTUAL_ENV are empty. /opt/myWebApp/server_venv is empty as well. There's a python at /usr/bin/python3.7, but I'm referencing that in the SystemD .service file as noted above, and it's throwing that error.
What am I missing?
Solved it!
ExecStart='/etc/alternatives/python3' ./manage.py myCronJob --settings=server.settings.production
WorkingDirectory=/opt/myWebapp
User=myUser
The user ('myUser' in the above code) has access to Django.

python3: can't find '__main__' module in 'app.py'

I'm trying to create a Docker container to be able to create a GUI with Flask for the utilisation of a tensorflow model.
The thing is that I would like to be able to modify my python files in real time and not have to rebuild my container everytime.
So for now I've created 3 files :
requirement.txt
Flask
tensorflow
keras
Dockerfile
# Use an official Python runtime as a parent image
FROM python:3.5.6-slim
# Set the working directory to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
ADD . /app
# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt
# Make port 80 available to the world outside this container
EXPOSE 80
# Define environment variable
ENV NAME World
# Run app.py when the container launches
CMD ["python3", "app.py"]
app.py
from flask import Flask
import os
import socket
app = Flask(__name__)
#app.route("/")
def test():
html = "<h3>Hello {name}!</h3>" \
"<b>Hostname:</b> {hostname}<br/>"
return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname())
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
So after all this I build my container with this command
docker build -t modelgui .
End then I use this command to run my container and make a link between the app file I want to modify on the host and the one in the container
docker run -p 4000:80 -v /home/Documents/modelGUI:/app modelgui
But I get this error and I really don't know why
/usr/local/bin/python3: can't find '__main__' module in 'app.py'
My problem might be dumb to resolve but I'm really stuck here.
Check that /home/Documents/modelGUI in your bind volume mount is the path to where your code files reside and that app.py in that path is not created as a directory rather than a python file with the code you intend to run.
If app.py in /home/Documents/modelGUI is a dir, then the cause of this problem is that are not calling your script app.py at all, you are just giving the Python interpreter a nonexistent script name, which in case a similarly named directory (case-insensitive actually) exists it tries to execute it.
I've tried to replicate:
$ ls -lFs
Dockerfile
app.py/
requirements.txt
Then called the Python interpreter with app.py:
$ python3 app.py
/usr/local/bin/python3: can't find '__main__' module in 'app.py'
Running this locally, it looks like mounting your volume is overwriting your directory:
No volume
docker run -it test_image bash
root#c3870b9845c3:/app# ls
Dockerfile app.py requirements.txt
root#c3870b9845c3:/app# python app.py
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://0.0.0.0:80/ (Press CTRL+C to quit)
With volume
docker run -it -v ~/Barings_VSTS/modelGUI:/app test_image bash
root#f6349f899079:/app# ls
somefile.txt
root#f6349f899079:/app#
That could be part of the issue. If you want to mount a filesystem in, I would mount it into a different directory. The default volume behavior is such that whatever you copied into app will be overwritten by the contents of modelGUI

How to run Flask app as a package in PyCharm

I was following this documentation on directory management for Flask projects. Now, I'm trying to run my flask application from PyCharm. I have added the below mentioned Environment Variables in Edit Configurations...:
FLASK_DEBUG=true
FLASK_APP=<absolute-path-to-root-directory-of-application>
I add the Script as flask run
The output running this configuration is this:
../red-flask/venv/bin/python "flask run"
../red-flask/venv/bin/python: can't open file 'flask run': [Errno 2] No such file or directory
Process finished with exit code 2
My project directory looks like:
/flask_app
setup.py
/flask_app
__init__.py
views.py
/static
style.css
/templates
layout.html
index.html
login.html
...
I am unable to figure out how to make this work, any help is appreciated.
This is documented in the development build of the docs.
You need to point to the location of the flask command.
Script: /path/to/env/bin/flask
Script parameters: run
Until 1.0 comes out, you need to point FLASK_APP at __init__.py if you don't install your package in your env.
Environment variables: FLASK_APP /path/to/flask_app/__init__.py
Preferably, install the package in the env and point to it using the import name.
From the terminal, in the virtualenv: pip install -e .
Environment variables: FLASK_APP flask_app

Run manage.py from AWS EB Linux instance

How to run manage.py from AWS EB (Elastic Beanstalk) Linux instance?
If I run it from '/opt/python/current/app', it shows the below exception.
Traceback (most recent call last):
File "./manage.py", line 8, in <module>
from django.core.management import execute_from_command_line
ImportError: No module named django.core.management
I think it's related with virtualenv. Any hints?
How to run manage.py from AWS Elastic Beanstalk AMI.
SSH login to Linux (eb ssh)
(optional may need to run sudo su - to have proper permissions)
source /opt/python/run/venv/bin/activate
source /opt/python/current/env
cd /opt/python/current/app
python manage.py <commands>
Or, you can run command as like the below:
cd /opt/python/current/app
/opt/python/run/venv/bin/python manage.py <command>
With the new version of Python paths seem to have changed.
The app is in /var/app/current
The virtual environment is in /var/app/venv/[KEY]
So the instructions are:
SSH to the machine using eb shh
Check the path of your environment with ls /var/app/venv/. The only folder should be the [KEY] for the next step
Activate the environment with source /var/app/venv/[KEY]/bin/activate
Execute the command python3 /var/app/current/manage.py <command>
Of course Amazon can change it anytime.
TL;DR
This answer assumes you have installed EB CLI. Follow these steps:
Connect to your running instance using ssh.
eb ssh <environment-name>
Once you are inside your environment, load the environment variables (this is important for database configuration)
. /opt/python/current/env
If you wish you can see the environment variables using printenv.
Activate your virtual environment
source /opt/python/run/venv/bin/activate
Navigate to your project directory (this will depend on your latest deployment, so use the number of your latest deployment instead of XX)
cd /opt/python/bundle/XX/app/
Run the command you wish:
python manage.py <command_name>
Running example
Asumming that your environment name is my-env, your latest deployment number is 13, and you want to run the shell command:
eb ssh my-env # 1
. /opt/python/current/env # 2
source /opt/python/run/venv/bin/activate # 3
cd /opt/python/bundle/13/app/ # 4
python manage.py shell # 5
As of February 2022 the solution is as follows:
$ eb ssh
$ sudo su -
$ export $(cat /opt/elasticbeanstalk/deployment/env | xargs)
$ source /var/app/venv/*/bin/activate
$ python3 /var/app/current/manage.py <command name>
$ export $(cat /opt/elasticbeanstalk/deployment/env | xargs) is needed to import your environment variables if you have a database connection (most likely you will)

Categories