0
0
Raspberry Piprogramming~5 mins

Flask web server on Raspberry Pi

Choose your learning style9 modes available
Introduction

A Flask web server lets your Raspberry Pi show web pages and respond to internet requests. It helps you create simple websites or control devices remotely.

You want to control Raspberry Pi devices from a phone or computer.
You want to create a small website hosted on your Raspberry Pi.
You want to collect data from sensors and show it on a webpage.
You want to learn how web servers work using a simple tool.
You want to build a home automation system accessible via browser.
Syntax
Raspberry Pi
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, Raspberry Pi!'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

@app.route('/') tells Flask what web address to listen to.

app.run(host='0.0.0.0') makes the server visible to other devices on the network.

Examples
Basic Flask server running on default localhost and port 5000.
Raspberry Pi
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Welcome to my Pi!'

if __name__ == '__main__':
    app.run()
Server listens on all network interfaces on port 8080 with a custom route.
Raspberry Pi
from flask import Flask

app = Flask(__name__)

@app.route('/status')
def status():
    return 'Pi is running smoothly!'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)
Sample Program

This program starts a Flask web server on your Raspberry Pi. When you open your Pi's IP address in a browser, it shows 'Hello, Raspberry Pi!'.

Raspberry Pi
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, Raspberry Pi!'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
OutputSuccess
Important Notes

Make sure Flask is installed on your Raspberry Pi using pip install flask.

Use host='0.0.0.0' to allow other devices on your network to access the server.

For security, this simple server is for learning and local use only, not for public internet.

Summary

Flask lets your Raspberry Pi serve web pages easily.

Use @app.route to set web addresses.

Run the server with app.run(host='0.0.0.0') to share on your network.