'webbrowser.open_new(filename) doesn't work inside a flask docker container?
I have a flask api with an endpoint that creates a pdf invoice file. I use webbrowser.open_new(filename) to open the pdf in browser, and that works fine when I run it outside the container. But if run it with docker it doesn't work. Here are my files:
app.py
from flask import Flask, jsonify, request
from api_pdf import InvoicePDF
from flask_restful import Api
app = Flask(__name__)
api = Api(app)
invoice_pdf_routes = [f'/hello']
api.add_resource(InvoicePDF, *invoice_pdf_routes)
if __name__ == '__main__':
app.run(debug=True)
api_invoice.py
from flask_restful import Resource
from flask import Flask, jsonify, request
from datetime import datetime
import pdfkit
import webbrowser
class InvoicePDF(Resource):
def create_pdf(self):
pdf_content = """<html> <head><body>Invoice</body></html>"""
invoice_date = str(datetime.now().strftime('%m-%d-%Y'))
filename = "invoice_" + invoice_date + '.pdf'
options = {
"enable-local-file-access": ""
}
pdfkit.from_string(pdf_content, filename, options=options)
webbrowser.open_new_tab(filename)
return filename
def get(self):
self.create_pdf()
return True
Dockerfile
FROM python:3.9
ENV WERKZEUNG_RUN_MAIN=true \
PYTHONUNBUFFERED=1 \
PYTHONIOENCODING=UTF-8 \
FLASK_RUN_HOST=0.0.0.0 \
FLASK_APP=app.py
WORKDIR /app
COPY . /app/
RUN apt update && \
apt upgrade -y && \
apt-get install wkhtmltopdf -y && \
pip install --no-cache-dir -r requirements.txt
EXPOSE 5000
CMD ["flask", "run"]
requirements.txt
flask>=1.1.2,<2.0.0
flask-restful
pdfkit
markupsafe==2.0.1
What I am doing:
docker build -t test .
docker run -p 5000:5000 test
and on postman I do: GET http://127.0.0.1:5000/hello
expected result: request return True and a new browser tab open with invoice pdf file
what happens: request return True but new browser tab doesn't open
Why does this not work inside the container? Should I be using something other than webbrowser.open_new(filename) or am I going about this completely wrong? I don't want to save the pdf in a DB and have to call that.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
