開發與維運

WSGI不同路徑返回不同內容

本文來自於千鋒教育在阿里雲開發者社區學習中心上線課程《Python入門2020最新大課》,主講人姜偉。

WSGI不同路徑返回不同內容

from wsgiref.simple_server import make_server


def demo_app(environ, start_response):
    path = environ['PATH_INFO']

    # 狀態碼: RESTFUL ==> 前後端分離
    # 2XX: 請求響應成功
    # 3XX: 重定向
    # 4XX: 客戶端的錯誤。  404 客戶端訪問了一個不存在的地址   405:請求方式不被允許
    # 5XX: 服務器的錯誤。
    status_code = '200 OK'  # 默認狀態碼是 200
    if path == '/':
        response = '歡迎來到我的首頁'
    elif path == '/test':
        response = '歡迎阿里到test頁面'
    elif path == '/demo':
        response = '歡迎來到demo頁面'
    else:
        status_code = '404 Not Found'  # 如果頁面沒有配置,返回404
        response = '頁面走丟了'

    start_response(status_code, [('Content-Type', 'text/html;charset=utf8')])
    return [response.encode('utf8')]


if __name__ == '__main__':
    httpd = make_server('', 8080, demo_app)
    sa = httpd.socket.getsockname()
    print("Serving HTTP on", sa[0], "port", sa[1], "...")
    httpd.serve_forever()

配套視頻

Leave a Reply

Your email address will not be published. Required fields are marked *