DEV Community

Cover image for πŸš€ Beginner's Guide to Flask Web Development
likhitha manikonda
likhitha manikonda

Posted on

πŸš€ Beginner's Guide to Flask Web Development

Welcome to your first steps into the world of Flask! Flask is a lightweight and powerful web framework for Python that makes it easy to build web applications. In this guide, we'll walk through the essential concepts of Flask in simple terms with examples and explanations for beginners.


🧠 Introduction to Flask Framework

Flask is a micro web framework written in Python. It’s called β€œmicro” because it doesn’t require particular tools or libraries. It gives you the flexibility to choose your components.

Why Flask?

  • Simple and easy to learn
  • Great for small to medium-sized applications
  • Large community and lots of extensions

Installation

To install Flask, use pip:

pip install flask
Enter fullscreen mode Exit fullscreen mode

πŸ—οΈ Understanding a Simple Flask App Skeleton

Here’s the basic structure of a Flask app:

from flask import Flask

app = Flask(__name__)  # Create a Flask app instance

@app.route('/')        # Define a route for the home page
def home():
    return "Hello, Flask!"  # Return a simple response

if __name__ == '__main__':
    app.run(debug=True)  # Run the app in debug mode
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Flask(__name__): Initializes the app. __name__ helps Flask locate resources.
  • @app.route('/'): Maps the URL / to the home() function.
  • home(): Returns a response when the route is accessed.
  • app.run(debug=True): Starts the server and shows errors in the browser.

🌐 Integrating HTML with Flask Web App

Flask can render HTML templates using the render_template() function.

Folder Structure:

project/
β”œβ”€β”€ app.py
└── templates/
    └── index.html
Enter fullscreen mode Exit fullscreen mode

app.py:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')  # Renders the HTML file
Enter fullscreen mode Exit fullscreen mode

templates/index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Flask App</title>
</head>
<body>
    <h1>Welcome to Flask!</h1>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Flask looks for HTML files in the templates/ folder.
  • render_template() loads and displays the HTML file.

πŸ” Working with HTTP Verbs: GET and POST

Flask supports different HTTP methods like GET and POST to handle form data.

Example:

from flask import Flask, request

app = Flask(__name__)

@app.route('/form', methods=['GET', 'POST'])
def form():
    if request.method == 'POST':
        name = request.form['name']  # Get data from form
        return f"Hello, {name}!"
    return '''
        <form method="post">
            Name: <input type="text" name="name">
            <input type="submit">
        </form>
    '''
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • GET: Loads the form.
  • POST: Submits the form and processes the data.

πŸ”— Building Dynamic URLs, Variable Rules, and Jinja2 Template Engine

Dynamic URLs:

@app.route('/user/<username>')
def show_user(username):
    return f"User: {username}"
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • <username> is a variable in the URL.
  • Flask passes it to the function as an argument.

Jinja2 Template Engine

Jinja2 lets you embed Python-like expressions in HTML.

Example profile.html:

<h1>Hello, {{ name }}!</h1>

Enter fullscreen mode Exit fullscreen mode

app.py:

@app.route('/hello/<name>')
def hello(name):
    return render_template('profile.html', name=name)
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • {{ name }} is replaced with the actual value passed from Flask.

πŸ”Œ Working with REST APIs and HTTP Verbs PUT and DELETE

Flask makes it easy to build RESTful APIs using different HTTP methods.

Example:

from flask import Flask, request, jsonify

app = Flask(__name__)
data = {}

@app.route('/item/<key>', methods=['PUT'])
def put_item(key):
    value = request.json.get('value')  # Get JSON data
    data[key] = value
    return jsonify({key: value})

@app.route('/item/<key>', methods=['DELETE'])
def delete_item(key):
    if key in data:
        del data[key]
        return jsonify({'message': 'Deleted'})
    return jsonify({'error': 'Not found'}), 404
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • PUT: Adds or updates data.
  • DELETE: Removes data if it exists.

βœ… Summary

Concept Description
Flask Micro web framework for Python
App Skeleton Basic structure with routes
HTML Integration Use render_template and templates/ folder
GET/POST Handle form data and user input
Dynamic URLs Use <variable> in routes
Jinja2 Template engine for dynamic HTML
REST APIs Build endpoints with PUT and DELETE

Top comments (0)