This guide provides a quick start to get you up and running with Flask, a popular Python web framework. Whether you're new to web development or looking to switch from another framework, Flask is a great choice.

Installation

To install Flask, you can use pip:

pip install flask

Hello World

Here's a simple "Hello, World!" example:

from flask import Flask

app = Flask(__name__)

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

if __name__ == '__main__':
    app.run(debug=True)

Save this as app.py and run it. You should see a message "Hello, World!" in your browser when you navigate to http://127.0.0.1:5000/.

Templates

Flask uses Jinja2 as its template engine. You can create a template file named index.html in the templates folder:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello, Flask</title>
</head>
<body>
    <h1>Hello, Flask</h1>
</body>
</html>

To render this template, update your hello_world function:

from flask import render_template

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

Forms

To handle forms, Flask provides request object which contains data from the form submission:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form Example</title>
</head>
<body>
    <form action="/" method="post">
        <input type="text" name="name">
        <input type="submit" value="Submit">
    </form>
    {% if name %}
        <p>Hello, {{ name }}!</p>
    {% endif %}
</body>
</html>

Update your hello_world function:

@app.route('/', methods=['GET', 'POST'])
def hello_world():
    name = None
    if request.method == 'POST':
        name = request.form['name']
    return render_template('index.html', name=name)

Databases

Flask can be integrated with various databases using extensions like SQLAlchemy:

from flask_sqlalchemy import SQLAlchemy

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)

@app.route('/add', methods=['GET', 'POST'])
def add_user():
    if request.method == 'POST':
        user = User(username=request.form['username'])
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('hello_world'))

Deployment

For deploying Flask applications, you can use platforms like Heroku, AWS, or Google Cloud Platform.

For more detailed information and tutorials, check out our Flask Documentation.


Flask is a versatile and lightweight framework that can be used for a wide range of web applications. Whether you're building a simple blog or a complex web application, Flask has the tools you need to get the job done.

If you're looking for more information or tutorials, check out our Flask Documentation or join our community forums for support and advice.