IT-INFO

Where IT meets innovation, IT-INFO lights the path to technological brilliance

Getting Started with Flask

Getting Started with Flask

Flask is a lightweight WSGI web application framework in Python. It is designed with simplicity and flexibility in mind.

Installation

To get started with Flask, you need to have Python installed. You can install Flask using pip.

pip install flask

Creating Your First Flask App

Let's create a simple Flask application. Create a new file named app.py and add the following content:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "Hello, World!"

Running Your Flask App

To run the Flask application, set the FLASK_APP environment variable and use the flask run command:

export FLASK_APP=app.py
flask run

Open your browser and go to http://127.0.0.1:5000. You should see "Hello, World!".

Creating API Endpoints

Flask allows you to easily create different types of API endpoints. For example, to create a new endpoint that accepts a URL parameter, you can add the following code to your app.py:

from flask import request

@app.route("/items/")
def get_item(item_id):
    return {"item_id": item_id}

Using Flask with Templates

Flask supports rendering templates using the Jinja2 template engine. To use templates, create a templates directory and add a file named index.html:




    Hello, Flask!


    

Hello, {{ name }}!

Edit your app.py to render this template:

from flask import render_template

@app.route("/hello/")
def hello(name):
    return render_template("index.html", name=name)

Conclusion

In this guide, you've learned how to install Flask, create a simple Flask application, and define different types of endpoints. Flask's simplicity and flexibility make it a great choice for small to medium-sized web applications. For more advanced features and customization, refer to the official Flask documentation.

Created on Aug. 7, 2024, 12:33 p.m.