Flask / Flask Basics

Getting Started with Flask

This tutorial will guide you through the basics of setting up a Flask environment, creating a simple Flask application, and understanding the basic principles of this microframewo…

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Introduces Flask, its features, and basic concepts including routing, templates, and request handling.

1. Introduction

In this tutorial, we will learn how to create a simple web application with Flask. Flask is a micro web framework written in Python, which means it does not require particular tools or libraries. It has a small and easy-to-extend core. It’s a microframework that doesn’t include an ORM (Object Relational Manager) or such features.

You will learn:
- How to set up a Flask environment
- How to create a simple Flask application
- Understand the basic principles of Flask

Prerequisites:
- Basic knowledge of Python programming language
- Python installed on your machine (Python 3 recommended)

2. Step-by-Step Guide

Installation

Before we begin, we need to install Flask. Open your terminal and type:

pip install flask

Basic Flask App

Now, let's create a new file named "app.py" and write our first Flask web app:

# Importing flask module in the project is mandatory
# An object of Flask class is our WSGI application.
from flask import Flask

# Flask constructor takes the name of
# current module (__name__) as argument.
app = Flask(__name__)

# The route() function of the Flask class is a decorator,
# which tells the application which URL should call
# the associated function.
@app.route('/')
# ‘/’ URL is bound with welcome() function.
def welcome():
    return "Welcome to Flask!"

# main driver function
if __name__ == '__main__':

    # run() method of Flask class runs the application
    # on the local development server.
    app.run()

Running the App

Save the file and in the terminal, navigate to the directory containing the file you just created and run the app using the command:

python app.py

You will see output telling you that the server is running. Open a web browser and navigate to http://127.0.0.1:5000/ to see your application.

3. Code Examples

Let's create a new route in our application:

@app.route('/hello/<name>')
def hello_name(name):
    return 'Hello %s!' % name

In this example, '/' URL is bound to the 'hello_name()' function. As a result, if we navigate to http://127.0.0.1:5000/hello/John, 'Hello John!' will be rendered in the web browser.

4. Summary

In this tutorial, we learned how to set up a Flask environment, create a simple Flask application, and create routes in the application.

Next steps for learning include exploring how to use templates in Flask to create more complex web pages, and learning about how to handle form data and create RESTful web services with Flask.

Additional resources:
- The Flask Documentation (http://flask.palletsprojects.com/en/1.1.x/)
- Flask Web Development with Python Tutorial (https://www.tutorialspoint.com/flask)

5. Practice Exercises

  1. Extend the app to include a route that takes in two numbers as inputs and returns their sum.
  2. Create a route that returns a simple HTML page instead of just a string.
  3. Create a route that takes in a string and returns the string reversed.

Solutions:

@app.route('/add/<int:num1>/<int:num2>')
def add(num1, num2):
    return str(num1 + num2)
@app.route('/home')
def home():
    return '''
    <html>
    <body>
    <h1>Welcome to My Home Page!</h1>
    </body>
    </html>
    '''
@app.route('/reverse/<string>')
def reverse(string):
    return string[::-1]

Remember, the best way to learn Flask is by practice. Try to create your own web application using what you've learned in this tutorial.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help