I'm trying to write to a file using Flask and docker.
If the file has anything in it before running, the file gets emptied and overwritten with a blank page. But my flask app isn't actually able to write to it.
I believe my volumes aren't setting up correctly. Here's what I have:
In my path I have:
matrices/sampleMatrix.txt
static/
templates/
app.py
Dockerfile
docker-compose.yml
Dockerfile
FROM python:3.6.1-alpine
ADD . .
RUN pip install -r requirements.txt
RUN pip install requests
#VOLUME [ "./matrices" ] <- Do I need this? Doesn't seem to do anything more than the compose file
WORKDIR /
CMD ["python","app.py"]
docker-compose.yml
version: '2'
services:
<container name>:
build: .
ports:
- 82:80
container_name: <container name>
volumes:
#- ./matrices:/var/lib/docker/matrices
- ./matrices:/matrices
^^ This last line I think is the mistake. The left side is set up correctly to write to the file locally, but the path on the right isn't writing to the correct file.
Flask app:
# This first block gets files in the matrices folder and confirms that my path matches a file which is there
for item in glob.glob("/matrices/*"):
print(item, file=sys.stderr)
fileName= "/matrices/sampleMatrix.txt"
print(item==fileName, file=sys.stderr)
fileName= "/matrices/sampleMatrix.txt"
print("Final path chosen: ",fileName, file=sys.stderr)
try:
#READ <- reads nothing even when I've written something in the file ahead of time
matrixFile= open(fileName, "w+")
print("About to read: ",fileName, file=sys.stderr)
print(matrixFile.read(), file=sys.stderr)
print("Read from: ",fileName, file=sys.stderr)
matrixFile.close()
#WRITE
matrixFile= open(fileName, "w+")
matrixFile.write("text:
")
#matrixFile.write(str(distanceMatrix))
print("wrote to: ",fileName, file=sys.stderr)
matrixFile.close()
#READ <- Reads nothing right after writing to the fil
matrixFile= open(fileName, "w+")
print("About to read: ",fileName, file=sys.stderr)
print(matrixFile.read(), file=sys.stderr)
print("Read from: ",fileName, file=sys.stderr)
matrixFile.close()
except: #<- this except never triggers, which tells me the file is found, it's just to doing anything with it
print("cant open file", file=sys.stderr)
My question here is, the Flask app clearly sees a file in matrices/ but for some reason, the docker path for the volume doesn't seem to be connecting to the right one.
question from:
https://stackoverflow.com/questions/65926350/cant-write-to-file-using-flask-and-docker-volumes 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…