创建Python Web服务器 - 布局和设置 [英] Creating a Python webserver - layout and setup

查看:114
本文介绍了创建Python Web服务器 - 布局和设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  import string,cgi,time 
来自os import curdir,sep
来自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]

如果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()
返回

if fileType ==。py:
pyth onFilename = 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())
返回

返回

除了IOError:
self.send_error(404,'找不到文件:%s'%self.path)


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

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

除外:
传递

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

server .serve_forever()
除了KeyboardInterrupt:
print'^ C received,关闭服务器'
server.socket.close()

if __name__ =='__ main__ ':
main()

html和css有效,但png图片无法加载

解决方案

尽管你的ifs非常冗余,但你已经走上了正轨。我建议你重构代码以使用循环和字典来检查类型:

  mime = {html:text / html,css:text / css,png:image / png} 
如果mime.keys()中的RequestedFileType:
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()
返回

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



来自toptal.com的Gergely


am I going about this in the correct way? Ive never done anything like this before, so im not 100% sure on what I am doing. The code so far gets html and css files and that works fine, but images wont load, and will I have to create a new "if" for every different file type? or am I doing this a silly way...here is what I have:

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 and css works, but png images do not load

解决方案

You are on the right track with it, though your ifs are very redundant. I suggest you refactor the code to check for type using a loop and a dict:

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

Also, you are sending binary files as text. Instead of open(curdir + sep + self.path) use open(curdir + sep + self.path, "b")

Gergely from toptal.com

这篇关于创建Python Web服务器 - 布局和设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆