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
Flaskis the core class used to create the application.jsonifyhelps 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:
- Where the application lives
Flask needs to know the “root path” of your project to find things like templates (/templatesfolder) or static files (/staticfolder). For example:- If you put
index.htmlinsidetemplates/, Flask looks relative to the file where__name__points. - Same with
/staticfor images, CSS, or JavaScript.
- If you put
- 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
/templatesor/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 thehello()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 justlocalhost. Useful in containers or when running in the cloud.port=5000is the default for Flask.debug=Trueenables 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:
- Install Flask:
pip install flask - Save the code above in a file, e.g.,
app.py. - Run it:
python app.py - 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.