我有一个后端项目,最终结果存储在fragrant_detection.db中。我正在尝试使用 Flask 和 docker,但似乎无法让所有东西运行起来。
这是我的文件树
DE-Project/
│
├── .dockerignore
├── docker-compose.yaml
├── Dockerfile.train_model
├── Dockerfile.producer
├── Dockerfile.consumer
├── Dockerfile.frontend
│
├── shared/
│ └── requirements.txt
│ └── kaggle.json
│
├── train_model/
│ ├── train_model.py
│ └── functions.py
│
└── make_predictions/
│ └── producer.py
│ └── consumer.py
│ └── functions.py
│ └── fraud_detection.db
└── frontend/
├── app.py
├── test.py
└── templates/
└── index.html
这是烧瓶应用程序.py
from flask import Flask, render_template
import sqlite3
import os
app = Flask(__name__)
# Set the path to the templates folder explicitly
template_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app.template_folder = template_path
# Get the absolute path to the directory containing this script
script_dir = os.path.dirname(os.path.abspath(__file__))
# Construct the absolute path to the database file
db_file_path = os.path.join(script_dir, 'make_predictions/fraud_detection.db')
@app.route('/')
def index():
# Connect to the SQLite database using the absolute path
conn = sqlite3.connect(db_file_path)
# Create a cursor object to execute SQL queries
cur = conn.cursor()
# Execute a query to fetch all entries (assuming your table is named 'potential_fraud')
sqlite_select_Query = "SELECT * FROM potential_fraud LIMIT 10;"
# Execute the query
cur.execute(sqlite_select_Query)
# Fetch all the entries
record = cur.fetchall()
# Close the database connection
conn.close()
# Render the HTML template with the entries
return render_template('index.html', entries=record)
if __name__ == '__main__':
# Run the Flask app on port 5000
这是我的 Dockerfile:
# Use an official Python runtime as a parent image
FROM python:3.8
# Set the working directory to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . /app
# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
# Expose port 5000 to the outside world
EXPOSE 5000
# Run app.py when the container launches
CMD ["python", "app.py"]
当我在 docker 中运行它时,通过本地主机访问它时出现此错误:
File "app.py", line 20, in index
conn = sqlite3.connect(db_file_path)
sqlite3.OperationalError: unable to open database file
据我所知,当文件路径出现问题时通常会发生此错误。我用 test.py 测试了连接,效果很好:
import sqlite3
conn = sqlite3.connect('make_predictions/fraud_detection.db')
cur = conn.cursor()
sqlite_select_Query = "SELECT * FROM potential_fraud LIMIT 1;"
cur.execute(sqlite_select_Query)
record = cur.fetchall()
print(record)
cur.close()
conn.close()
print("The SQLite connection is closed")
我的 app.py 中有什么错误吗?也许是我的 Dockerfile 或者两者都有?
我设法解决了我的问题。诀窍,或者说我的解决方案,是将数据库放入共享驱动器中。我在 docker-compose、consumer.py 和前端中指定了它。这有效。我想更好的解决方案是在完全独立的容器中设置真正的数据库。但这目前有效:)