Pages

Saturday 8 April 2023

Web Application using Flask with Visual Studio Code

Introduction

In this article, we will learn how to use Flask with Visual Studio Code (VS Code) in Python. Flask is a web framework that allows us to build web applications quickly and easily. VS Code is a powerful and popular code editor that can help us to develop our Flask application efficiently.

Setting up a Flask Project in VS Code:


To get started with Flask in VS Code, we need to create a new project folder and open it in VS Code. We can do this by following these steps:


Open VS Code and click on the "Explorer" icon on the left-hand side of the screen.

Click on the "Open Folder" button and create a new folder for your project.

Open the new folder in VS Code.

Next, we need to create a virtual environment for our project. A virtual environment allows us to install and manage project-specific packages without affecting the global Python installation. We can create a virtual environment by opening a new terminal window in VS Code and running the following command:

python -m venv venv

This will create a new virtual environment called "venv" in our project folder.


After creating the virtual environment, we need to activate it by running the following command in the terminal:


source venv/bin/activate

Creating a Flask Application:

Next, we can create a Flask application in our project folder. We can do this by creating a new Python file called app.py and adding the following code:


from flask import Flask


app = Flask(__name__)


@app.route('/')

def hello():

    return 'Hello, World!'

In this code, we import the Flask class from the flask module and create an instance of it called app. We then define a route for the root URL / and a function called hello() that returns the string "Hello, World!".


Running the Flask Application:

To run the Flask application, we need to set the FLASK_APP environment variable to app.py and run the flask run command in the terminal. We can do this by running the following commands:


export FLASK_APP=app.py

flask run

This will start the Flask development server and output the URL of our application. We can open this URL in a web browser to see the "Hello, World!" message.

Using Templates in Flask:


Flask provides a built-in template engine called Jinja2, which allows us to create HTML templates for our web application. Using templates can make our code more organized and easier to maintain, as we can separate our application logic from the presentation layer.


To use templates in Flask, we first need to create a folder called templates in our project directory. Inside this folder, we can create a new HTML file called index.html, and add the following code:


<!DOCTYPE html>

<html>

  <head>

    <title>{{ title }}</title>

  </head>

  <body>

    <h1>{{ heading }}</h1>

    <p>{{ content }}</p>

  </body>

</html>

In this code, we use Jinja2 syntax to include dynamic content in our HTML template. We can pass in values for the title, heading, and content variables when we render the template.


To render the template in our Flask application, we need to modify our app.py file to include the following code:


from flask import Flask, render_template


app = Flask(__name__)


@app.route('/')

def index():

    title = 'Flask App'

    heading = 'Welcome to my Flask App'

    content = 'This is my first Flask App'

    return render_template('index.html', title=title, heading=heading, content=content)

In this code, we import the render_template function from the flask module and modify the index() function to return the rendered template instead of a string. We pass in values for the title, heading, and content variables using keyword arguments.


Using Forms in Flask:

Flask also provides support for creating and processing HTML forms in our web application. To use forms in Flask, we need to create a form class that inherits from the FlaskForm class provided by the flask_wtf module.


We can create a new file called forms.py in our project directory and add the following code:


from flask_wtf import FlaskForm

from wtforms import StringField, SubmitField


class NameForm(FlaskForm):

    name = StringField('Name')

    submit = SubmitField('Submit')

In this code, we create a form class called NameForm that has a single field called name and a submit button called submit.


We can then modify our app.py file to include the following code:


from flask import Flask, render_template

from forms import NameForm


app = Flask(__name__)

app.config['SECRET_KEY'] = 'mysecretkey'


@app.route('/', methods=['GET', 'POST'])

def index():

    form = NameForm()

    if form.validate_on_submit():

        name = form.name.data

        form.name.data = ''

        return render_template('name.html', name=name)

    return render_template('index.html', form=form)

Using SQL in Flask

Before we begin, make sure that you have MySQL installed on your machine, and you have created a database with a table. You will also need to install the Flask-MySQLdb package. You can install it by running the following command in your terminal:


pip install flask-mysqldb
Once you have installed Flask-MySQLdb, create a new file called app.py. In this file, import the necessary modules:


from flask import Flask, render_template, request
from flask_mysqldb import MySQL
Next, create a Flask app and configure it to connect to your MySQL database:


app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'your_username'
app.config['MYSQL_PASSWORD'] = 'your_password'
app.config['MYSQL_DB'] = 'your_database'
Replace 'your_username', 'your_password', and 'your_database' with your actual MySQL credentials and database name.

Now, initialize a MySQL instance and connect it to your Flask app:


mysql = MySQL(app)
This creates a MySQL instance that is bound to your Flask app.

Next, create a route to display data from your MySQL database:


@app.route('/')
def index():
    cur = mysql.connection.cursor()
    cur.execute('''SELECT * FROM your_table''')
    data = cur.fetchall()
    cur.close()
    return render_template('index.html', data=data)
This route creates a cursor object to execute SQL queries, executes a SELECT statement to retrieve all data from your table, fetches all the data from the cursor, closes the cursor and returns the data to an HTML template called index.html.

Create an index.html template in a templates directory and add the following code:


<!DOCTYPE html>
<html>
<head>
    <title>Flask-MySQLdb Example</title>
</head>
<body>
    <h1>Data from MySQL Database</h1>
    <table>
        {% for row in data %}
        <tr>
            <td>{{ row[0] }}</td>
            <td>{{ row[1] }}</td>
            <td>{{ row[2] }}</td>
        </tr>
        {% endfor %}
    </table>
</body>
</html>
This template displays the data from the MySQL database in a table.

Finally, add a conditional statement to check if the app is being run directly and then run it:


if __name__ == '__main__':
    app.run(debug=True)
Your complete app.py file should look something like this:


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

app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'your_username'
app.config['MYSQL_PASSWORD'] = 'your_password'
app.config['MYSQL_DB'] = 'your_database'

mysql = MySQL(app)

@app.route('/')
def index():
    cur = mysql.connection.cursor()
    cur.execute('''SELECT * FROM your_table''')
    data = cur.fetchall()
    cur.close()
    return render_template('index.html', data=data)

if __name__ == '__main__':
    app.run(debug=True)
Run your app by typing the following command in your terminal:


python app.py
You should now be able to access your Flask app at http://localhost:5000/ and see the data from your MySQL database displayed


Session Management in Flask

Session management is an important aspect of web development, as it allows us to store user data across multiple requests. Flask provides a simple way to manage sessions using the session object provided by the flask module.


To use sessions in Flask, we need to first set a secret key for our application. We can do this by adding the following code to our app.py file:

app = Flask(__name__)

app.config['SECRET_KEY'] = 'mysecretkey'

In this code, we set the SECRET_KEY configuration variable to a secret value. This value is used to securely sign session cookies and should be kept secret.


We can then modify our index() function to store and retrieve data from the session:

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


app = Flask(__name__)

app.config['SECRET_KEY'] = 'mysecretkey'


@app.route('/', methods=['GET', 'POST'])

def index():

    if request.method == 'POST':

        session['name'] = request.form['name']

        return redirect(url_for('index'))

    name = session.get('name')

    return render_template('index.html', name=name)

In this code, we use the session object to store and retrieve the name variable. When the user submits the form, we store the name in the session using the session['name'] = request.form['name'] code. When the user visits the page again, we retrieve the name from the session using the session.get('name') code.

Authentication in Flask:

Authentication is the process of verifying the identity of a user. Flask provides several extensions that make it easy to add authentication to our web application. One popular extension is Flask-Login, which provides user session management, password hashing, and more.


To use Flask-Login in our application, we first need to install it using pip:

pip install flask-login

We can then create a new file called models.py in our project directory and add the following code:


from flask_login import UserMixin


class User(UserMixin):

    def __init__(self, id, username, password):

        self.id = id

        self.username = username

        self.password = password


    def __repr__(self):

        return f'<User {self.username}>'

In this code, we create a User class that inherits from the UserMixin class provided by Flask-Login. We define three attributes for each user: an id, a username, and a password.


We can then modify our app.py file to include the following code:

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

from flask_login import LoginManager, login_user, current_user

from models import User


app = Flask(__name__)

app.config['SECRET_KEY'] = 'mysecretkey'


login_manager = LoginManager()

login_manager.init_app(app)


@login_manager.user_loader

Conclusion

In conclusion, Flask is a powerful and flexible web framework in Python that is widely used for building web applications. It provides a simple and elegant way to develop web applications quickly and efficiently. Flask is easy to set up and has a small footprint, making it ideal for small to medium-sized projects.

Flask is highly customizable and extensible, with a large number of third-party extensions available that can be easily integrated into Flask applications. Flask supports different database systems, including MySQL, PostgreSQL, and SQLite, making it a versatile option for data-driven web applications.

One of the most significant advantages of Flask is its excellent documentation, which is thorough and easy to understand, making it easy to get started with Flask. Flask also has an active and supportive community that provides help and support to developers who use the framework.

In summary, Flask is a powerful and versatile web framework in Python that is easy to learn and use. It is an excellent option for building small to medium-sized web applications and can be easily extended and customized to meet specific project requirements.


No comments:

Post a Comment