article

Sunday, December 20, 2020

Python Flask Delete image unlink files from folder and records from the database MySQLdb

Python Flask Delete image unlink files from folder and records from the database MySQLdb

app.py
 
#app.py
from flask import Flask, render_template, jsonify, request
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
import os

app = Flask(__name__)
    
app.secret_key = "caircocoders-ednalan-2020"
    
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'testingdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)

UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/')
def main():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    result = cur.execute("SELECT * FROM uploads ORDER BY id")
    gallery = cur.fetchall()
    return render_template('delete.html', gallery=gallery)
 
@app.route('/delete/')
def delete(get_ig):
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    result = cur.execute("SELECT * FROM uploads WHERE id = %s", [get_ig])
    data = cur.fetchone()
    filename = data['file_name']
	
    os.unlink(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    cur.execute('DELETE FROM uploads WHERE id = {0}'.format(get_ig))
    mysql.connection.commit()
    cur.close()
    print('File successfully deleted!')
    msg = 'Success deleted'		
    return jsonify(msg)
	
if __name__ == '__main__':
    app.run(debug=True)
templates/delete.html
//templates/delete.html
<html>  
 <head>  
  <title>Python Flask Delete image unlink files from folder and records from the database MySQLdb </title> 
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>  
 </head>  
 <body> 
<div class="container">
	<div class="row">
	<div class="col-md-12">
        <h4>Python Flask Delete image unlink files from folder and records from the database MySQLdb </h4>
        <div class="table-responsive">
		<table id="mytable" class="table table-bordred table-striped">
            <thead>
                <th>Photo</th>
                <th>Delete</th>
            </thead>
		<tbody>
		{% for row in gallery %}
		<tr>
		<td><img src="static/uploads/{{row.file_name}}" width="60"/></td>
		<td><p><a href="/delete/{{row.id}}" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-trash"></span></a></p></td>
		</tr>
		{% endfor %}
		</tbody>   
		</table> 
        </div>
        </div>
	</div>
</div>
 </body>  
</html>   

Related Post