What im doing
Im trying to get my hands dirty with python and im making a very simple http server so i can send commands to my arduino via serial. Im validating the commands as i sgould and everything works as it ahould be.
The concept
Im using the HTTP server in order to recieve POST requests from remote computers and smartphones and execute code with my arduino via Serial.
It has few cool features like users and user permission levels.
The problem
I would like to give feedback when a request arrives. Specificaly JSON feedback with the outcome of the execution like error, notes and success.
Im thinking to make a dictionary in python and add whatever i want to send back the the frontend then enclode it in json and send it as a response. (Something like php's json_encode() which takes an array and outputs json)
The code
import SimpleHTTPServer
import SocketServer
import logging
import cgi
import time
import sys
class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
logging.warning("======= GET STARTED =======")
logging.warning(self.headers)
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
def do_POST(self):
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
if self.check_auth(username, passcode):
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
else:
print cur_time + "failed to login " + form.list[0].name + form.list[0].value
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
Handler = ServerHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
httpd.serve_forever()
I've tried to minimize the code so you can see the clear HTTP part.
As you can see im sending the headers and the response type (200 for successful login and 500 for unsuccessful login)
Objectives i need to accomplish
Pass inside a dictionary the stuff i want to encode
- Exemple: out = {'status': 'ok', 'executed': 'yes'}
- Respond with json
The complet code as a gist: https://gist.github.com/FlevasGR/1170d2ea47d851bfe024
I know this might not be the best you you've ever seens in your life but its my first time writing in Python :)