Untitled

mail@pastecode.io avatar
unknown
plain_text
8 months ago
2.0 kB
3
Indexable
Never
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management App</title>
</head>
<body>
    <h1>User Management App</h1>
    <form action="/add_user" method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" required>
        <br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <br>
        <button type="submit">Add User</button>
    </form>
    <h2>Users:</h2>
    <ul>
        {% for user in users %}
            <li>{{ user[1] }} - {{ user[2] }}</li>
        {% endfor %}
    </ul>
</body>
</html>
from flask import Flask, render_template, request, redirect, url_for
import sqlite3

app = Flask(__name__)

# Create a SQLite database and table
conn = sqlite3.connect('app.db')
cursor = conn.cursor()
cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT NOT NULL,
        email TEXT NOT NULL
    )
''')
conn.commit()
conn.close()

@app.route('/')
def home():
    # Fetch users from the database
    conn = sqlite3.connect('app.db')
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM users')
    users = cursor.fetchall()
    conn.close()
    return render_template('index.html', users=users)

@app.route('/add_user', methods=['POST'])
def add_user():
    if request.method == 'POST':
        username = request.form['username']
        email = request.form['email']

        # Insert user into the database
        conn = sqlite3.connect('app.db')
        cursor = conn.cursor()
        cursor.execute('INSERT INTO users (username, email) VALUES (?, ?)', (username, email))
        conn.commit()
        conn.close()

    return redirect(url_for('home'))

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