開發與維運

讀取文件並返回給瀏覽器

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

讀取文件並返回給瀏覽器

hello.html:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .box {
            margin:0 auto;
        }
        div {
            width:1000px;
        }
        .top {
            height:80px;
            background-color:red;
            margin-bottom:10px;
        }
        .middle {
            height:400px;
        }
        .left {
            width:100px;
            height:100%;
            background-color:yellow;
            float:left;
            margin-right:10px;
        }
        .content {
            width:780px;
            height:100%;
            background-color:pink;
            float:left;
            margin-right:10px;
        }
        .right {
            width:100px;
            height:100%;
            background-color:blue;
            float:left;
        }
        .bottom {
            height:80px;
            background-color:lime;
            margin-top:10px;
        }

    </style>
</head>
<body>
<div class="box">
    <div class="top"></div>
    <div class="middle">
        <div class="left"></div>
        <div class="content"></div>
        <div class="right"></div>
    </div>
    <div class="bottom"></div>
</div>

</body>
</html>

info.html:

{username},歡迎回來,你今年{age}歲了,你的性別是{gender}

讀取文件:

import json
from wsgiref.simple_server import make_server


def demo_app(environ, start_response):
    path = environ['PATH_INFO']
    # print(environ.get('QUERY_STRING'))  # QUERY_STRING ==> 獲取到客戶端GET請求方式傳遞的參數
    # POST 請求數據的方式後面再說

    status_code = '200 OK'
    if path == '/':
        response = '歡迎來到我的首頁'
    elif path == '/test':
        response = json.dumps({'name': 'zhangsan', 'age': 18})
    elif path == '/demo':
        with open('pages/xxxx.txt', 'r', encoding='utf8') as file:
            response = file.read()
    elif path == '/hello':
        with open('pages/hello.html', 'r', encoding='utf8') as file:
            response = file.read()
    elif path == '/info':
        # 查詢數據庫,獲取到用戶名
        name = 'jack'
        with open('pages/info.html', 'r', encoding='utf8') as file:
            # '{username}, 歡迎回來'.format(username=name)
            # flask  django  模板,渲染引擎
            response = file.read().format(username=name, age=18, gender='男')
    else:
        status_code = '404 Not Found'
        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()

返回JSON字符串:
image.png
返回文件內容:
image.png
返回hello.html:
image.png
返回info.html:
image.png

HTTP服務器優化

import json
from wsgiref.simple_server import make_server


def load_file(file_name, **kwargs):
    try:
        with open('pages/' + file_name, 'r', encoding='utf8') as file:
            content = file.read()
            if kwargs:  # kwargs = {'username':'zhangsan','age':19,'gender':'male'}
                content = content.format(**kwargs)
                # {username},歡迎回來,你今年{age}歲了,你的性別是{gender}.format(**kwargs)
            return content
    except FileNotFoundError:
        print('文件未找到')


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

    status_code = '200 OK'
    if path == '/':
        response = '歡迎來到我的首頁'
    elif path == '/test':
        response = json.dumps({'name': 'zhangsan', 'age': 18})
    elif path == '/demo':
        response = load_file('xxxx.txt')
    elif path == '/hello':
        response = load_file('hello.html')
    elif path == '/info':
        response = load_file('info.html', username='zhangsan', age=19, gender='male')
    else:
        status_code = '404 Not Found'
        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 *