码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • python http模块快速搭建“简单”服务器笔记


    极简运行

    python -m http.sever
    
    • 1

    或

    # test.py
    import http.server
    import socketserver
    
    PORT = 8000
    
    Handler = http.server.SimpleHTTPRequestHandler
    
    with socketserver.TCPServer(("", PORT), Handler) as httpd:
        print("serving at port", PORT)
        httpd.serve_forever()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在这里插入图片描述
    在这里插入图片描述

    CGI-Bin

    • 做了以上的启动之后就得到了一个文件服务器。

    • 我主要复制教你如何用几行Python代码编写出一个简易Web服务器的代码。在当前目录下创建C:\Users\admin\Desktop\http\cgi-bin文件夹,CGI-bin 是一个用于存放脚本的文件夹,这些脚本将与 Web 浏览器交互以提供网页或网站的功能。通用网关接口 (CGI) 是一种资源,用于在 Web 设计中使用脚本。当脚本从服务器发送到 Web 浏览器时,通常在 url 中引用 CGI-bin。,用于实现类似jsp的功能。

    • 但是大多数的博客都比较推荐使用此模块搭建简单的测试项目。

    启动服务

    import os
    from http.server import HTTPServer, CGIHTTPRequestHandler
    webdir="C:\\Users\\admin\\Desktop\\http"
    os.chdir(webdir)
    HTTPServer(("127.0.0.1", 8080), CGIHTTPRequestHandler).serve_forever()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    import pickle
    import os
    
    student_keys = ("name", "gender", "age", "score")
    
    if os.path.exists("student.data"):
        with open("student.data", "rb") as file:
            student = pickle.load(file)
        student = student or {}
    else:
        student = {}
    
    if not student:
        student = dict.fromkeys(student_keys, "")
    
    header = "Content-Type: text/html\n"
    content = """
    <html>
      <body>
        <form action="/cgi-bin/update.py" method="POST">
            <table>
                <tr>
                    <td>name: </td>
                    <td><input name="name" value="{name}"/></td>
                </tr>
                <tr>
                    <td>gender:</td>
                    <td><input name="gender" value="{gender}"/></td>
                <tr>
                <tr>
                    <td>age: </td>
                    <td><input name="age" value="{age}"/></td>
                </tr>
                <tr>
                    <td>score: </td>
                    <td><input name="score" value="{score}"/></td>
                </tr>
                <tr>
                    <td style="padding-top: 10px" align="center" colspan="2">
                        <button type="submit">Submit</button>
                    </td>
                </tr>
            </table>
        </form>
      </body>
    </html>
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    import os
    import cgi
    import pickle
    
    student_keys = ("name", "gender", "age", "score")
    if os.path.exists("student.data"):
        with open("student.data", "rb") as file:
            student = pickle.load(file)
        student = student or {}
    else:
        student = {} 
    
    if not student:
        student = dict.fromkeys(student_keys, "")
    
    form = cgi.FieldStorage()
    for key in student_keys:
        if key in form and form[key].value:
            student[key] = form[key].value
    
    with open("student.data", "wb") as file:
        pickle.dump(student, file)
    
    header = "Content-Type: text/html\n"
    content = """
    <html>
    <body>
    <h1>update successfully, will skip to display page: <span id="count_down">3</span></h1>
    <script>
       var count = 3 
       timer_id = setInterval(function(){
           count = count -1
           if(count == 0) {
               clearInterval(timer_id)
               location.href="/cgi-bin/student.py"
           } else {
               document.getElementById("count_down").innerHTML = "" + count
           }
       },1000)
    </script>
    </body>
    </html>
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    在这里插入图片描述
    你可能应该访问“localhost:81/cgi-bin/index.py”。因为“localhost:81/cgi-bin/”是一个目录,不是一个python script。

    使用体验

    • 当在文件服务器的模式下,可以直接访问并渲染html文件,但是当我使用以下代码时,浏览器提示var myChart = echarts.init(document.getElementById('main'));无法找到echarts对象。
    import os
    import cgi
    import pickle
    
    # student_keys = ("name", "gender", "age", "score")
    # if os.path.exists("student.data"):
    #     with open("student.data", "rb") as file:
    #         student = pickle.load(file)
    #     student = student or {}
    # else:
    #     student = {}
    #
    # if not student:
    #     student = dict.fromkeys(student_keys, "")
    
    form = cgi.FieldStorage()
    # for key in student_keys:
    #     if key in form and form[key].value:
    #         student[key] = form[key].value
    
    # with open("student.data", "wb") as file:
    #     pickle.dump(student, file)
    
    header = "Content-Type: text/html\n"
    content = """
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>bar</title>
        <!-- 引入 echarts.js -->
        <script src="echarts.min.js"></script>
    </head>
    <body>
    <!-- 为ECharts准备一个具备大小(宽高)的Dom -->
    <div id="main" style="width: 900px;height:600px;"></div>
    
    <script type="text/javascript">
    // 基于准备好的dom,初始化echarts实例
    
    var myChart = echarts.init(document.getElementById('main'));
    
    // 指定图表的配置项和数据
    var option = {
        // 标题
        title: {
            text: 'ECharts 入门示例'
        },
        // 工具箱
        toolbox: {
            show: true,
            feature: {
                saveAsImage: {
                    show: true
                }
            }
        },
        // 图例
        legend: {
            data: ['销量']
        },
        // x轴
        xAxis: {
            data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
        },
        yAxis: {},
        // 数据
        series: [{
            name: '销量',
            type: 'bar',
            data: [5, 20, 36, 10, 10, 20]
        }]
    };
    
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
    </script>
    </body>
    </html>
    """
    print(header + content)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81

    参考与更多

    https://docs.python.org/3/library/http.server.html
    用 Python 的 SimpleHTTPServer 模組快速建立一個臨時網頁伺服器(Web Server)
    使用Python的http.server实现一个简易的Web Api对外提供HanLP拼音转换服务
    simple http server for upload and download

  • 相关阅读:
    ANR 触发、监控、分析 一网打尽
    selenium 自动化测试——元素定位
    C语言例题(递归、二分查找、冒泡排序)
    TypeScript(5)类、继承、多态
    飞腾全国产化加固计算机
    一、特征工程
    深入剖析阻塞式socket的timeout
    储能:储能大会“共建储能生态链,共创储能新发展”
    万字长文!对比分析了多款存储方案,KeeWiDB最终选择自己来
    实习项目遇到的bug
  • 原文地址:https://blog.csdn.net/ResumeProject/article/details/128163316
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号