analitics

Pages

Wednesday, August 14, 2024

Python 3.12.1 : Web server with SQLite database using flask.

This python surce script can be used to start a web server with an SQLite server.
For example, you can use this to test with javascript on sql server, see next image:
This is the source code:
from flask import Flask, request, jsonify, render_template_string
import sqlite3
from datetime import datetime

app = Flask(__name__)

# Clasa pentru serverul SQL
class SQLServer:
    def __init__(self, db_name):
        self.db_name = db_name
        self.init_db()

    def init_db(self):
        conn = sqlite3.connect(self.db_name)
        c = conn.cursor()
        c.execute('''
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY,
                first_name TEXT,
                last_name TEXT,
                occupation TEXT,
                hobby TEXT,
                year_of_birth INTEGER,
                age INTEGER
            )
        ''')
        conn.commit()
        conn.close()

    def calculate_age(self, year_of_birth):
        # Adjust year_of_birth if only two digits are provided
        if len(str(year_of_birth)) == 2:
            if year_of_birth > int(str(datetime.now().year)[-2:]):
                year_of_birth += 1900
            else:
                year_of_birth += 2000
        current_year = datetime.now().year
        return current_year - year_of_birth

    def add_user(self, first_name, last_name, occupation, hobby, year_of_birth):
        age = self.calculate_age(year_of_birth)
        conn = sqlite3.connect(self.db_name)
        c = conn.cursor()
        c.execute('''
            INSERT INTO users (first_name, last_name, occupation, hobby, year_of_birth, age)
            VALUES (?, ?, ?, ?, ?, ?)
        ''', (first_name, last_name, occupation, hobby, year_of_birth, age))
        conn.commit()
        conn.close()

    def get_users(self):
        conn = sqlite3.connect(self.db_name)
        c = conn.cursor()
        c.execute("SELECT * FROM users")
        users = c.fetchall()
        conn.close()
        return users

# Clasa pentru serverul web
class WebServer:
    def __init__(self, sql_server):
        self.sql_server = sql_server

    def run(self):
        app.run(debug=True)

    @app.route('/')
    def index():
        users = sql_server.get_users()
        return render_template_string('''
            <h1>Users</h1>
            <ul>
                {% for user in users %}
                    <li>{{ user[1] }} {{ user[2] }} - {{ user[3] }} - {{ user[4] }} - {{ user[5] }} ({{ user[6] }} years old)</li>
                {% endfor %}
            </ul>
            <h2>Add User</h2>
            <form action="/add_user" method="post">
                First Name: <input type="text" name="first_name"><br>
                Last Name: <input type="text" name="last_name"><br>
                Occupation: <input type="text" name="occupation"><br>
                Hobby: <input type="text" name="hobby"><br>
                Year of Birth: <input type="text" name="year_of_birth"><br>
                <input type="submit" value="Add User">
            </form>
        ''', users=users)

    @app.route('/add_user', methods=['POST'])
    def add_user():
        first_name = request.form['first_name']
        last_name = request.form['last_name']
        occupation = request.form['occupation']
        hobby = request.form['hobby']
        year_of_birth = int(request.form['year_of_birth'])
        sql_server.add_user(first_name, last_name, occupation, hobby, year_of_birth)
        return 'User added successfully! <a href="/">Go back</a>'

# Instanțierea serverului SQL și a serverului web
sql_server = SQLServer('example.db')
web_server = WebServer(sql_server)

if __name__ == '__main__':
    web_server.run()