读取文件并返回给浏览器 | 手把手教你入门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()

配套视频

相关文章
|
13天前
|
Python
【python】python跨文件使用全局变量
【python】python跨文件使用全局变量
|
20天前
|
Web App开发 Python
在ModelScope中,你可以使用Python的浏览器自动化库
在ModelScope中,你可以使用Python的浏览器自动化库
15 2
|
22天前
|
监控 数据处理 索引
使用Python批量实现文件夹下所有Excel文件的第二张表合并
使用Python和pandas批量合并文件夹中所有Excel文件的第二张表,通过os库遍历文件,pandas的read_excel读取表,concat函数合并数据。主要步骤包括:1) 遍历获取Excel文件,2) 读取第二张表,3) 合并所有表格,最后将结果保存为新的Excel文件。注意文件路径、表格结构一致性及异常处理。可扩展为动态指定合并表、优化性能、日志记录等功能。适合数据处理初学者提升自动化处理技能。
19 1
|
5天前
|
JavaScript 前端开发 API
游戏开发入门:Python后端与Vue前端的协同工作方式
【4月更文挑战第11天】使用Python后端(Flask或Django)和Vue.js前端开发游戏变得流行,能提高开发效率和可维护性。本文指导如何构建这样的项目,包括设置环境、创建虚拟环境、搭建后端API及前端Vue组件,强调前后端协作和API接口的重要性。这种架构促进团队合作,提升代码质量和游戏体验。
|
7天前
|
机器学习/深度学习 人工智能 算法
机器学习基础:使用Python和Scikit-learn入门
【4月更文挑战第9天】本文介绍了使用Python和Scikit-learn进行机器学习的基础知识和入门实践。首先,简述了机器学习的基本概念和类型。接着,展示了如何安装Python和Scikit-learn,加载与处理数据,选择模型进行训练,以及评估模型性能。通过本文,读者可了解机器学习入门步骤,并借助Python和Scikit-learn开始实践。
|
8天前
|
机器学习/深度学习 数据可视化 数据挖掘
利用Python进行数据分析与可视化:从入门到精通
本文将介绍如何使用Python语言进行数据分析与可视化,从基础概念到高级技巧一应俱全。通过学习本文,读者将掌握Python在数据处理、分析和可视化方面的核心技能,为实际项目应用打下坚实基础。
|
13天前
|
C++ Python
【C++/Python】C++调用python文件
【C++/Python】C++调用python文件
|
14天前
|
JSON 数据处理 数据格式
Python中的文件读写操作详解
【4月更文挑战第2天】在Python中,文件读写操作是数据处理和程序开发的重要部分。通过文件,我们可以将信息持久化地保存在磁盘上,并在需要时读取和使用这些数据。Python提供了丰富的内置函数和模块,使得文件读写变得简单而高效。本文将详细介绍Python中文件读写的基本操作和常用方法。
|
25天前
|
存储 算法 数据挖掘
【Python 基础教程 25】全面入门指南:深度解析Python3的命名空间,作用域及变量使用教程
【Python 基础教程 25】全面入门指南:深度解析Python3的命名空间,作用域及变量使用教程
50 0
|
25天前
|
存储 机器学习/深度学习 数据安全/隐私保护
【Python 基础教程 24】全面入门Python面向对象编程:深度探索与实战教程
【Python 基础教程 24】全面入门Python面向对象编程:深度探索与实战教程
76 0

热门文章

最新文章