To create a Python app that allows users to upload a file and saves the file name to a SQLite database, you can follow these steps:
Install the necessary libraries:
sqlite3: This library is used for interacting with SQLite databases. You can install it using pip install sqlite3.
python-dateutil: This library is used for formatting dates and times in a consistent manner across different languages and cultures. You can install it using pip install dateutil.
Create a new Python file and import the necessary libraries:
import sqlite3
from dateutil.relativedelta import relativedelta
Define a function to connect to the SQLite database and create a table if it doesn’t exist:
def connect_database():
db_file = 'uploads.db'
cnx = sqlite3.connect(db_file)
cnx.execute('CREATE TABLE IF NOT EXISTS uploads (filename TEXT PRIMARY KEY)')
return cnx
Define a function to save the file name to the database:
def save_file_name(filename):
cnx = connect_database()
cnx.execute('INSERT INTO uploads (filename) VALUES (?)', (filename,))
cnx.commit()
return True
Create a function to handle the file upload and call the save_file_name function:
def handle_upload(file):
try:
with open(file, 'rb') as f:
data = f.read()
filename = os.path.basename(file)
save_file_name(filename)
except Exception as e:
print(f'Error uploading file: {e}')
Create a form to handle the file upload and call the handle_upload function:
<form enctype="multipart/form-data" method="post">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
Handle the file upload in your Python script by calling the handle_upload function:
if **name** == '**main**':
handle_upload('file.txt')
Run the script and open a web browser to the form page. Select a file to upload and click the “Upload” button. The file name should now be saved in the SQLite database.
Here’s the complete code:
import sqlite3
from dateutil.relativedelta import relativedelta
import sqlite3
from dateutil.relativedelta import relativedelta
def connect_database():
db_file = 'uploads.db'
cnx = sqlite3.connect(db_file)
cnx.execute('CREATE TABLE IF NOT EXISTS uploads (filename TEXT PRIMARY KEY)')
return cnx
def save_file_name(filename):
cnx = connect_database()
cnx.execute('INSERT INTO uploads (filename) VALUES (?)', (filename,))
cnx.commit()
return True
form = HTMLForm()
def handle_upload(file):
try:
with open(file, 'rb') as f:
data = f.read()
filename = os.path.basename(file)
save_file_name(filename)
except Exception as e:
print(f'Error uploading file: {e}')
class HTMLForm():
def **init**(self):
self.form = HTMLForm()
def __call__(self, file):
self.form['file'] = FileField('File to upload')
return self.form
### Run script when main module is loaded
if **name** == '**main**':
handle_upload('file.txt')
Note: In this code, the HTMLForm class creates a simple HTML form with a file field named “File to upload”. The handle_upload function handles the file upload and saves the file name to the SQLite database using the save_file_name function.