Running FastAPI multiple process error after pyinstaller - python

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

Uvicorn Pyinstaller Error loading ASGI App [duplicate]

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.

Running Flask by "flask run" vs running from editor (Windows 10)

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.

Python run command to launch server then continue my main program

I want to use command to launch server in python code, but main program stop here.
How to modify code to let server launch then continue my main program code.
This is my python code below.
import os
os.system('/usr/local/bin/python3.7 -m pyxtermjs')
print("Hello")
This is my console output below
serving on http://127.0.0.1:5000
* Serving Flask app "pyxtermjs.app" (lazy loading)
* 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
WebSocket transport not available. Install eventlet or gevent and gevent-websocket for improved performance.
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
You can use a Thread to multiprocess:
import os
from threading import Thread
def pro(): # Define a function to add to the Thread
os.system('/usr/local/bin/python3.7 -m pyxtermjs')
program = Thread(target=pro) # Define the Thread with the function
program.start() # Start the Thread
print('Hello World')
You should use subprocess.popen, like advised here
subprocess.Popen(["/usr/local/bin/python3.7", "-m", "pyxtermjs"])

CTRL+C does not terminate aiohttp app in Python 3.6 script on Windows

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)

Why heroku fails to find the python/flask module or application?

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!

Categories

Resources