Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
HTTP server with python
import RPi.GPIO as GPIO
class Led:
def __init__(self, pin):
self.pin = pin
self.s = 0
GPIO.setmode(GPIO.BOARD)
GPIO.setup(self.pin, GPIO.OUT)
def __del__(self):
GPIO.cleanup(self.pin)
def state(self, s):
self.s = s
if s == '0':
GPIO.output(self.pin, GPIO.LOW)
else:
GPIO.output(self.pin, GPIO.HIGH)
# -*- coding:utf-8 -*-
import BaseHTTPServer
import socket
import cgi
from led import Led
def get_ip_address():
""" get ip address of active network interface """
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
addr = s.getsockname()[0]
s.close()
return addr
class TestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
""" Simple HTTP server
This site has RESTful API for L-Chika.
UI page for TEST
/ui.html This page has UI for API test.
API as follows:
/api/led
state 0 or 1
"""
html = """
<html>
<head>
<title>service UI</title>
<style type="text/css">
<!--
button {
font-size: 1.4em;
width: 40%;
height: 10%;
padding: 10px;
margin: 10px;
}
//-->
</style>
</head>
<body>
<p>LED
<form action="http://@HOST@:8000/api/led" method="post">
<button type='submit' name='state' value='1'>Hi</button>
<button type='submit' name='state' value='0'>Lo</button>
</form></p>
</body>
</html>
"""
html = html.replace('@HOST@', get_ip_address())
led = Led(40)
def do_GET(self):
# ignore request to favicon
if self.path.endswith('favicon.ico'):
return
# visited to ui.html, return html.
if self.path.endswith('ui.html'):
self.send_response(200)
self.end_headers
self.wfile.write(self.html)
return
# otherwise return 404 not found
self.send_response(404)
self.end_headers()
self.wfile.write("not found")
def do_POST(self):
# get the form data
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': self.headers['Content-Type'], })
# check path
if self.path.endswith('/api/led'):
self.process_post_header()
# do something...
self.led.state(form["state"].value)
print "Received %s" % form["state"].value
return
# otherwise return 404 not found
self.send_response(404)
self.end_headers()
self.wfile.write("not found")
def process_post_header(self):
# get the referer
referer = self.headers.get('Referer')
# if visited from ui.html, redirect to referer URI
if referer.endswith('ui.html'):
self.send_response(301)
self.send_header('Location', referer)
else:
self.send_response(200)
self.end_headers()
self.wfile.write(self.html)
server_address = ('', 8000)
httpd = BaseHTTPServer.HTTPServer(server_address, TestHandler)
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment