I am running a simple Python webserver to toggle a GPIO pin on a Raspberry Pi. All seems to work well, but I have a few questions about my code (see below).
I am using the urlparse
module to obtain the URL arguments.
The HTML file just sends out Ajax requests using buttons when clicked.
- I've commented out the send_response lines, and it seems to work both ways. Is it mandatory to send a response?
- Is the code below easy to exploit? Are there improvements I can make to make it a bit more robust?
Python code:
import time
import SimpleHTTPServer
import SocketServer
from urlparse import *
ledpin=18
myport=8123
# Turn LED on => http://ip_of_pi:port/control.html?led=on
# Turn LED off => http://ip_of_pi:port/control.html?led=off
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
urlcomp=urlparse(self.path) # Split URL in components
query = parse_qs(urlcomp.query) # Get args as dictionary
if len(query)==0 or query.has_key("led")==False:
self.path=urlcomp.path
# self.send_response(200)
elif query["led"] == ["on"] :
GPIO.output(ledpin,True)
# self.send_response(200)
return
elif query["led"] == ["off"] :
GPIO.output(ledpin,False)
# self.send_response(200)
return
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(ledpin,GPIO.OUT)
Handler = MyRequestHandler
httpd = SocketServer.TCPServer(('0.0.0.0', myport), Handler)
httpd.serve_forever()
import
lines in your code so that those of us with a raspi can copy/paste your code directly to try it out. \$\endgroup\$