读取文件并返回给浏览器 | 手把手教你入门Python之一百一十五

简介: 本节介绍了文件的读取,并返回结果到浏览器。

上一篇:WSGI不同路径返回不同内容| 手把手教你入门Python之一百一十四
下一篇:方法的封装 | 手把手教你入门Python之一百一十六

本文来自于千锋教育在阿里云开发者社区学习中心上线课程《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()

配套视频

相关文章
|
4天前
|
JavaScript
浏览器插件crx文件--JS混淆与解密
浏览器插件crx文件--JS混淆与解密
11 0
|
1天前
|
JSON JavaScript 数据格式
python遍历目录文件_结合vue获取所有的html文件并且展示
python遍历目录文件_结合vue获取所有的html文件并且展示
4 0
|
2天前
|
Python
Python从入门到精通:深入学习面向对象编程——2.1.2继承、封装和多态的概念
Python从入门到精通:深入学习面向对象编程——2.1.2继承、封装和多态的概念
|
2天前
|
存储 索引 Python
Python从入门到精通——1.3.1练习编写简单程序
Python从入门到精通——1.3.1练习编写简单程序
|
2天前
|
开发框架 前端开发 数据库
Python从入门到精通:3.3.2 深入学习Python库和框架:Web开发框架的探索与实践
Python从入门到精通:3.3.2 深入学习Python库和框架:Web开发框架的探索与实践
|
2天前
|
数据采集 数据可视化 数据处理
Python从入门到精通的文章3.3.1 深入学习Python库和框架:数据处理与可视化的利器
Python从入门到精通的文章3.3.1 深入学习Python库和框架:数据处理与可视化的利器
|
2天前
|
Java 数据库连接 数据处理
Python从入门到精通:3.1.2多线程与多进程编程
Python从入门到精通:3.1.2多线程与多进程编程
|
2天前
|
存储 网络协议 关系型数据库
Python从入门到精通:2.3.2数据库操作与网络编程——学习socket编程,实现简单的TCP/UDP通信
Python从入门到精通:2.3.2数据库操作与网络编程——学习socket编程,实现简单的TCP/UDP通信
|
8天前
|
存储 Python
用Python实现批量下载文件——代理ip排除万难
用Python实现批量下载文件——代理ip排除万难
|
8天前
|
机器学习/深度学习 数据可视化 数据挖掘
《Python 简易速速上手小册》第9章:数据科学和机器学习入门(2024 最新版)
《Python 简易速速上手小册》第9章:数据科学和机器学习入门(2024 最新版)
19 1