Home Azure Cloud Understanding a Simple Web Server Code Using Python (Flask)

Understanding a Simple Web Server Code Using Python (Flask)

218
0

In the blog post Deploying Python (Flask) App with VS Code to Azure App Service, we saw the following short script that created a simple web application using the Flask Python library:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/")
def hello():
    return jsonify(message="Hello from Python on Azure via Flask!")

if __name__ == "__main__":
    # For local development only
    app.run(host="0.0.0.0", port=5000, debug=True)

At first glance, this code looks simple, but it actually demonstrates the core building blocks of a Flask web server: creating an application, defining routes, returning responses, and running a local server for testing.

In this post, let’s break it down step by step and understand how it works.


What is Flask?

Flask is a lightweight web framework for Python. It doesn’t come with everything pre-installed like Django, but that’s its strength—you get only what you need, and you can plug in extra components (databases, templates, authentication) later.

  • ✅ Easy to start: Just a few lines of code get you a working server.
  • ✅ Flexible: You choose the structure and extensions.
  • ✅ Great for APIs: Returning JSON is simple and natural.
  • ✅ Best use cases: Small projects, APIs, microservices, or when you want full control.

Breaking Down the Code

1. Importing Flask and jsonify

from flask import Flask, jsonify
  • Flask is the core class used to create the application.
  • jsonify helps return responses in JSON format, which is the standard for APIs.

2. Creating the Application

app = Flask(__name__)
  • This initializes the Flask app.

What __name__ Means in Python

In Python, every file (module) has a special variable called __name__.

  • If you run a file directly, Python sets __name__ = "__main__".
  • If you import that file as a module, __name__ becomes the module’s name (e.g., "app" or "myfile").

So __name__ is a way for Python to know “where” the code is running from.

Why Flask Uses It

When you create a Flask app with:

app = Flask(__name__)

you’re passing that __name__ into Flask so it knows:

  1. Where the application lives
    Flask needs to know the “root path” of your project to find things like templates (/templates folder) or static files (/static folder). For example:
    • If you put index.html inside templates/, Flask looks relative to the file where __name__ points.
    • Same with /static for images, CSS, or JavaScript.
  2. Error messages and debugging
    When Flask logs errors or stack traces, it uses __name__ to show which module the error came from.

What If You Didn’t Use __name__?

If you wrote:

app = Flask("myapp")
  • Flask would still run, but it might not correctly find the default folders like /templates or /static, unless you explicitly configure them.
  • Using __name__ is a safe default, because it always points to the correct location of your current file.

✅ In short:
__name__ tells Flask “this is where my app is defined”, so Flask can correctly find templates, static files, and other resources relative to that file.


3. Defining a Route

@app.route("/")
def hello():
    return jsonify(message="Hello from Python on Azure via Flask!")
  • @app.route("/") maps the root URL (/) to the hello() function.
  • Whenever someone visits http://localhost:5000/, Flask runs the function.
  • The function returns a JSON response:
{ "message": "Hello from Python on Azure via Flask!" }

This is why Flask is so common for building REST APIs—returning structured data is straightforward.


4. Running the Development Server

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)
  • This block makes sure the app runs only if the file is executed directly (not imported as a module).
  • host="0.0.0.0" means the app is available on all network interfaces, not just localhost. Useful in containers or when running in the cloud.
  • port=5000 is the default for Flask.
  • debug=True enables hot-reloading and detailed error pages. Great for development, but never use it in production for security reasons.

Running the App Locally

You can try this yourself:

  1. Install Flask: pip install flask
  2. Save the code above in a file, e.g., app.py.
  3. Run it: python app.py
  4. Open your browser and go to http://localhost:5000.

You should see the JSON message appear. 🎉


Moving to Azure

When running locally, using app.run() is fine. But in Azure App Service (or any production cloud platform), the server is managed by Azure.

Instead of running Flask directly, Azure uses a production-ready WSGI server (like Gunicorn) that imports your app object.

That’s why keeping this line at the top level is important:

app = Flask(__name__)

It allows Azure (or any deployment service) to discover and run your application properly.


To Try: Adding More Functionality

Once you understand the basics, you can expand your app quickly:

  • Add another route: @app.route("/ping") def ping(): return jsonify(status="ok")
  • Return HTML instead of JSON: @app.route("/hello-html") def hello_html(): return "<h1>Hello from Flask!</h1>"
  • Use dynamic parameters: @app.route("/hello/<name>") def hello_name(name): return jsonify(greeting=f"Hello, {name}!")

With just a few lines, you can create APIs, serve web pages, or connect to a database.


Recap

This short Flask program introduced you to:

  • Setting up a Flask app
  • Creating a route (/) to handle requests
  • Returning JSON responses
  • Running the app locally with debugging
  • Preparing it for deployment on Azure

Flask is simple but powerful. It gives you the flexibility to build anything from a one-page web server to a scalable API service hosted on the cloud.

Previous articleDeploying Python (FLASK) App with VS Code To Azure App Service
Next articlePython for Serverless Programming with Azure Functions on VS Code
Heartin Kanikathottu
As a seasoned Cloud and Security Architect, I’ve led transformative initiatives in key roles, including Vice President at Morgan Stanley, Principal Architect at Societe Generale, and Tech Lead & Cloud Security Architect at VMware, among others. I’m also an internationally published author with multiple books available on platforms like Amazon and O'Reilly. Notably, one of my books was recognized as the 8th best cloud computing book of all time in 2020, reflecting the impact of my contributions to the field. With over 15 professional certifications from providers such as Microsoft (Azure), Amazon (AWS), Oracle (Java), Pivotal (Spring), and IBM, I bring a wealth of expertise to my work. Academically, I hold dual Master’s degrees in Cloud Computing and Data Analytics. I’m passionate about sharing knowledge and mentoring others, which is why I actively speak at global technical forums such as Tech Opportunities Fest at Platform Calgary, Google's Kubernetes Meetup, Java User Group, Elasticsearch Meetup, and the Agile India Conference.

LEAVE A REPLY

Please enter your comment!
Please enter your name here