Phani varma
Phani varma

Reputation: 381

no module named http.server

here is my web server class :

import http.server  
import socketserver

class WebHandler(http.server.BaseHTTPRequestHandler):

    def parse_POST(self):
        ctype, pdict = cgi.parse_header(self.headers['content-type'])
        if ctype == 'multipart/form-data':
            postvars = cgi.parse_multipart(self.rfile, pdict)
        elif ctype == 'application/x-www-form-urlencoded':
            length = int(self.headers['content-length'])
            postvars = urllib.parse.parse_qs(self.rfile.read(length),
                                             keep_blank_values=1)
        else:
            postvars = {}
        return postvars

    def do_POST(self):
        postvars = self.parse_POST()

        print(postvars)

        # reply with JSON
        self.send_response(200)
        self.send_header("Content-type", "application/json")
        self.send_header("Access-Control-Allow-Origin","*");
        self.send_header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
        self.send_header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        self.end_headers()
        json_response = json.dumps({'test': 42})
        self.wfile.write(bytes(json_response, "utf-8"))

when i run server i got "name 'http' is not defined" after import http.server then i got this "no module named http.server"

Upvotes: 36

Views: 86351

Answers (3)

Sami
Sami

Reputation: 8419

In python earlier than v3 you need to run http server as

python -m SimpleHTTPServer 8012 
#(8069=portnumber on which your python server is configured)

And for python3

python3 -m http.server 7034 #(any free port number)

Upvotes: 53

sarakainimame
sarakainimame

Reputation: 1

like @Sami said: you need earlier versions of python (2.7) - if you're running on Linux you need to "apt install python-minimal" - when launching the server "python2 -m SimpleHTTPServer 8082" [or any other port]. By default, python will launch it on 0.0.0.0 which actually is 127.0.0.1:8082 [or your specific port]

Happy hacking

PS when you have 2 versions of python, you need to specify every time you run a command, "python2" or "python3"

Upvotes: 0

MattDMo
MattDMo

Reputation: 102902

http.server only exists in Python 3. In Python 2, you should use the BaseHTTPServer module:

from BaseHTTPServer import BaseHTTPRequestHandler

should work just fine.

Upvotes: 31

Related Questions