flask basics

 

What is Flask?

Flask is a micro web framework written in Python. It’s called a "micro" framework because it provides the essential tools to build web applications without imposing any dependencies or project layout. This makes Flask lightweight and flexible, allowing developers to add extensions as needed.

Key Features of Flask:

  • Lightweight and modular.
  • Built-in development server and debugger.
  • RESTful request dispatching.
  • Jinja2 templating.
  • Support for secure cookies.

Setting Up Flask

Before we dive into the code, let's set up Flask. Here’s how you can install Flask:

  1. Install Python: Make sure Python is installed on your system. You can download it from python.org.

  2. Install Flask: Open your terminal or command prompt and run: pip install Flask

  3. Create a Project Directory: Create a directory for your project and navigate into it: cd my_flask_app

  4. Create a Virtual Environment:  python -m venv venv

             venv\Scripts\activate

Basic Flask Application Structure

A basic Flask application typically consists of a single Python file. Let’s create a simple "Hello, World!" application.

 from flask import Flask

app = Flask(__name__)

@app.route('/')

def hello_world():

    return 'Hello, World!'

if __name__ == '__main__':

    app.run(debug=True)

  • Importing Flask: We import the Flask class from the flask module.
  • Creating a Flask Instance: We create an instance of the Flask class. This instance will be our WSGI application.
  • Defining a Route: We use the @app.route('/') decorator to tell Flask which URL should trigger our function. In this case, the root URL (/) will call the hello_world function.
  • Running the Application: We run the application if this script is executed directly. The debug=True parameter enables the debugger and automatically restarts the server when code changes.
  • Comments

    Popular posts from this blog

    Gen ai Evloution