如何从WSGI python访问单独的html文件

时间:2019-02-28 17:33:02

标签: python sockets web server wsgi

要使用WSGI创建一个简单的Web服务器,并在我通过浏览器中的“发生服务器错误。请与管理员联系”时运行此代码。

我的代码

main.py

import os
from wsgiref.simple_server import make_server


def application(environ, start_response):
    # Mimetype
    ctype = 'text/html'

    # Directory
    dir = environ["SCRIPT_FILENAME"][:environ["SCRIPT_FILENAME"].rindex("/")]
    # Get File Contents
    file_contents = b""
    with open(dir+"/main.html", "rb") as file:
        file_contents = file.read()

    # Add Dynamic Content
    response_body = b"This is a header!".join(
        b"".join(
            file_contents.split(b"%(HEAD)")
        ).split(b"%(HEADING)")
    )

    # Heading
    status = '200 OK'
    response_headers = [
        ('Content-Type', ctype), ('Content-Length', str(len(response_body)))
    ]

    # Send Response
    start_response(status, response_headers)
    return [response_body.encode('utf-8')]


httpd = make_server('localhost', 8080, application)
# Now it is serve_forever() in instead of handle_request()
httpd.serve_forever()

main.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>

<h1>Hello, Python WSGI Application</h1>

</body>
</html>

文件main.py和main.html都包含在“ app”目录的名称中。我无法检测到实际问题在这里发生了什么。

谢谢。

0 个答案:

没有答案