Thursday, May 9, 2024

Python revisited: a little web app

Python interpreter is a little read-eval-print loop. You can play with it without downloading anything, such as https://www.online-python.com/. But all you do is console stuff... Every tutorial just tells you how to use its data types, how do do loops and lists/tuples and so on... How about something more exciting like web app? BTW, nobody seems to be concerned about tab exactness or declaring your variables before use (like most other languages). Every programmer needs to know a thing or two about Python these days. You will need a little more than the interpreter to do a web app.

Enter Flask. Plenty of tutorials out there and many give you full-blown apps. I'm like come on, start with basics first?

First it needs to be installed.

On my computer (Mac), I have "pip3" (package installer for python) so I ran

pip3 install flask --upgrade
Then I have a little code like this:

from flask import Flask, render_template
app = Flask(__name__)

@app.get("/")
def index():
    return "this is home"

@app.get("/page1")
def page1():
   return "<h1>hello</h1><br/>This is like a <i>servlet</i>"
   
@app.get("/page2")
def page2():
    return render_template("mypage.html",name="Johnny")

if __name__=="__main__":
    app.run()

This gives you 3 pages, the main page "/", "/page1", and "/page2"

This is the local url: http://127.0.0.1:5000/

And python warned me this is just a development server, a toy.

The first two methods are straightforward... you have to punch in html that you are returning. Mixing html and code is nightmare from the original java servlet days like 1990s. It is hard to do a full blown web page even with the triple quote Python string isn't it?

The 3rd method is loading a templated file, which resides in my "templates" folder, it can take variables from the caller too:

mypage.html looks like this:

<h1>Hi {{name}}</h1>

This is a <i>simple</i>, but dynamic HTML page.
<p/>
{% for i in range(5) %}
  This is like jsp<br/>
{% endfor %}

This template file is html intermixed with code. and you can have loops and stuff too! Intermixing html and code can be difficult to maintain. This reminds me of Java Server Pages (which I think nobody uses nowadays)

This is a very simple example. Simple examples work better than complex examples for beginners. And that endfor above tells you that blocks are actually good thing.

No comments: