【Python】WSGI简单Web服务器,处理GET和POST请求

本文介绍了一个基于Python WSGI的简易Web服务器实现,该服务器能够处理GET和POST请求,并根据请求路径提供静态资源或定制化的HTML响应。通过具体代码示例展示了如何使用Python进行Web开发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【Python】WSGI简单Web服务器,处理GET和POST请求

Python服务器代码

"""
Small wsgiref based web server. Takes a path to serve from and an
optional port number (defaults to 8000), then tries to serve files.
MIME types are guessed from the file names, 404 errors are raised
if the file is not found.
"""
import mimetypes
import os
import sys
from wsgiref import simple_server, util
from urllib.parse import parse_qs


def app(environ, respond):
    get_query_ =environ['QUERY_STRING']
    post_query_=environ["wsgi.input"].read(int(e)).decode("utf-8", 'ignore') if (e:=environ.get("CONTENT_LENGTH")) else None
    get_query =parse_qs(get_query_)
    post_query=parse_qs(post_query_)

    print("REQUEST_METHOD: "+environ['REQUEST_METHOD'])
    print("GET : ",(get_query))
    print("POST: ",(post_query))

    if(environ["PATH_INFO"].startswith(r"/post")):
        respond("200 OK", [("Content-Type", "text/html; charset=utf-8")])
        message=("Welcome, "+e[0]+" !") if (e:=post_query.get('username')) else "Welcome ! "
        html = '''<!DOCTYPE HTML>
        <html>
            <head>
                <title>Post page</title>  
            </head>
            <body>
                <h1>  %s  </h1>
                Post Data:<br> %s  <br />
                Path:<br> %s  <br />
            </body>
        </html>''' %( message, str(post_query), environ["PATH_INFO"])
        return [html.encode("utf-8")]
    else:
        # Get the file name and MIME type
        fn = os.path.join(path,"res", environ["PATH_INFO"][1:])
        if "." not in fn.split(os.path.sep)[-1]:
            fn = os.path.join(fn, "index.html")
        mime_type = mimetypes.guess_type(fn)[0]


        # Return 200 OK if file exists, otherwise 404 Not Found
        if os.path.exists(fn):
            respond("200 OK", [("Content-Type", mime_type)])
            return util.FileWrapper(open(fn, "rb"))
        else:
            respond("404 Not Found", [("Content-Type", "text/plain")])
            return [b"not found"]


if __name__ == "__main__":
    # Get the path and port from command-line arguments
    path = sys.argv[1] if len(sys.argv) > 1 else os.getcwd()
    port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000

    # Make and start the server until control-c
    httpd = simple_server.make_server("", port, app)
    print(f"Serving {path} on port {port}, control-C to stop")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("Shutting down.")
        httpd.server_close()

静态HTML文件代码

<!DOCTYPE HTML>
<html>

<head>
    <meta charset="utf-8">
    <title>⭐⭐⭐⭐⭐</title>
</head>

<body>
    <form action="post_page" method="post">
        username: <input type="text" name="username" /><br />
        password: <input type="password" name="password" /><br />
        文本框: <input type="textarea" name="textarea" /><br />
        <input type="submit" value="POST" />
    </form>
    <a href="logo.gif" download="mylogo.gif">download</a>
</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乌托邦的乌班图

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值