lilzz
Posts: 411
Joined: Sat Nov 30, 2013 5:27 pm

A simple Web Server in Python

Thu Mar 06, 2014 10:19 pm

Code: Select all

import string,cgi,time
    from os import curdir, sep
    from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
    
    class MyHandler(BaseHTTPRequestHandler):
    
        def do_GET(self):
            try:
                if self.path.endswith(".html"):
                    f = open(curdir + sep + self.path) 
                    self.send_response(200)
                    self.send_header('Content-type','text/html')
                    self.end_headers()
                    self.wfile.write(f.read())
                    f.close()
                    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(('', 80), MyHandler)
            print 'started httpserver...'
            server.serve_forever()
        except KeyboardInterrupt:
            print '^C received, shutting down server'
            server.socket.close()
    
    if __name__ == '__main__':
        main()
upload.html

Code: Select all

 <HTML><BODY>
    
    <form method='POST' enctype='multipart/form-data' action='http://127.0.0.1/'>
    
    File to upload: <input type=file name=upfile><br>
    
    <br>
    <input type=submit value=Press> to upload the file!
    </form>
    
    </BODY>
    </HTML>
Questions

1)In upload.html, the action is POST, so, POST will translate to do_POST on the server Python side?

2)Does Python server need some type of htaccess rule like the apache server?

3)what does it mean send_response(200)

4)what's self.wfile.write(f.read())?

User avatar
paddyg
Posts: 2541
Joined: Sat Jan 28, 2012 11:57 am
Location: UK

Re: A simple Web Server in Python

Fri Mar 07, 2014 4:19 pm

I've just set something up using flask which may be more sophistication than you need but seems to run quite fast enough on the pi and does a lot of stuff for you. You will find some answers here
1. I think BaseHTTPRequestHandler has to be wrapped in either a GET or POST handler, not sure how it knows to use do_get or do_post. Have you tried the code? Does it work?
2. I think you will have to write the behaviour as you want it, you could read a file called htaccess and obey its rules. (Don't know about this though)
3. writing to the BaseHTTPRequestHandler output stream code 200 (i.e. successful request) if unsuccessful it will send 404
4. writing to the BaseHTTPRequestHandler output stream from the file stream you just opened.

PS if you look at your snippet in the code windows above you will see why it is a REALLY bad idea to mix spaces and tabs unless you are absolutely sure that you will be the only person to ever see the code and that you will always be editing it on the same editor!
also https://groups.google.com/forum/?hl=en-GB&fromgroups=#!forum/pi3d

lilzz
Posts: 411
Joined: Sat Nov 30, 2013 5:27 pm

Re: A simple Web Server in Python

Fri Mar 07, 2014 4:38 pm

paddyg wrote:I've just set something up using flask which may be more sophistication than you need but seems to run quite fast enough on the pi and does a lot of stuff for you. You will find some answers here
1. I think BaseHTTPRequestHandler has to be wrapped in either a GET or POST handler, not sure how it knows to use do_get or do_post. Have you tried the code? Does it work?
2. I think you will have to write the behaviour as you want it, you could read a file called htaccess and obey its rules. (Don't know about this though)
3. writing to the BaseHTTPRequestHandler output stream code 200 (i.e. successful request) if unsuccessful it will send 404
4. writing to the BaseHTTPRequestHandler output stream from the file stream you just opened.

PS if you look at your snippet in the code windows above you will see why it is a REALLY bad idea to mix spaces and tabs unless you are absolutely sure that you will be the only person to ever see the code and that you will always be editing it on the same editor!

Thanks, from that reference page.
client_address
Contains a tuple of the form (host, port) referring to the client’s address.

I thought the host is referring to the Server, I don't get how it relate to the client?

User avatar
paddyg
Posts: 2541
Joined: Sat Jan 28, 2012 11:57 am
Location: UK

Re: A simple Web Server in Python

Fri Mar 07, 2014 5:53 pm

As I read the docs client_address is, as you say, (client ip, port) if you want those for the server they are held as instance variables server_name and server_port, but you already know them because you entered them when you created the server.

What I don't see is how the do_get and do_post are joined in. If your code works then I wouldn't worry about it. The documentation for BaseHTTPRequestHandler doesn't mention them, however there are methods do_GET() implemented via SimpleHTTPServer and do_POST() implemented via CGIHTTPServer
also https://groups.google.com/forum/?hl=en-GB&fromgroups=#!forum/pi3d

Return to “Python”