Building a Simple Web App with Flask

 

Building a Simple Web App with Flask

Flask is a lightweight, flexible Python web framework that's ideal for beginners and experienced developers alike. Let's create a basic web application that displays a "Hello, World!" message.

1. Set Up the Environment

  • Install Python: Ensure you have Python installed on your system. You can download it from https://www.python.org/.
  • Install Flask: Use pip, Python's package manager, to install Flask:
    Bash
    pip install Flask
    

2. Create a New Python File

Create a new Python file, for example, app.py.

3. Import Flask

Import the Flask class from the Flask module:

Python
from flask import Flask

4. Create a Flask App Instance

Create an instance of the Flask class, passing the name of the application module as an argument:

Python
app = Flask(__name__)

5. Define a Route

Decorate a function with the @app.route() decorator to define a route for your web application. The route specifies the URL that will trigger the function:

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

6. Run the App

Use the app.run() method to start the development server:

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

Complete app.py Code:

Python
from flask import Flask

app = Flask(__name__)

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

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

Running the App

  • Open a terminal or command prompt.
  • Navigate to the directory where you saved app.py.
  • Run the following command:
    Bash
    python app.py
    
  • The development server will start. Open your web browser and go to http://127.0.0.1:5000/. You should see the message "Hello, World!".

Additional Features

  • Templates: Use Jinja2 templates to create dynamic HTML content.
  • Forms: Handle form submissions and process data.
  • Databases: Connect to databases using libraries like SQLAlchemy.
  • REST APIs: Build RESTful APIs for interacting with your application.

This is a basic example to get you started with Flask. As you explore more, you'll discover its flexibility and power in building various types of web applications.

Would you like to explore a specific feature of Flask or build a more complex web application?

Comments

Popular posts from this blog

Data Analysis with Pandas: A Practical Tutorial

overview of Python