0% found this document useful (0 votes)
6 views

Curd Flask

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Curd Flask

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

from flask import Flask, render_template, request, redirect, url_for, jsonify

import mysql.connector

app = Flask(__name__)

# Configuración de conexión a MySQL


app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'flaskcurd'
app.config['MYSQL_PASSWORD'] = 'D1niel#_FD'
app.config['MYSQL_DATABASE'] = 'flaskapp'

def get_db_connection():
return mysql.connector.connect(
host=app.config['MYSQL_HOST'],
user=app.config['MYSQL_USER'],
password=app.config['MYSQL_PASSWORD'],
database=app.config['MYSQL_DATABASE']
)

# Ruta para mostrar todos los usuarios


@app.route('/')
def index():
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
cursor.execute('SELECT * FROM users')
users = cursor.fetchall()
cursor.close()
connection.close()
return render_template('index.html', users=users)

# Ruta para agregar un nuevo usuario (Crear)


@app.route('/add', methods=['POST'])
def add_user():
name = request.form['name']
email = request.form['email']
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute('INSERT INTO users (name, email) VALUES (%s, %s)', (name, email))
connection.commit()
cursor.close()
connection.close()
return redirect(url_for('index'))

# Ruta para editar un usuario (Actualizar)


@app.route('/edit/<int:id>', methods=['GET', 'POST'])
def edit_user(id):
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
cursor.execute('UPDATE users SET name = %s, email = %s WHERE id = %s', (name, email, id))
connection.commit()
cursor.close()
connection.close()
return redirect(url_for('index'))

cursor.execute('SELECT * FROM users WHERE id = %s', (id,))


user = cursor.fetchone()
cursor.close()
connection.close()
return render_template('edit.html', user=user)

# Ruta para eliminar un usuario (Eliminar)


@app.route('/delete/<int:id>', methods=['GET', 'POST'])
def delete_user(id):
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute('DELETE FROM users WHERE id = %s', (id,))
connection.commit()
cursor.close()
connection.close()
return redirect(url_for('index'))

if __name__ == '__main__':
app.run(debug=True)

You might also like