I am running python FastAPI with UVICORN with multiple processors (5 processes),It is running smoothly from the code, but when I tried make the exe from pyinstaller and try to run the file, it is showing error.
filename: main.py
import multiprocessing
import os
import uvicorn
from fastapi import FastAPI
app = FastAPI()
#app.get("/")
async def root():
return {"message": "Hello World"}
if __name__ == "__main__":
multiprocessing.freeze_support()
print("Running the instance")
uvicorn.run("main:app", host="0.0.0.0", port=9000, workers=5)
Output code from source
python3 main.py
Running the instance
INFO: Uvicorn running on http://0.0.0.0:9000 (Press CTRL+C to quit)
INFO: Started parent process [17828]
INFO: Started server process [17869]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Started server process [17870]
INFO: Waiting for application startup.
INFO: Application startup complete.
I make a single file using pyinstaller with the following command
pyinstaller --onefile main.py
and while running the main file using
./main
get the following error
Running the instance
INFO: Uvicorn running on http://0.0.0.0:9000 (Press CTRL+C to quit)
INFO: Started parent process [18964]
ERROR: Error loading ASGI app. Could not import module "main".
ERROR: Error loading ASGI app. Could not import module "main".
How to refer the main:app, what is the actual class name after installer is created?
I read somewhere that we need to use like
foldername.main:app , but that also not working
I tried your program and installing with
pyinstaller --onefile --hidden-import=main main.py
solved it for me.
Related
I am running python FastAPI with UVICORN with multiple processors (5 processes),It is running smoothly from the code, but when I tried make the exe from pyinstaller and try to run the file, it is showing error.
filename: main.py
import multiprocessing
import os
import uvicorn
from fastapi import FastAPI
app = FastAPI()
#app.get("/")
async def root():
return {"message": "Hello World"}
if __name__ == "__main__":
multiprocessing.freeze_support()
print("Running the instance")
uvicorn.run("main:app", host="0.0.0.0", port=9000, workers=5)
Output code from source
python3 main.py
Running the instance
INFO: Uvicorn running on http://0.0.0.0:9000 (Press CTRL+C to quit)
INFO: Started parent process [17828]
INFO: Started server process [17869]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Started server process [17870]
INFO: Waiting for application startup.
INFO: Application startup complete.
I make a single file using pyinstaller with the following command
pyinstaller --onefile main.py
and while running the main file using
./main
get the following error
Running the instance
INFO: Uvicorn running on http://0.0.0.0:9000 (Press CTRL+C to quit)
INFO: Started parent process [18964]
ERROR: Error loading ASGI app. Could not import module "main".
ERROR: Error loading ASGI app. Could not import module "main".
How to refer the main:app, what is the actual class name after installer is created?
I read somewhere that we need to use like
foldername.main:app , but that also not working
I tried your program and installing with
pyinstaller --onefile --hidden-import=main main.py
solved it for me.
If I run my Flask app through the command "flask run", not only the arguments in app.run are ignored (making debugger false and choosing the default port 5000), but changes made to the script too, e.g. changing url_prefix to "/views". The cmd prompt won't even respond when I save the script after making alterations. This way, changes are only effective after stopping the script then running again.
This doesn't happen when the app script is ran through VSCode commands (Ctrl+F5 or the play button): through those, the script is executed as written and changes are recognized right after saving a script.
Why is that so?
from flask import Flask
from views import views
app = Flask(__name__)
app.register_blueprint(views, url_prefix="/")
if __name__ == '__main__':
app.run(debug=True, port=8000)
C:\Users\*******\Documents\flask_quick_website>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
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
The flask executable works by importing the app object from your code. This is similar to how a WSGI server like gunicorn works (research what this is if you're unsure).
As for when you run the script with VSCode, or in-fact if you launch with the python executable by running python app.py or similar, then anything inside the if __name__ == '__main__': block is executed, in your case the app.run call.
Also note your app.run call is passed the debug=True argument. If you investigate the Flask source code, inside the run function, the use_reloader argument is set to the same value as debug so in this case the auto-reloader runs if debug is True.
So how to make the auto-reloader work with the flask command? Pass the --reload flag:
flask run --reload
You can also set the environment to development to achieve the same. On windows:
> set FLASK_ENV=development
> flask run
See Environment and Debug features for more on this.
I have a simple API with the following tree structure:
.
├── api
│ ├── fast.py
│ └── __init__.py
├── Dockerfile
├── Makefile
└── requirements.txt
The contents of fast.py are as follows:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
app = FastAPI()
#app.get("/")
def index():
return {"greeting": "Hello world!!!!!!!!!!!!!!"}
#app.get("/predict")
def predict():
# create a datetime object from the user provided datetime
return {'cool': True}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
The contents of the Dockerfile are as follows:
FROM python:3.8.6-buster
COPY api /api
COPY requirements.txt /requirements.txt
RUN pip install -r requirements.txt
CMD uvicorn api.fast:app --host 0.0.0.0 --port $PORT
When I start the API on my localhost in my Windows machine using wsl, it works fine, and I can access my API:
# uvicorn api.fast:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [20733] using statreload
INFO: Started server process [20770]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: 127.0.0.1:40446 - "GET / HTTP/1.1" 200 OK
However, when I try to access it from within a Docker container, I have issues. First I build the image as follows:
docker build --tag=docker_api_example .
then I run a container as follows:
docker run -it -e PORT=8000 -p 8000:8000 docker_api_example sh
The container opens up and I run the same uvicorn command again:
# uvicorn api.fast:app --reload
The process appears to start with no issues:
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [8] using statreload
INFO: Started server process [10]
INFO: Waiting for application startup.
INFO: Application startup complete.
However, when I navigate to http://127.0.0.1:8000 on my browser I get an error:
Why does this occur and how can I fix it?
A simple Python 3.6 script using aiohttp and python-socketio and running on Windows 10 outputs the following when started:
======== Running on http://0.0.0.0:8080 ========
(Press CTRL+C to quit)
However, pressing CTRL+C does not terminate the script! I had to open Task Manager and kill each of the Python processes until killing one of them releases the aiohttp script back to the command prompt.
Any one experienced the same problem?
from aiohttp import web
import socketio
sio = socketio.AsyncServer()
app = web.Application()
sio.attach(app)
#sio.on('connect')
def connect(sid, environ):
print(sid)
if __name__ == '__main__':
web.run_app(app)
my heroku app runs into application error with the following logs:
Starting process with command `gunicorn run:app`
Failed to find application: run
here is my Procfile
web: gunicorn run:flask_app
run.py file
from app import create_app, db
from app.auth.models import User
if __name__ == '__main__':
flask_app = create_app('prod')
with flask_app.app_context():
db.create_all()
if not User.query.filter_by(user_name='harry').first():
User.create_user(user='harry', email='harry#potters.com', password='secret')
flask_app.run()
Your main-method does not get executed (AFAIK) because Gunicorn is calling your script, you are not executing it as the main-file. Try moving the flask_app out of your main-method to the top of the file so Gunicorn can actually find it when importing your run.py!