If you love the freedom that PHP offers but want to harness the power of Python (e.g., for data processing or AI), Flask is the ideal choice. Unlike the massive Django, Flask does not require a complex structure.
1. Why Flask instead of Django?
- Simplicity: You can write an entire website in a single Python file.
- Total Control: You decide where your HTML and CSS documents are located.
- Speed: It's great for smaller projects, APIs, and connecting with Arduino devices.
2. Practical Example: A Simple "Hello World" Server
Below is the code that creates a web server in Python and displays a greeting:
from flask import Flask
app = Flask(name)
@app.route("/")
def home():
return "<h1>Hello, this is powered by Python!</h1>"
if name == "main":
app.run(debug=True)
When you run this code, your computer becomes a server. Visiting localhost:5000 will display your HTML heading in the browser.
3. Connecting with Full Stack Development
Flask uses the Jinja2 templating engine, which means you can insert Python variables into your HTML, similar to how you use <?php echo $variable; ?> in PHP.