Python代码没有执行

时间:2012-02-22 09:55:15

标签: python http-post

我有以下代码,它是从命令行执行的:

import cgi,time,os,json,sys,zipfile,urllib2
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from time import strftime
from poster.encode import multipart_encode, MultipartParam
from poster.streaminghttp import register_openers

class MyHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        try:
            if self.path.endswith("/"):
                self.send_response(200)
                self.send_header('Content-type',    'text/html')
                self.end_headers()
                self.wfile.write("<HTML> GET OK.<BR>")
                return  
            return

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


    def do_POST(self):
        global rootnode
        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(200)
        self.send_header('Content-type',    'text/html')
        self.end_headers()
        file = query.get('file')

        zfile = "C:\Users\VM1\Desktop\data.zip"
        extract_path = "C:\Users\VM1\Desktop\data\\"

        f = open(zfile, "wb")
        f.write(file[0])
        f.close()
        self.wfile.write("POST OK. File received from VM Host")
        print("File received from VM Host.")
        print("Unzipping zip file")
        unzip = zipfile.ZipFile(zfile)
        unzip.extractall(extract_path)
        print "Files extracted to " + extract_path
        scan_path = '"C:\Program Files (x86)\AVG\AVG2012\\avgscana.exe" /repok /report=C:\Users\VM1\Desktop\\avg_scan_results.txt /scan=' + extract_path
        os.system('"%s"' % scan_path)
        self.write_json_report()
        self.upload_json_report()
        return

    def write_json_report(self):
        scan_results = open("avg_scan_results.txt", "r")
        saved = sys.stdout
        f = file('avg_report.json', 'wb')
        sys.stdout = f
        dict2 = {}
        for line in scan_results:
            if ".jpg" in line:
                result = line.split('\\')
                result_split = result[5].split(' ')
                filename = result_split[0]
                raw_status = result_split[3]
                if "OK" in raw_status:
                    status = "Okay"
                    status_code = "0"
                elif "Virus identified" in raw_status:
                    status = raw_status
                    status_code = "1"
                dict2[filename] = {'FileName': filename, 'DateTime': strftime("%Y-%m-%d %H:%M:%S"), 'statusCode': status_code, 'Description': status}
        print json.dumps(dict2)
        sys.stdout = saved
        f.close()
        print ""
        print "JSON report written"
        json_zip = zipfile.ZipFile("avg_report.zip", "w")
        try:
            json_zip.write('avg_report.json')
        finally:
            json_zip.close()
        return

    def upload_json_report(self):
        av_name = "AVG Free 2012"
        av_version = ""
        scan_results = open("avg_scan_results.txt", "r")
        for line in scan_results:
            if "Program version" in line:
                version_split = line.split(', ')
                program_version_full = version_split[0]
                program_version_split = program_version_full.split(' ')
                av_version = program_version_split[2]
        register_openers()
        datagen, headers = multipart_encode({"av_name": av_name, "av_version": av_version, "filename": "avg_report.zip", "content": open("avg_report.zip", "rb")})
        request = urllib2.Request("http://" + self.client_address[0] + ":8080/", datagen, headers)
        print "Uploading JSON report"
        print urllib2.urlopen(request).read()
        return

def main():
    try:
        server = HTTPServer(('', 8080), MyHandler)
        print 'Server started..'
        server.serve_forever()
    except KeyboardInterrupt:
        print 'KeyboardInterrupt received, shutting down server'
        server.socket.close()

if __name__ == '__main__':
    main()

除了upload_json_report()之外,其他功能都运行良好。字符串Uploading JSON report显示但后面的行不执行。我正在侦听请求的服务器没有收到任何内容。这里的代码有什么问题吗?如果是,问题是什么?如何解决?非常感谢提前。

修改 我创建了一个单独的客户端,其中包含以下方法:

register_openers()
datagen, headers = multipart_encode({"av_name": av_name, "av_version": av_version, "filename": "avg_report.zip", "content": open("avg_report.zip", "rb")})
request = urllib2.Request("http://" + self.client_address[0] + ":8080/", datagen, headers)
print "Uploading JSON report"
print urllib2.urlopen(request).read()

这很有用。我很困惑为什么相同的代码行无法在函数中工作。

4 个答案:

答案 0 :(得分:2)

BaseHTTPRequestHandler维护一个单线程(和单进程)服务器。这意味着每个请求必须在执行另一个请求之前完成执行。

upload_json_report方法中调用do_POST函数。在它运行时,您的服务器无法处理任何其他内容。但接下来就行了:

    print urllib2.urlopen(request).read()

您实际上是在尝试将.zip文件上传到同一个端口8080。因此,upload_json_report正在等待do_POST完成,do_POST等待upload_json_report完成,所以当然他们永远不会停止等待。

顺便提一下,这解释了为什么它在您的服务器上工作(我假设它是多线程的,但您需要提供更多详细信息),为什么当您使用单独执行它时它可以工作客户(它不等待自己完成)。

答案 1 :(得分:1)

我建议调试代码。为此,我将删除print语句,在pdb.set_trace方法调用之前添加urllib2.urlopen并运行脚本。一旦调试器接管,我会检查url是你期望的那个,尝试执行下一行并检查urllib2.urlopen返回的值是什么(响应代码,文本等)。这应该为您提供有关正在发生的事情的足够信息,并希望让您知道如何解决问题。

答案 2 :(得分:0)

urllib2.urlopen(...)返回一个文件描述符对象,您必须阅读该对象才能打印出响应。基本上,为了查看从服务器获取的响应,您需要执行print urllib2.urlopen(request).read()

答案 3 :(得分:0)

我的建议是在“urllib2.urlopen”行周围添加“try”“except”,以查看是否有任何异常。

try:
    request = urllib2.Request("http://" + self.client_address[0] + ":8080/", datagen, headers)
except Exception, e:
    print e

使用打印的异常信息,您可能会有一些线索。