#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2011
    Posts
    8
    Rep Power
    0

    Accessing HTTP request.


    Scenario:

    I have an HTML page with a button that loads another HTML page from the same directory.

    How do I "listen in" to this process and figure out when the button is pressed in python?

    Once this button is pressed i'm going to access the serial port with python to send commands to a microcontroller. I already know how to do the serial port part. I just need to figure out when buttons or links or whatever I want is clicked.

    Maybe I can listen to HTTP request on the network. Filter out request only for the port my webpage is using and then look through the data to see if my button was pressed???

    Here is my HTML code. The button calls for ("FirstLink.html").
    Code:
    <html> 
    
    <input type="button" onclick="location.href='FirstLink.html';" style="color:black;font:arial bold;background-color:white;" value="Turn on LED1" /> 
    
    </html>
    Any suggestions? I'm not stuck with this html code or anything. It all can be changed if needed.

    Thanks
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,995
    Rep Power
    481
    Last edited by b49P23TIvg; August 15th, 2012 at 08:16 AM.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2011
    Posts
    8
    Rep Power
    0
    Thanks but is not what I'm looking for at all. I need to control the MCU through a web browser. I just thought that instead of using Microchips ethernet controler enc24j60 I could use a computer to do the websever part.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2012
    Posts
    39
    Rep Power
    3

    Simple web server


    Assuming you are happy for python to be your web server and you just want to run functions when pages are loaded the following should work

    Code:
    def index (env):
        return [ """<html>
    <input type="button" onclick="location.href='FirstLink.html';" style="color:black;font:arial bold;background-color:white;" value="Turn on LED1" />
    </html>""" ]
    
    def firstlink (env):
        # do something with serial port
        return [ "<html><p>Serial port return</p></html>" ]
    
    def test (env):
        tablevars = [ "<tr><td>%s</td><td>%s</td></tr>\n" % (x,env[x]) for x in env ]
        tablevars.insert(0,"<html>\n<head><title>Environment Variables</title></head>\n<body><table>\n")
        tablevars.append("</table></body>\n</html>")
        return tablevars
    
    # the files dictionary maps pages to functions
    filesdic = { '/': index, '/index.html': index, # index page
                 '/firstlink.html': firstlink,     # button page
                 '/test/env.html': test }          # page in test
    port = 8081
    
    def webapp(environ, start_response):
            filename = environ.get('PATH_INFO', '').lower()
    	if filename in filesdic:
                status = '200 OK' # HTTP Status
                headers = [('Content-type', 'text/html')] # HTTP Headers
                start_response(status, headers)
                return filesdic[filename](environ)
            else:
                status = '200 OK' # HTTP Status
                headers = [('Content-type', 'text/plain')] # HTTP Headers
                start_response(status, headers)
                return ["Page not found"]
    
    from wsgiref.simple_server import make_server
    srv = make_server('localhost',port,webapp)
    print "Webserver on port %s" % (port)
    try:
        srv.serve_forever()
    except KeyboardInterrupt:
        print "Server closed due to keyboard interrupt"
    I've edited the code to remove the currying of filesdic and sort the mess I made of getting the filename.
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2011
    Posts
    8
    Rep Power
    0
    Originally Posted by Quackajack
    Assuming you are happy for python to be your web server and you just want to run functions when pages are loaded the following should work

    Code:
    def index (env):
        return [ """<html>
    <input type="button" onclick="location.href='FirstLink.html';" style="color:black;font:arial bold;background-color:white;" value="Turn on LED1" />
    </html>""" ]
    
    def firstlink (env):
        # do something with serial port
        return [ "<html><p>Serial port return</p></html>" ]
    
    def test (env):
        tablevars = [ "<tr><td>%s</td><td>%s</td></tr>\n" % (x,env[x]) for x in env ]
        tablevars.insert(0,"<html>\n<head><title>Environment Variables</title></head>\n<body><table>\n")
        tablevars.append("</table></body>\n</html>")
        return tablevars
    
    # the files dictionary maps pages to functions
    files = { '': index, 'index.htm': index,
              'firstlink.htm': firstlink,
              'test.htm': test, 'env.htm': test, 'vars.htm': test }
    port = 8081
    
    def getapp ( filesdic ):
        def webapp(environ, start_response):
            pathpieces = environ.get('PATH_INFO', '').split('/')
    	filename = pathpieces[-1].lower().rstrip('l')
    	if filename in filesdic:
                status = '200 OK' # HTTP Status
                headers = [('Content-type', 'text/html')] # HTTP Headers
                start_response(status, headers)
                return filesdic[filename](environ)
            else:
                status = '200 OK' # HTTP Status
                headers = [('Content-type', 'text/plain')] # HTTP Headers
                start_response(status, headers)
                return ["Page not found"]
        return webapp
    
    from wsgiref.simple_server import make_server
    myapp = getapp(files)
    srv = make_server('localhost',port,myapp)
    print "Webserver on port %s" % (port)
    try:
        srv.serve_forever()
    except KeyboardInterrupt:
        print "Server closed due to keyboard interrupt"
    Hopefully this weekend I'll put an explanation of the code up if you need details about how it works.

    Thanks, but no need to do that work unless you want to. I have successfully made an apache web sever running cgi scripts in python to control my MCU. Now i'm working on writing PHP code and javascript using ajax to provide real time updates of the MCU status.

    I've came a long ways since I posted that question not to long ago!

    But you can help progress the project! If you know how to access the serial port in PHP that would be awsome!!!!! If not i'm trying to get a clear and thorough lesson on how to pass variables to a python script in PHP and have the python script send variables back to my PHP. Do you know how to do either one of these?

    Thanks!
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2012
    Posts
    39
    Rep Power
    3
    I believe shell_exec in PHP allows you to run shell commands, so you could try something like
    PHP Code:
    $output shell_exec("python code.py $params"); 
    The params passed would then be available in the argv variable as normal. Unsure of the performance of doing this, especially if your code will need a lot of setting up.

    No idea about serial port access in PHP. It is a little outside of the original design for the language so may not be possible at all.

    I'll leave the explanation of the web server for my blog. I've been meaning to add one for a couple of weeks.
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2011
    Posts
    8
    Rep Power
    0
    Originally Posted by Quackajack
    I believe shell_exec in PHP allows you to run shell commands, so you could try something like
    PHP Code:
    $output shell_exec("python code.py $params"); 
    The params passed would then be available in the argv variable as normal. Unsure of the performance of doing this, especially if your code will need a lot of setting up.

    No idea about serial port access in PHP. It is a little outside of the original design for the language so may not be possible at all.

    I'll leave the explanation of the web server for my blog. I've been meaning to add one for a couple of weeks.
    That gave me the right research. I have it working now. I used exec('python_script.py '.$some_data,$return_data)

    appending attributes to the python_scripts.py as a string is the data I pass to the python script and the $return_data is an array that python puts all of its output to after execution.

    Just in case some one cares
    python side

    access data you passed:
    import sys
    sys.argv[0] #this is always the script path name
    sys.argv[1] #this would be in my case the string i appended ($some_data) don't forget the space between .py and the data strings you pass


    I'm using the setInterval in java script to send a request to my MCU every 100mS. But this is not working so well.

    It works but when I pass what button is press on my HTML page to my php document that passes what button was pressed to my python script, all the time that i'm also sending a request to my MCU every 100mS. Its a little glitchy. Somtimes the serial port does not open. I think its becuase it is in the middle of a regular interval request and when I push a button the python script is already sending something else??

IMN logo majestic logo threadwatch logo seochat tools logo