#!/usr/bin/python # -*- coding: utf-8 -*- #from __future__ import with_statement import cgitb cgitb.enable() import sys, os, cgi, json, codecs, time #activate_this = os.path.join(os.path.dirname(__file__), 'venv/bin/activate_this.py') #execfile(activate_this, dict(__file__=activate_this)) def main(): """Main CGI handler.""" # Print JSON header print_header() # Convert form fields to regular dictionary form = dict((field, cgi.FieldStorage().getvalue(field)) for field in cgi.FieldStorage().keys()) # Get input values + analyze text #if "complexity" in form: if form.get("command", "") == "complexity": pass elif form.get("command", "") == "log": timestamp = "\n" + time.strftime("%H:%M:%S") + "\n" text_to_log = timestamp + form.get("text", "") #.decode("utf-8") log_type = form.get("log_type", "exe_linguists") if text_to_log and log_type in ["exe_linguists"]: log_file = "logs/%s.txt" % log_type with codecs.open(log_file, "a") as f: os.chmod(log_file, 0o664) f.write(str(text_to_log)) complexity_analysis = json.dumps({"result":"Result logged.","code":202}) else: complexity_analysis = json.dumps({"Error":"Wrong value for 'log_type'. Available options: exe_linguists","code":400}) else: complexity_analysis = json.dumps({"Error":"Unknown or missing command. Command option(s): complexity, log","code":501}) print_object(json.loads(complexity_analysis), form) def print_header(): """Prints the JSON header.""" print "Content-Type: application/json" print "Access-Control-Allow-Origin: *" print "Access-Control-Allow-Methods: POST, GET, OPTIONS" print "Access-Control-Allow-Headers: Content-Type" print def print_object(obj, form): """Prints an object in JSON format. The CGI form can contain optional parameters 'callback' and 'indent' which change the output format. """ callback = form.get("callback") if callback: print callback + "(", try: indent = int(form.get("indent")) print json.dumps(obj, sort_keys=True, indent=indent), except: print json.dumps(obj, separators=(",",":")) if callback: print ")", print if __name__ == "__main__": main()