Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active May 2, 2024 04:02
Show Gist options
  • Save code-boxx/1093a138538fe6439c88944047233841 to your computer and use it in GitHub Desktop.
Save code-boxx/1093a138538fe6439c88944047233841 to your computer and use it in GitHub Desktop.
Upload File To Database In Python Flask

PYTHON FLASK UPLOAD FILE INTO DATABASE

https://code-boxx.com/python-flask-upload-file-database/

NOTES

  1. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Create templates and static folders.
    • Move 2-upload.html into templates.
    • Move x-dummy.css into static
    • Download dummy image below.
    • Create a virtual environment - virtualenv venv
    • Activate the virtual environment - venv\scripts\activate (Windows) venv/bin/activate (Mac/Linux)
    • Install Flask pip install flask werkzeug
    • Create dummy database python 1b-create.py
    • Launch HTTP server python 3-server.py
  2. Open your browser, access http://localhost, and upload any dummy file.
  3. Open demo.db and confirm the upload.

DUMMY IMAGE FOR TESTING

vegetarian

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE `storage` (
`file_name` TEXT PRIMARY KEY,
`file_mime` TEXT NOT NULL,
`file_data` BLOB NOT NULL
);
# (A) LOAD PACKAGES
import sqlite3, os
from sqlite3 import Error
# (B) DATABASE + SQL FILE
DBFILE = "demo.db"
SQLFILE = "1a-database.sql"
# (C) DELETE OLD DATABASE IF EXIST
if os.path.exists(DBFILE):
os.remove(DBFILE)
# (D) IMPORT SQL
conn = sqlite3.connect(DBFILE)
with open(SQLFILE) as f:
conn.executescript(f.read())
conn.commit()
conn.close()
print("Database created!")
<!DOCTYPE html>
<html>
<head>
<title>Upload File</title>
<meta charset="utf-8">
<link rel="stylesheet" href="static/x-dummy.css">
</head>
<body>
<form method="post" action="/upload" target="_blank" enctype="multipart/form-data">
<input type="file" name="upload" required>
<input type="submit" name="submit" value="Upload File">
</form>
</body>
</html>
# (A) INIT
# (A1) LOAD MODULES
from flask import Flask, render_template, request, make_response
from werkzeug.utils import secure_filename
import sqlite3
# (A2) FLASK SETTINGS + INIT
HOST_NAME = "localhost"
HOST_PORT = 80
app = Flask(__name__)
# app.debug = True
# (B) ENDPOINTS
# (B1) FILE UPLOAD PAGE
@app.route("/", methods=["GET", "POST"])
def index():
return render_template("2-upload.html")
# (B2) SAVE UPLOADED FILE
@app.route("/upload", methods = ["POST"])
def saveup():
# (B2-1) GET FILE INFO
up = request.files["upload"]
updata = up.read()
upname = secure_filename(up.filename)
upmime = up.content_type
# (B2-2) SAVE INTO DATABASE
conn = sqlite3.connect("demo.db")
cursor = conn.cursor()
cursor.execute(
"REPLACE INTO storage (`file_name`, `file_mime`, `file_data`) VALUES (?,?,?)",
(upname, upmime, updata)
)
conn.commit()
conn.close()
return "OK"
# (B3) DOWNLOAD
@app.route("/download", methods=["GET", "POST"])
def dl():
# (B3-1) GET FILE FROM DATABASE
conn = sqlite3.connect("demo.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM storage WHERE `file_name`=?", ("vegetarian.png",))
dbfile = cursor.fetchone()
# (B3-2) FORCE DOWNLOAD
response = make_response(dbfile[2], 200)
response.headers["Content-type"] = dbfile[1]
response.headers["Content-Transfer-Encoding"] = "Binary"
response.headers["Content-Disposition"] = "attachment; filename=\"%s\"" % dbfile[0]
return response
# (C) START
if __name__ == "__main__":
app.run(HOST_NAME, HOST_PORT)
md templates
md static
move 2-upload.html templates
move x-dummy.css static
curl https://user-images.githubusercontent.com/11156244/280895847-3b52c85a-041b-4f11-bc1a-699dc31bf74a.png --ssl-no-revoke --output vegetarian.png
virtualenv venv
call venv\Scripts\activate
pip install flask werkzeug
python 1b-create.py
python 3-server.py
mkdir -m 777 static
mkdir -m 777 templates
mv ./2-upload.html ./templates
mv ./x-dummy.css ./static
curl https://user-images.githubusercontent.com/11156244/280895847-3b52c85a-041b-4f11-bc1a-699dc31bf74a.png --ssl-no-revoke --output ./vegetarian.png
virtualenv venv
source "venv/bin/activate"
pip install flask werkzeug
python 1b-create.py
python 3-server.py
/* NOT IMPORTANT */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body {
max-width: 400px;
}
form {
padding: 20px;
border: 1px solid #ededed;
background: #f2f2f2;
}
input, select {
display: block;
width: 100%;
padding: 10px;
}
input[type=file], select {
border: 1px solid #c9c9c9;
background: #fff;
}
input[type=submit] {
margin-top: 20px;
border: 0;
color: #fff;
background: #3c56b7;
cursor: pointer;
}
div.note {
padding: 10px;
margin-bottom: 20px;
border: 1px solid #a9dfff;
background: #edf7ff;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment