Table of Contents
What You’ll Build in This Chapter
In this chapter, you will:
- Start a very simple web server with Python and Flask.
- Understand how a Python script listens for web requests.
- See how a URL in the browser is connected to a function in your code.
- Run and test your web server on your own computer.
You’ll need Flask installed (covered earlier in this chapter’s parent section). All examples assume you have a file named app.py and can run it with Python.
The Basic Structure of a Flask Web Server
A minimal Flask web server has three main parts:
- Import Flask
- Create the app object
- Define routes (URLs) and what they return
- Start the server
Here is the smallest useful Flask server:
from flask import Flask
app = Flask(__name__) # 1. create the app object
@app.route("/") # 2. connect URL "/" to this function
def home():
return "Hello from my first web server!" # 3. response
if __name__ == "__main__": # 4. start the server when script is run
app.run()Line by line, what’s happening that is specific to web servers:
Flask(__name__): creates a web application object. This object:- Knows how to listen for web requests.
- Knows how to send back responses.
@app.route("/"): tells Flask:- “When someone visits the root URL (
/), run thehome()function.” return "...": whatever this function returns becomes the HTTP response body (what the browser shows).app.run(): starts a development web server on your computer.
Running the Server and Visiting It in the Browser
Save the previous code as app.py, then in your terminal:
python app.pyYou should see output similar to:
* Serving Flask app 'app'
* Debug mode: off
* Running on http://127.0.0.1:5000Key points:
http://127.0.0.1:5000is the address of your web server:127.0.0.1orlocalhostmeans “this computer”.:5000is the port number Flask uses by default.- Open a browser and go to:
http://127.0.0.1:5000/
orhttp://localhost:5000/
You should see:
- A blank page with the text:
Hello from my first web server!
Behind the scenes:
- Your browser sends a request to
localhost:5000/. - Flask receives it and sees that
"/"matches the@app.route("/")decorator. - Flask calls the
home()function. - The string it returns is sent back to the browser.
Adding More Pages (Routes)
A web server can respond to different URLs. Each URL usually has its own function.
You can add more routes like this:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Welcome to the home page."
@app.route("/about")
def about():
return "This is the about page."
@app.route("/contact")
def contact():
return "Contact us at: example@example.com"
if __name__ == "__main__":
app.run()Now you can visit:
http://localhost:5000/→ home pagehttp://localhost:5000/about→ about pagehttp://localhost:5000/contact→ contact page
Important details:
- URLs usually do not end with
.pyor.htmlhere. They are just paths like/about. - Each
@app.route("...")decorator connects a URL path to a Python function.
Returning Simple HTML from Your Server
So far we are returning plain text, but web pages are usually HTML.
You can return small HTML snippets directly as strings:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return """
<h1>My Simple Web Server</h1>
<p>This is a basic page served by Flask.</p>
"""
@app.route("/about")
def about():
return """
<h1>About</h1>
<p>This page is also generated by Python!</p>
"""
if __name__ == "__main__":
app.run()Notes:
- Triple quotes
""" ... """let you write multi-line strings. - The browser interprets the string as HTML, not as plain code.
Changing the Host and Port (Optional but Useful)
By default, app.run():
- Uses host
127.0.0.1(only your computer). - Uses port
5000.
You can change these:
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)host="0.0.0.0": listen on all network interfaces (useful if you want other devices on your local network to access it).port=8000: change the port number. Then you would visit:
http://localhost:8000/
For practice, just using the default app.run() is enough.
Using Debug Mode While Developing
While learning and testing, it is common to use debug mode:
if __name__ == "__main__":
app.run(debug=True)Debug mode:
- Automatically restarts the server when you change your code.
- Shows a more detailed error page in the browser when something goes wrong.
Use debug mode only on your own computer, not on a real public server.
A Tiny Multi-Page Example
Here is a slightly more complete example of a simple web server with multiple pages:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return """
<h1>Welcome!</h1>
<p>This is the home page of my simple Flask website.</p>
<p>Try visiting <a href="/hello">/hello</a> or <a href="/about">/about</a>.</p>
"""
@app.route("/hello")
def hello():
return "<h1>Hello there!</h1><p>This page says hello.</p>"
@app.route("/about")
def about():
return """
<h1>About This Site</h1>
<p>This site is powered by a tiny Python web server using Flask.</p>
"""
if __name__ == "__main__":
app.run(debug=True)Steps:
- Run
python app.py. - Open your browser at
http://localhost:5000/. - Click the links to visit the other routes.
You now have a working multi-page web server written in just a few lines of Python.
Common Issues When Starting Your First Server
Here are some typical problems and quick checks:
- “ModuleNotFoundError: No module named 'flask'”
- Flask is not installed in your Python environment.
- Install it with
pip install flask(as covered earlier). - Browser says: “This site can’t be reached”
- Is your server running in the terminal?
- Did you close the terminal or stop the server with
Ctrl + C? - Are you visiting the right URL (
http://localhost:5000/)? - Port already in use
- Another process might be using port
5000. - Run the app on a different port:
app.run(port=5001)- Code changes not showing up
- Did you restart the server after editing
app.py? - Or did you enable debug mode:
app.run(debug=True)?
Summary
In this chapter, you:
- Created a basic Flask web server in a file like
app.py. - Started the server with
app.run()and visited it in the browser. - Mapped URLs to Python functions using
@app.route. - Returned text and simple HTML from your routes.
- Added multiple pages to your simple web server.
You now have the foundation needed to connect this simple server to templates and user input (forms) in the next sections.