Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7572781
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T16:00:46+00:00 2026-05-30T16:00:46+00:00

I have the following code which is executed from the command line: import cgi,time,os,json,sys,zipfile,urllib2

  • 0

I have the following code which is executed from the command line:

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()

The rest of the functions worked fine except for upload_json_report(). The string Uploading JSON report shows but the line after doesn’t execute. My server which is listening for the request does not receive anything. Is there anything wrong with the code here? If yes, what is the problem and how do I solve it? Many thanks in advance.

EDIT:
I have created a seperate client with the following lines from the method:

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()

This worked. I’m confused as to why the same lines of codes could not work in the function.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T16:00:47+00:00Added an answer on May 30, 2026 at 4:00 pm

    BaseHTTPRequestHandler maintains a single-threaded (and single-process) server. This means that each request has to finish executing before another request can be executed.

    The upload_json_report function is called from within the do_POST method. While it is running, your server can’t handle anything else. But then at the line:

        print urllib2.urlopen(request).read()
    

    You are actually trying to upload the .zip file to the same port, 8080. Thus, upload_json_report is waiting for do_POST to finish, and do_POST is waiting for upload_json_report to finish, so of course they will never stop waiting.

    Incidentally, this explains why it was working on your server (I assume it was multithreaded, though you’d need to provide more details), and why it works when you perform it using a separate client (it’s not waiting for itself to finish).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to use opengl in C#. I have following code which fails with
I have following Code Block Which I tried to optimize in the Optimized section
I have the following code which works just fine when the method is POST,
I have the following code which works fine. However, I only want to return
I have the following code which should put programs startable in Bash. if [
I have the following code which reads in the follow file, append a \r\n
I have the following code which re-uses a CookieContainer which logs in on the
I have the following code which I stripped out of any non-essential lines to
I have the following code which ends up forever reading '/proc/cpuinfo' as it keeps
I have the following code which lets the user plot two points on a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.