PythonPlaza - Python & AI

Python - Flask

A lightweight web framework for creating web apps and APIs is called Python Flask. It was developed by Armin Ronacher and is regarded as a micro-framework since it offers developers flexibility and control by only providing necessary functionality. Werkzeug, which regulates server connection, and Jinja2, which controls HTML templating, are the foundations of Flask.

Flask's simplicity is one of its main advantages. Because it lacks built-in database and authentication mechanisms, developers can build extensions like Flask-Login or SQLAlchemy as needed. It is very customizable because of its modular design.

Flask makes code clear and clean by using routing to link URLs to Python functions, frequently with decorators. Additionally, it uses Jinja2 templates to allow dynamic web pages.

Furthermore, Flask comes with an integrated development server and debugger that aid in the process of development. All things considered, Flask's flexibility and ease of use make it perfect for novices, small projects, and scalable applications.

Here's a sample REST webservice in Python.




Install dependencies:

pip install flask flask-mysqldb
 2. MySQL Database

Create a database and table:

CREATE DATABASE flask_crud;

USE flask_crud;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100)
);
 3. Flask App (CRUD API)
from flask import Flask, request, jsonify
from flask_mysqldb import MySQL

app = Flask(__name__)

# MySQL Configuration
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'yourpassword'
app.config['MYSQL_DB'] = 'flask_crud'

mysql = MySQL(app)

# -------------------
# CREATE (POST)
# -------------------
@app.route('/users', methods=['POST'])
def create_user():
    data = request.get_json()
    name = data['name']
    email = data['email']

    cur = mysql.connection.cursor()
    cur.execute("INSERT INTO users(name, email) VALUES(%s, %s)", (name, email))
    mysql.connection.commit()
    cur.close()

    return jsonify({"message": "User created"}), 201

# -------------------
# READ ALL (GET)
# -------------------
@app.route('/users', methods=['GET'])
def get_users():
    cur = mysql.connection.cursor()
    cur.execute("SELECT * FROM users")
    rows = cur.fetchall()
    cur.close()

    users = []
    for row in rows:
        users.append({
            "id": row[0],
            "name": row[1],
            "email": row[2]
        })

    return jsonify(users)

# -------------------
# READ ONE (GET)
# -------------------
@app.route('/users/', methods=['GET'])
def get_user(id):
    cur = mysql.connection.cursor()
    cur.execute("SELECT * FROM users WHERE id = %s", (id,))
    row = cur.fetchone()
    cur.close()

    if row:
        return jsonify({
            "id": row[0],
            "name": row[1],
            "email": row[2]
        })
    return jsonify({"message": "User not found"}), 404

# -------------------
# UPDATE (PUT)
# -------------------
@app.route('/users/', methods=['PUT'])
def update_user(id):
    data = request.get_json()
    name = data['name']
    email = data['email']

    cur = mysql.connection.cursor()
    cur.execute(
        "UPDATE users SET name=%s, email=%s WHERE id=%s",
        (name, email, id)
    )
    mysql.connection.commit()
    cur.close()

    return jsonify({"message": "User updated"})

# -------------------
# DELETE (DELETE)
# -------------------
@app.route('/users/', methods=['DELETE'])
def delete_user(id):
    cur = mysql.connection.cursor()
    cur.execute("DELETE FROM users WHERE id = %s", (id,))
    mysql.connection.commit()
    cur.close()

    return jsonify({"message": "User deleted"})

# -------------------
# RUN APP
# -------------------
if __name__ == '__main__':
    app.run(debug=True)