Flask

Flask is a straightforward framework to build web apps more quickly than ever.

Set up Flask

Install Flask :

pip install Flask

Lunch the app :

python3 application.py

Basic application structure :

Basic router file :

from flask import Flask, render_template

app = Flask(name)

@app.route('/') def welcome(): return render_template('hello.html')

@app.route('/login') def login(): return render_template('login.html')

if name == 'main': app.run(debug=True)

Connect MySQL Database to Flask project :

Install depedencies :

pip install flask flask-mysqldb mysql-connector-python

Set up router file with right db configuration :

from flask import Flask, render_template, request, redirect, url_for
from flask_mysqldb import MySQL

app = Flask(__name__)

# MySQL configurations
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'ayra'
app.config['MYSQL_PASSWORD'] = 'yourpassword'  # replace with your actual password
app.config['MYSQL_DB'] = 'hackerpoulette'

mysql = MySQL(app)

@app.route('/')
def welcome():
    return render_template('hello.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # Get form data
        username = request.form['username']
        last_name = request.form['lastName']
        email = request.form['email']
        country = request.form['country']
        gender = request.form['gender']
        services = request.form.getlist('service')  # Get list of selected services
        services_str = ','.join(services)  # Join the list into a string

        # Insert form data into the database
        cur = mysql.connection.cursor()
        cur.execute("INSERT INTO users(first_name, last_name, email, country, gender, service) VALUES (%s, %s, %s, %s, %s, %s)",
                    (username, last_name, email, country, gender, services_str))
        mysql.connection.commit()
        cur.close()
        return redirect(url_for('welcome'))
    return render_template('login.html')

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

Our current form :

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Login</title>
  </head>
  <style> form{ display:flex; flex-direction:row; justify-content:space-around; } div {border-style: dotted; padding: 30px;} </style>
  <body>
    <h1>Formulaire</h1>
    <form action="/login" method="post">
      <div>
        <label for="firstName" name="firstName">firstName:</label>
        <input type="text" id="firstName" name="username">
      </div>
      <div>
        <label for="lastName">lastName:</label>
        <input type="lastName" id="lastName" name="lastName">
      </div>
      <div>
        <label for="email">email</label>
        <input type="email" id="email" name="email">
      </div>
      <div>
        <label for="country">country</label>
        <input type="country" id="country" name="country">
      </div>
      <div>
        <label for="male">
          <input type="radio" id="male" name="gender" value="male">Male
        </label>
        <br>
        <label for="female">
          <input type="radio" id="female" name="gender" value="female">Female
        </label>
      </div>
      <div>
        <label for="repair">
          <input type="checkbox" id="repair" name="service" value="repair">Repair
        </label>
        <br>
        <label for="order">
          <input type="checkbox" id="order" name="service" value="order">Order
        </label>
        <br>
        <label for="others">
          <input type="checkbox" id="others" name="service" value="others">Others
        </label>
      </div>
      <div>
        <button type="submit">Submit</button>
      </div>
    </form>
  </body>
</html>
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    email VARCHAR(100),
    country VARCHAR(50),
    gender VARCHAR(10),
    service VARCHAR(255)
);

Verify the database is correctly connected :

SELECT * from USERS;

Sanitizing form input

Sanitizing form on client side :

Bleach is a python library which handle input and sanitize them before it's sent to the backend.

pip install bleach

Implementation of bleach in our router :

from flask import Flask, render_template, request, redirect, url_for
from flask_mysqldb import MySQL
import bleach

app = Flask(__name__)

# MySQL configurations
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'ayra'
app.config['MYSQL_PASSWORD'] = 'passwordhere'  # replace with your actual password
app.config['MYSQL_DB'] = 'hackerpoulette'

mysql = MySQL(app)

@app.route('/')
def welcome():
    return render_template('hello.html')

@app.route('/success')
def success():
    return render_template('success.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # Get form data
        username = bleach.clean(request.form['username'])  # Sanitize username
        last_name = bleach.clean(request.form['lastName'])  # Sanitize last name
        email = bleach.clean(request.form['email'])  # Sanitize email
        country = bleach.clean(request.form['country'])  # Sanitize country
        gender = request.form['gender']  # Gender doesn't need sanitization
        services = request.form.getlist('service')  # Get list of selected services
        services_str = ','.join(services)  # Join the list into a string

        # Insert form data into the database
        cur = mysql.connection.cursor()
        cur.execute("INSERT INTO users(first_name, last_name, email, country, gender, service) VALUES (%s, %s, %s, %s, %s, %s)",
                    (username, last_name, email, country, gender, services_str))
        mysql.connection.commit()
        cur.close()
        return redirect(url_for('success'))
    return render_template('login.html')

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

Prevent SQL injection by sanitizing server-side input data :

Instead of directly concatenating user inputs into SQL queries, parameterized queries use placeholders (%s in this case) to separate SQL code from user-supplied data. This method ensures that user inputs are treated as data rather than executable SQL code, thus preventing SQL injection attacks.

The MySQL library I'm using (pymysqld) automatically handles escaping special characters in the parameters passed through %s. This means that even if a user enters something like ' OR '1'='1', it will be safely treated as data rather than an attempt to modify the query structure.

Last updated

Was this helpful?