15.3. Creating a simple web server
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.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Chapter 1: What Is Programming?
- ☰ 1.1. What is a computer program?
- ☰ 1.2. What is Python?
- ☰ 1.3. Where is Python used?
- ☰ 1.4. How programming helps solve problems
- ☰ 1.5. Your first Python program
-
- ☰ 2. Chapter 2: Setting Up Python
- ☰ 2.1. Installing Python (Windows / macOS / Linux)
- ☰ 2.2. Using Python in the terminal
- ☰ 2.3. Using an IDE (IDLE / VS Code)
- ☰ 2.4. Running Python scripts
- ☰ 2.5. Python interactive mode
-
- ☰ 3. Chapter 3: Variables and Data Types
- ☰ 3.1. What is a variable?
- ☰ 3.2. Creating variables
- ☰ 3.3. Numbers
- ☰ 3.4. Test
- ☰ 3.5. Boolean values
- ☰ 3.6. Type checking
-
- ☰ 4. Chapter 4: Basic Operations
- ☰ 4.1. Arithmetic operations
- ☰ 4.2. Working with numbers
- ☰ 4.3. String operations
- ☰ 4.4. Combining text and variables
- ☰ 4.5. Comments in Python
-
- ☰ 5. Chapter 5: User Input and Output
- ☰ 5.1. Getting input from the user
- ☰ 5.2. Converting input to numbers
- ☰ 5.3. Formatting output
- ☰ 5.4. Writing interactive programs
-
- ☰ 6. Chapter 6: Conditions
- ☰ 6.1. Comparison operators
- ☰ 6.2. Logical operators
- ☰ 6.3. if, elif, else
- ☰ 6.4. Nested conditions
- ☰ 6.5. Common beginner mistakes
-
- ☰ 7. Chapter 7: Loops
- ☰ 7.1. Why loops are useful
- ☰ 7.2. for loops
- ☰ 7.3. while loops
- ☰ 7.4. Loop counters
- ☰ 7.5. break and continue
- ☰ 7.6. Loop exercises
-
- ☰ 8. Chapter 8: Data Collections
- ☰ 8.1. Lists
- ☰ 8.2. Tuples
- ☰ 8.3. Dictionaries
- ☰ 8.4. Sets (basics)
- ☰ 8.5. Choosing the right data structure
-
- ☰ 9. Chapter 9: Functions
- ☰ 9.1. Why functions matter
- ☰ 9.2. Defining functions
- ☰ 9.3. Parameters and arguments
- ☰ 9.4. Return values
- ☰ 9.5. Scope (local vs global)
- ☰ 9.6. Reusing code
-
- ☰ 10. Chapter 10: Working with Files
- ☰ 10.1. What is a file?
- ☰ 10.2. Reading text files
- ☰ 10.3. Writing and appending files
- ☰ 10.4. File paths
- ☰ 10.5. Simple file-based programs
-
- ☰ 11. Chapter 11: Errors and Debugging
- ☰ 11.1. Types of errors
- ☰ 11.2. Reading error messages
- ☰ 11.3. Common beginner errors
- ☰ 11.4. try and except
- ☰ 11.5. Debugging strategies
-
- ☰ 12. Chapter 12: Using Python Libraries
- ☰ 12.1. What is a library?
- ☰ 12.2. Importing modules
- ☰ 12.3. Standard libraries
- ☰ 12.3.1. math
- ☰ 12.3.2. random
- ☰ 12.3.3. datetime
-
- ☰ 12.4. Installing external libraries with pip
-
- ☰ 13. Chapter 13: Object-Oriented Programming
- ☰ 13.1. What is object-oriented programming?
- ☰ 13.2. Classes and objects
- ☰ 13.3. The `__init__` method
- ☰ 13.4. Attributes and methods
- ☰ 13.5. Encapsulation
- ☰ 13.6. Inheritance (basics)
- ☰ 13.7. Simple OOP examples
-
- ☰ 14. Chapter 14: Automation with Python
- ☰ 14.1. What is automation?
- ☰ 14.2. Automating simple tasks
- ☰ 14.3. Working with files and folders
- ☰ 14.4. Automating text processing
- ☰ 14.5. Scheduling scripts
- ☰ 14.6. Practical automation examples
-
- ☰ 15. Chapter 15: Web Development with Python
- ☰ 15.1. How the web works (basic overview)
- ☰ 15.2. Introduction to Flask
- ☰ 15.3. Creating a simple web server
- ☰ 15.4. Routing and templates
- ☰ 15.5. Handling user input (forms)
- ☰ 15.6. Very basic APIs
-
- ☰ 16. Chapter 16: Data Science with Python
- ☰ 16.1. What is data science?
- ☰ 16.2. Working with data
- ☰ 16.3. Introduction to NumPy
- ☰ 16.4. Introduction to pandas
- ☰ 16.5. Data visualization with matplotlib
- ☰ 16.6. Simple data analysis examples
-
- ☰ 17. Chapter 17: Mini Projects
- ☰ 17.1. Number guessing game
- ☰ 17.2. Simple calculator
- ☰ 17.3. To-do list
- ☰ 17.4. Password generator
- ☰ 17.5. Quiz application
- ☰ 17.6. Small web or data project
-
- ☰ 18. Chapter 18: Next Steps
- ☰ 18.1. How to practice Python
- ☰ 18.2. Writing clean and readable code
- ☰ 18.3. Choosing a specialization
- ☰ 18.3.1. Web development
- ☰ 18.3.2. Data science
- ☰ 18.3.3. Automation
- ☰ 18.3.4. Software development
-
- ☰ 18.4. Learning resources and communities
-
- ☰ 19. Appendix
- ☰ 19.1. Python syntax cheat sheet
- ☰ 19.2. Common errors and solutions
- ☰ 19.3. Glossary of terms
-
Comments
Please login to add a comment.
Don't have an account? Register now!