Deploying a flask api in python using Linux server.
On The asposecells library call the run gets stuck.this same program when tried on cherrypy causes no issue. Please help.
It seems that you are experiencing an issue where the Aspose.Cells library call is causing your Flask API to hang when deployed with Gunicorn, while it works fine with CherryPy. This type of problem can sometimes arise due to differences in how these servers handle threading and process management.
Here are a few suggestions to troubleshoot and potentially resolve the issue:
-
Check for Thread Safety: Ensure that the Aspose.Cells library is being used in a thread-safe manner. If your application is multi-threaded (which is common with Gunicorn), make sure that the library calls are not being made concurrently in a way that could lead to deadlocks or resource contention.
-
Use a Different Worker Class: Gunicorn supports different worker types. If you are using the default synchronous worker, consider switching to an asynchronous worker (like
gevent
oreventlet
) to see if that resolves the hanging issue. -
Debugging: Since you mentioned that there are no error messages, try adding logging around the Aspose.Cells calls to capture more information about what is happening when the hang occurs. This can help identify if the issue is with a specific part of the code.
-
Simplify the Code: Test with a minimal version of your code that only includes the Aspose.Cells functionality. This can help isolate the problem and determine if the issue is with the library itself or how it interacts with your Flask application.
-
Sample Code: Ensure that you are importing the Aspose.Cells library correctly at the start of your program. Here’s a simple example of how to use it in a Flask route:
from flask import Flask from asposecells.api import Workbook app = Flask(__name__) @app.route('/create_excel') def create_excel(): workbook = Workbook() # Add your logic here return "Excel file created!"
-
Testing in Console: Since you mentioned that the code works in the Python console, try to replicate the environment as closely as possible in your Gunicorn setup. This includes checking Python versions, library versions, and any environment variables.
If these suggestions do not resolve the issue, consider reaching out to the Aspose support team with detailed information about your setup, including the versions of Python, Flask, Gunicorn, and Aspose.Cells you are using.
If you need further assistance, feel free to ask!
Sources:
[1]: Python Flask Web server Hang at Aspose.Cells
The issue occurs exactly at the asposecells api call for Workbook().can you give a sample code of this library code working in flask
with gunicorn setup as I have tried many things but issue still persists.This same code works in chetrypy but not in gunicorn
@ar123
We understand the issue you are experiencing and are currently analyzing and trying to reproduce the issue. This may take some time. We will notify you as soon as we make progress.
@ar123
If the Aspose API call is commented out, can it still run normally? For example, can it output a simple “hello”?
Yes. Also all the commands before the api call gets executed.only on the api call the program gets stuck.if we comment out the api call the run completed normally
Please spare us little time to evaluate your issue thoroughly before we could update you on it. Hopefully, we will get back to you soon.
Hope the following sample code can help you.
Environment:
Linux+gunicorn+flask
Aspose.Cells python via java 24.11
import jpype
import asposecells
jpype.startJVM()
from asposecells.api import Workbook
from flask import Flask
app = Flask(__name__)
def start_jvm():
if not jpype.isJVMStarted():
jpype.startJVM()
def shutdown_jvm():
if jpype.isJVMStarted():
jpype.shutdownJVM()
@app.route('/')
def hello_world():
try:
workbook = Workbook()
workbook.getWorksheets().get(0).getCells().get("A1").putValue("Hello World")
workbook.save("output.xlsx")
shutdown_jvm()
return 'Hello World! test'
except Exception as e:
return jsonify({"error": str(e)})
finally:
shutdown_jvm()
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000)
Is this working in gunicorn.as my code is exactly similar to this except for shutdownJVM and the program gets stuck at Workbook()
@ar123
The sample code works when executing the following command in the test.
When you open this address in your browser, a sample file output.xlsx will be generated.
gunicorn -w 2 -b 127.0.0.1:5000 app:app
If you can’t find jpype, you may need to install the corresponding package
pip install jpype1
If these operations still can’t solve your problem, you can tell me your own sample code. This will help solve your problem.
For this same program code I am getting error on the Workbook() while running on gunicorn.If I am running on cheroot the program is a success
Please find the code below
I am configuring the setup for gunicorn as:
‘’’
#gunicornapp.py
from gunicorn.app.base import BaseApplication
class GunicornApp(BaseApplication):
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super().__init__()
def load(self):
return self.application
def load_config(self):
config = {key: value for key, value in self.options.items()
if key in self.cfg.settings and value is not None}
for key, value in config.items():
self.cfg.set(key.lower(), value)
and the main file is serverconfig.py as shown below
serverconfig…py
import os
import logging
import importlib
import sys
import importlib
logging.basicConfig(
stream=sys.stdout,
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', # Custom log format
)
logger = logging.getLogger(__name__)
app_module = os.getenv('MAIN_APP',None)
app_server = os.getenv('MAIN_SERVER', None)
app_port= os.getenv('MAIN_PORT', None)
app_worker=os.getenv('MAIN_WORKER', None)
server_log='serverlog.txt'
ADDRESS='0.0.0.0'
TIMEOUT=1800
app_mod = importlib.import_module(app_module)
If __name__ == "__main__":
# Log the environment and configuration details
logger.debug("Starting application...")
# If not Windows, use Gunicorn
logger.debug("Detected non-Windows OS. Using Gunicorn server.")
print("Running on a non-Windows OS, using Gunicorn...")
options = {
'bind': '%s:%s' %(ADDRESS,app_port),
'timeout':TIMEOUT, # Port 8000, can change to another port if needed
'workers':app_worker,
'acceslog':server_log # Number of worker processes, adjust based on your server
}
try:
GunicornApp(app, options).run()
print("Running on Gunicorn, ...")
except:
logger.exception("Error...")
ALso running this in docker and the docker file is as below:
.Docker file
FROM ubuntu:20.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y \
python3 \
python3-pip \
python3-dev \
python3-venv \
build-essential \
libssl-dev \
libffi-dev \
libpq-dev \
openjdk-11-jdk \
wget \
curl \
unzip \
&& rm -rf /var/lib/apt/lists/*
ENV JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
ENV PATH=$JAVA_HOME/bin:$PATH
RUN pip3 install --no-cache-dir virtualenvWORKDIR /app
COPY . /app
RUN python3 -m venv /app/venv
RUN /app/venv/bin/pip install --no-cache-dir -r /app/requirements.txt
ENV PATH=/app/venv/bin:$PATH
WORKDIR /app
CMD ["python3", "serverconfig.py"]
@duojie.yang still facing issue at the aspose cells.api call for Workbook with the same code given here…the gunicorn configured is given above
Thanks for the sample code, docker file and details.
We will evaluate your issue and get back to you with updates.
Any update on this
@ar123
We are still working hard to study your issue. We will notify you promptly once there are any updates.
@ar123
It is difficult for us to reproduce your problem based on the information you provided. Can you package your sample project according to the project directory structure?
e.g
test/
|----app.py
|----venv
Sorry do you need the codebase or the sample project structure
The sample project structure is as below;
aspose-sample/
|-.Dockerfile
|-gunicornapp.py
|-hello.py
|-requirements.txt
|-severconfig.py
Also regardingthe code for all these files .In the reply above where had earlier given the code have edited to reflect according to the project structure.The hello.py is the same sample code which was given by you.Please let me know if anything else is need
The env varables passed in the docker run command
main_App=hello,MAIN_SERVER=gunicorn(if one wants to run on gunicorn),main_port=the port which one wants to run,MAIN_WORKER=2