BUILD A WEB APPLICATION FROM SCRATCH WITH FLASK AND PYTHON

  • June 07, 2024

    BUILD A WEB APPLICATION FROM SCRATCH WITH FLASK AND PYTHON

    Introduction

    Flask is a popular micro-framework in Python for creating lightweight and scalable web applications. In this walkthrough, we will build a web application from scratch using Flask and Python. By the end of this article, you will have a basic understanding of how to create a web application, set up routes, and work with templates.

    Requirements:

    1. Python 3.6 or later
    2. Flask (install it using pip install Flask)

    Step 1: Setting up the Flask Application

    To begin developing your web application, start by creating a dedicated directory to house your project files. This organization is crucial as your application scales and potentially integrates more components.

    • Create Project Directory: Open your terminal or command prompt and run the following commands to create a new directory and navigate into it:
    mkdir briskbrain_flask_app
    cd briskbrain_flask_app
    • Create a Python File: Within this directory, create a file named app.py. This file will serve as the entry point for your Flask application. You can use any text editor to create and edit this file.
    from flask import Flask

    app = Flask(__name__) # Create a Flask instance

    # Define a basic route and a function that will be called when accessing the root URL
    @app.route('/')
    def home():
    return 'Hello BriskBrain, Flask!'

    if __name__ == "__main__":
    app.run(debug=True) # Run the app in debug mode

    Explanation:

    • from flask import Flask: Imports the Flask class from the Flask library.
    • app = Flask(__name__): Instantiates the Flask class. __name__ is a Python special variable which is set to the name of the module in which it is used.
    • app.route('/')The decorator that tells Flask what URL should trigger the function that follows.
    • app.run(debug=True): Starts the application with the ability to print out possible Python errors on the web page. This will help you trace the errors.

    Step 2: Adding Routes

    Routes are essential in Flask as they define the endpoints and HTTP methods your application can handle. Each route is associated with a Python function, which is executed when the route is accessed.

    • Create a Simple Route: Let’s define a basic route to our application:
    @app.route('/')
    def home():
    return 'Welcome to the Flask App from BriskBrain Technologies!'
    • Adding a New Route:

    Suppose we want a page that greets the user by name. We add another route as follows:

    @app.route('/briskbrainteam/<name>')
    def briskbrainteam(name):
    return f'Hello, {name}!'

    Explanation:

    • The route /briskbrainteam/<name> is a dynamic route that accepts an input from the URL.
    • briskbrainteam(name) is the function that will be invoked at this route.

    Step 3: Using Templates

    To make web pages dynamic, we use Jinja2 templates, which are integrated with Flask. Templates allow you to inject data into HTML files from your Flask application.

    • Set Up Templates Directory:
    1. Create a folder named templates in your project directory.
    2. Inside this folder, create an HTML file named index.html.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BriskBrain Flask App</title>
    </head>
    <body>
    <h1>{{ message }}</h1>
    </body>
    </html>
    • Modify the Home Function:

    Modify the home function in app.py to render the index.html file

    from flask import render_template

    @app.route('/')
    def home():
    return render_template('index.html', message='Welcome to Briskbrain Team!')

    Explanation:

    • render_template is used to generate output from a template file based on the Jinja2 engine that Flask uses.

    Step 4: Working with Forms

    Handling form data is straightforward in Flask. You can easily gather data submitted by users and process it.

    • Create a Form Template:

    In the templates folder, create another HTML file called form.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BriskBrain Form Example</title>
    </head>
    <body>
    <form action="/submit" method="POST">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>
    <button type="submit">Submit</button>
    </form>
    </body>
    </html>
    • Handle Form Submission:

    Add routes to display the form and to handle the form submission:

    from flask import request

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

    @app.route('/submit', methods=['POST'])
    def submit():
    name = request.form['name']
    return f'Hello, {name}!'

    Explanation:

    • The form in form.html submits a POST request to the /submit route.
    • The submit() function retrieves data from the form and returns a personalized greeting.

    Conclusion

    This guide provided a fundamental walkthrough for creating a simple web application using Flask, Python’s micro-framework. We covered setting up your project, defining routes, using templates for dynamic content, and handling form data. With these core components, you now possess the basic skills to expand your application further. You might consider adding advanced features like user authentication, integrating a database, or developing RESTful APIs to enhance functionality and user experience. Explore and experiment to make the most of what Flask has to offer!

    Comments

WhatsApp