Python Web Programming¶

資訊之芽 梁安哲 2024/05/12

課前提問¶

還喜歡超級貓貓星際探險嗎?

Outline¶

  • Internet Basics
  • Frontend? Backend?
  • Flack Introduction
  • HTML
  • Flask Cont.
  • Template Response
  • Deployment
  • Remarks
  • Homework

Internet Basics¶

What is the Internet?¶

相互連接的電腦所組成的網路。

OSI 7-Layer Protocol Reference Model¶

讓全世界不同國家制定的標準、廠商製造的設備能相互溝通。

Example: Application Layer¶

應用程式 對應的通訊協定
Web HTTP(RFC 2616)
Email SMTP(RFC 2821)
File FTP(RFC 959)

Example: Data-link Layer¶

HTTP in action¶

點擊 Chrome 瀏覽器左上角的點點 -> 更多工具 -> 開發者工具。

HTTP 通訊協定可以向不同 IP 位置的主機請求檔案。

HTTP Cont.¶

DNS 協定可以將網址(如www.google.com)轉換成 IP 位置。

Frontend? Backend?¶

Frontend/Backend¶

前端負責設計網頁界面、後端負責設計應用程式的邏輯。

Where is Python?¶

後端框架 Django 和 Flask 即是以 Python 編寫而成。

由於網頁瀏覽器的標準化,前端所使用的程式語言以 Javascript 為大宗。

Practice¶

找到藏在 https://tw-csie-sprout.github.io/py2023/speaker 中的祕密。

格式為: SPROUT{P0_XXXXXXXXXX}

Flack Introduction¶

Before we start¶

  1. pip install flask
  2. 準備一個獨立的資料夾裝所有檔案

Hello Sprout¶

link

Initialize¶

from flask import Flask
app = Flask(__name__)

Define route and view¶

@app.route("/")
def hello_sprout():
    return "Hello, Sprout!"

Run the app!¶

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

Practice¶

  1. 讓伺服器顯示自己的名字。
  2. 執行的時候使用app.run(host="0.0.0.0")。
  3. 試試看連不連得到左鄰右舍的伺服器。

HTML: HyperText Markup Language¶

Structure on my website!¶

想要網站上有標題、段落、圖片等,和 Word 一樣。

實際上 Microsoft Word / Google Docs 背後也是使用某種 Markup Language

以資芽網站為例:

HTML Elements¶

Simple Introduction¶

  1. <h1>Title</h1> n=1...5
  2. <p>Text</p>
  3. Table
<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
</table>

Simple Introduction Cont.¶

  1. <img src="/link/to/image.extension">
  2. <h1 style="color:red;">Red Title!</h1>

For more information, read: link

Practice¶

  1. 讓伺服器回傳自己的名字。
  2. 回傳最高級的標題,字體顏色為藍色。
  3. 在 giphy 找一張自己喜歡的動圖,點選 Embed 後將動圖嵌入到自己的網頁裡。

Flask Cont.¶

Route & View¶

網站上可以有很多頁面(view),可以通過不同路由(route)存取

Hello Maowman!¶

https://github.com/namwoam/sprout-material/blob/main/py2024-taipei-flask/src/example-2.py

Different Routes¶

@app.route("/dancing")
def dancing():
    return '<div class="tenor-gif-embed" data-postid="8301814479124957525" data-share-method="host" data-aspect-ratio="0.618834" data-width="100%"><a href="https://tenor.com/view/catdancing-cat-dance-cat-busting-it-down-cat-dance-girlfriend-tiktokcatdance-gif-8301814479124957525">Catdancing Cat Dance GIF</a>from <a href="https://tenor.com/search/catdancing-gifs">Catdancing GIFs</a></div> <script type="text/javascript" async src="https://tenor.com/embed.js"></script>'


@app.route("/who")
def price():
    return "<p>我是超級貓貓男<\p>"

Dynamic Routes¶

@app.route("/student/<studentName>")
def hello_student(studentName):
    return f"<h1>Hello, {studentName}!</h1>"

HTTP parameters¶

password = "CHIPI-CHIPI-CHAPA-CHAPA"
@app.route("/secret")
def getSecret():
    try:
        inputPassword = request.args.get("password")
        if password != inputPassword:
            raise Exception("Password incorrect")
        return "<h1>超級貓貓男高中的時候體育跟美術都被當:P</h1>"
    except Exception as e:
        return f"403 Forbidden : {e}", 403

http://{app.host}:{app.port}/secret?password=CHIPI-CHIPI-CHAPA-CHAPA

Status Code¶

  • 200 -> OK
  • 403 -> Forbidden
  • 404 -> Not Found
  • 500 -> Internal Server Error

更多狀態碼: link

Redirect¶

@app.route("/chipi")
def rickroll():
    return redirect("https://www.youtube.com/watch?v=wh9QLjk3M2k")

Practice¶

  1. 建立一個新的 route traffic。
  2. 顯示所有頁面被訪問的次數。

Template Response¶

Before we start¶

  1. 建立名為templates的資料夾放模板檔案(一字不差!)。

Hello Maowman! 2.0¶

https://github.com/namwoam/sprout-material/blob/main/py2024-taipei-flask/src/example-3.py

Template¶

from flask import render_template
@app.route("/")
def index():
    return render_template("index.html")

新增檔案 /templates/index.html

<h1>Hello Sprout!</h1>

Template 有什麼好處?¶

把程式邏輯跟視覺設計分開

功能的抽象化有助於管理跟分工

Variables¶

@app.route("/ship")
def ship():
    return render_template("ship.html" , system = "太陽系" , planet = "地球")

新增檔案 /templates/ship.html

<p>超級貓貓號現在停留在 {{system}}星系 - {{planet}}星球</p>

Condition¶

@app.route("/board")
def board():
    age = 0
    try:
        age = int( request.args.get("age"))
    except Exception as e:
        print(e)
    return render_template("board.html" , age = age )

新增檔案 /templates/board.html

<h1>你的年齡是:{{ age }}</h1>
{% if age > 18 %}
<h1>歡迎搭乘超級貓貓號。</h1>
{% else %}
<h1>年齡太小了,請明年再試看看!</h1>
{% endif %}

Loop¶

@app.route("/passenger")
def passenger():
    passenger_data = {"超級貓貓男":"1A" , "豬大哥":"1B" , "勒布朗-詹姆斯":"2A"}
    return render_template("passenger.html" , data = passenger_data )

新增檔案 /templates/passenger.html

<h1>乘客名單</h1>
{%for passenger , seat in cart.items() %}
<p>{{passenger}} 坐在 {{seat}} </p>
{% endfor %}

Practice¶

超級貓貓號想要在太陽系裡面停留一陣子,如果該地的地心引力比地球大,他就得在上面穿超級貓貓鞋。

請你寫一個頁面讓他知道在哪些星球上面要穿超級貓貓鞋,地心引力的資訊可以參考:link

Deployment¶

我們想要讓全世界的人都能使用我們的工具!

pythonanywhere¶

https://www.pythonanywhere.com/

Remarks¶

Source¶

  1. Computer Networking: A Top-Down Approach Copyright © 2022 Pearson Education Ltd
  2. Amazon Web Service Official Website
  3. GeeksforGeeks
  4. Statistics and data

Additional Information¶

  1. SQL資料庫 https://flask-sqlalchemy.palletsprojects.com/en/2.x/

  2. Email發送 https://pythonhosted.org/Flask-Mail/

  3. 一堆酷東西 https://www.fullstackpython.com/flask-extensions-plug-ins-related-libraries.html

  4. 編教材時用的工具書 https://www.books.com.tw/products/0010793455?sloc=main

The sky is the limit!!¶

希望大家今天都有學到有趣的東西!