def do_POST(self): """handle POST routes""" parsed_path = urlparse(self.path) if parsed_path.path == '/cow': try: content_length = int(self.headers['Content-Length']) body = json.loads(self.rfile.read(content_length).decode('utf8')) except (KeyError, json.decoder.JSONDecodeError) as err: self.send_response(400) self.end_headers() self.wfile.write(b'Incorrect format') return self.send_response(201) self.send_header('Content-Type', 'application/json') self.end_headers() daemon = cow.Daemon() msg = daemon.milk(body['msg']) self.wfile.write(json.dumps({'content': msg}).encode('utf8')) else: self.send_response(404) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write(b'Not Found')
decode_morse = dict( (morse_char, char) for (char, morse_char) in encode_morse.items()) cowList = { "cow": cow.Cowacter(), "hellokitty": cow.HelloKitty(), "bunny": cow.Bunny(), "cheese": cow.Cheese(), "milk": cow.Milk(), "bong": cow.BongCow(), "eyes": cow.Eyes(), "legitvore": cow.HeadInCow(), "666": cow.Satanic(), "frogs": cow.BudFrogs(), "daemon": cow.Daemon(), "moofasa": cow.Moofasa(), "mutilated": cow.Mutilated(), "skeleton": cow.Skeleton(), "small": cow.Small(), "sodomized": cow.Sodomized(), "garfield": cow.Stimpy(), "tux": cow.Tux(), "vader": cow.Vader() } def write_file(filename, contents): with open(filename, "w", encoding="utf8") as file: for item in contents: file.write(str(item))
def hello_world(message): return cow.Daemon().milk(message)
def do_GET(self): """handle GET routes""" parsed_path = urlparse(self.path) parsed_qs = parse_qs(parsed_path.query) if parsed_path.path == '/': #set header self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() #set body self.wfile.write(b"""<!DOCTYPE html> <html> <head> <title> cowsay </title> </head> <body> <header> <nav> <ul> <li><a href="/cowsay">cowsay</a></li> </ul> </nav> <header> <main> <p>cowsay is a program that generates ASCII pictures of a cow with a message. This is my first time making an HTTP server in Python</p> </main> </body> </html>""") elif parsed_path.path == '/cowsay': self.send_response(200) self.end_headers() self.wfile.write(b"""<!DOCTYPE html> <html> <head> <title> cowsay </title> </head> <body> <header> <nav> <ul> <li><a href="/">Home</a></li> </ul> </nav> <header> <main> <p>A message about other things you can do. After the port number, add <b>cow?msg="message"</b> in the address bar, replacing message with your message </p> </main> </body> </html>""") elif parsed_path.path == '/cow': try: daemon = cow.Daemon() msg = daemon.milk(json.loads(parsed_qs['msg'][0])) except (KeyError, json.decoder.JSONDecodeError): self.send_response(400) self.end_headers() self.wfile.write(b'Incorrect format') return self.send_response(200) self.end_headers() self.wfile.write(msg.encode('utf8')) else: self.send_response(404) self.end_headers() self.wfile.write(b'Not Found')