Kahibaro
Discord Login Register

Creating a simple web server

What You’ll Build in This Chapter

In this chapter, you will:

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:

  1. Import Flask
  2. Create the app object
  3. Define routes (URLs) and what they return
  4. 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:

Running the Server and Visiting It in the Browser

Save the previous code as app.py, then in your terminal:

python app.py

You should see output similar to:

 * Serving Flask app 'app'
 * Debug mode: off
 * Running on http://127.0.0.1:5000

Key points:

You should see:

Behind the scenes:

  1. Your browser sends a request to localhost:5000/.
  2. Flask receives it and sees that "/" matches the @app.route("/") decorator.
  3. Flask calls the home() function.
  4. 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:

Important details:

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:

Changing the Host and Port (Optional but Useful)

By default, app.run():

You can change these:

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=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:

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:

  1. Run python app.py.
  2. Open your browser at http://localhost:5000/.
  3. 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:

  1. “ModuleNotFoundError: No module named 'flask'”
    • Flask is not installed in your Python environment.
    • Install it with pip install flask (as covered earlier).
  2. 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/)?
  3. Port already in use
    • Another process might be using port 5000.
    • Run the app on a different port:
     app.run(port=5001)
  1. 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:

You now have the foundation needed to connect this simple server to templates and user input (forms) in the next sections.

Views: 18

Comments

Please login to add a comment.

Don't have an account? Register now!