You are not logged in.

#1 2013-05-10 21:00:40

Predator
Member
Registered: 2013-05-03
Posts: 3

Python BaseHTTPServer - jQuery .get not receiving data

Here's a slightly modified example I have put together to test this, but apparently it is not working.

#!/usr/bin/env python2

import BaseHTTPServer

SERVER_HOSTNAME = "localhost"
SERVER_PORT = 80

def parseHTTPCommand(command):

	if command == "test":

		print("TEST COMMAND RECEIVED!")

		return "TEST COMMAND CONTENT FROM SERVER"
		
	elif command == "status":
		
		print("STATUS COMMAND RECEIVED!")
		
		return "STATUS COMMAND CONTENT FROM SERVER"

class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):

	def do_HEAD(s):

		s.send_respone(200)
		s.send_header("Content-type", "text/html")
		s.end_headers()

	def do_GET(s):

		s.send_response(200)
		s.send_header("Content-type", "text/html")
		s.end_headers()

		if s.path.find("?") != -1:

			# Check and extract client commands
			data = s.path.split("?", 1)
			
			command = data[1].split("=", 1)[1]
			
			client_data = parseHTTPCommand(command)
			
			# Write data back to the client
			s.wfile.write(client_data)

if __name__ == "__main__":

	server = BaseHTTPServer.HTTPServer
	httpd = server((SERVER_HOSTNAME, SERVER_PORT), MyHandler)

	try:

		httpd.serve_forever()

	except KeyboardInterrupt:

		pass

	httpd.server_close()

The server itself receives the request, BUT jQuery seems to be left without any response/data, which is weird, because simple HTML requests (without using jQuery) do just fine.

Where's the problem?

Offline

#2 2013-05-10 21:13:34

Xyne
Administrator/PM
Registered: 2008-08-03
Posts: 6,965
Website

Re: Python BaseHTTPServer - jQuery .get not receiving data

Haha, I just got done writing this and the first new post I see is about Python HTTP servers. Funny little coincidence.

Try sending a "Content-Length" header. Be careful with the case of your headers too (e.g. "Content-Type", not "Content-type").

Other tips going forward:
* Try to keep the code that sends the headers together with the code that sends the data. It will be easier to send conditional headers that way.
* May extensive use of the urllib.parse functions (whatever the Python 2 equivalent is) instead of writing your own custom parsers

You may find some useful stuff in ThreadedHTTPSServer.py from the link above (e.g. functions for transferring files, HTML, JSON and plaintext with all the expected headers).


My Arch Linux StuffForum EtiquetteCommunity Ethos - Arch is not for everyone

Offline

Board footer

Powered by FluxBB