python - 创建 Python Web 服务器 - 布局和设置

标签 python html http http-headers webserver

我是否以正确的方式处理这个问题?我以前从未做过这样的事情,所以我不能 100% 确定我在做什么。到目前为止,代码获取了 html 和 css 文件,并且工作正常,但图像无法加载,我是否必须为每种不同的文件类型创建一个新的“if”?或者我这样做是不是很愚蠢......这就是我所拥有的:

import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import os
import mimetypes

#import pri
port = 888
host = "0.0.0.0"

class MyHandler(BaseHTTPRequestHandler):

def do_GET(self):
    try:
        #RequestedURL = self.path
        mimeType = mimetypes.guess_type(self.path)[0]
        fileType = mimetypes.guess_extension(mimeType)
        infoList = [mimeType, fileType]

        if infoList[1] != ".py":
            self.send_response(200)
            self.send_header('Content-type', mimeType)
            self.end_headers()
            f = open(curdir + sep + self.path, "rb")
            self.wfile.write(f.read())
            f.close()
            return

        if fileType == ".py":
            pythonFilename = self.path.lstrip("/")
            self.send_response(200)
            self.send_header('Content-type',    'text/html')
            self.end_headers()
            pyname = pythonFilename.replace("/", ".")[:-3]
            print pythonFilename
            print pyname
            temp1 = pyname.split(".")
            temp2 = temp1[-1]
            print temp2
            module = __import__(root.index)
            self.wfile.write(module.root.index.do_work())
            #module = __import__("test.index")
            #self.wfile.write( module.index.do_work())
            return

        return

    except IOError:
        self.send_error(404,'File Not Found: %s' % self.path)


def do_POST(self):
    global rootnode
    try:
        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
        if ctype == 'multipart/form-data':
            query=cgi.parse_multipart(self.rfile, pdict)
        self.send_response(301)

        self.end_headers()
        upfilecontent = query.get('upfile')
        print "filecontent", upfilecontent[0]
        self.wfile.write("<HTML>POST OK.<BR><BR>");
        self.wfile.write(upfilecontent[0]);

    except :
        pass

def main():
try:
    server = HTTPServer((host, port), MyHandler)
    print 'started httpserver:'
    print  ("Host: "  + (host))
    print  ("Port: "  + str(port))

    server.serve_forever()
except KeyboardInterrupt:
    print '^C received, shutting down server'
    server.socket.close()

if __name__ == '__main__':
main()

html 和 css 可以工作,但 png 图像无法加载

最佳答案

尽管你的假设非常多余,但你的做法是正确的。我建议您重构代码以使用循环和字典检查类型:

mime = {"html":"text/html", "css":"text/css", "png":"image/png"}
if RequestedFileType in mime.keys():
    self.send_response(200)
    self.send_header('Content-type', mime[RequestedFileType])
    self.end_headers()
    print RequestedFileType
    f = open(curdir + sep + self.path)             
    self.wfile.write(f.read())              
    f.close()
    return

此外,您还将二进制文件作为文本发送。使用 open(curdir + sep + self.path, "b") 而不是 open(curdir + sep + self.path)

Gergely 来自 toptal.com

关于python - 创建 Python Web 服务器 - 布局和设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8051506/

相关文章:

python - 从二进制掩码裁剪图像

python - 任何关于 psutil 隐藏导入的 pyinstaller 详细示例?

python - 类中的列表未转储到文件

html - diff 到 html (diff2html) 程序

jquery - 如何获得第一个字符为 $ 的 div

HTTP 缓存测试

asp.net-mvc - 当页面依赖于 session 时,处理永久链接的正确方法是什么?

python - 在 Python 中更简洁地表示规则 (if-else)

php - 单击按钮时使用 ID 进行 SQL 查询

android - 仅通过WiFi接口(interface)发送POST请求