2013-10-31 70 views
0

我建立一個簡單的服務器:Python的HTTP GET參數

s = socket(AF_INET, SOCK_STREAM) 
s.bind(('127.0.0.1',8282)) 
s.listen(1) 
client, info = s.accept() 

request = "" 
i = 0 

while True: 
    c = client.recv(1) 
    request += c 
    if c in ["\r","\n"]: 
     i += 1 
    else: 
     i = 0 
    if i == 4: 
     break 

print "=============" 
print "Client Request" 
print "=============" 
print request 

raw_input('Press Enter to send response') 

data = """<html> 
<body> 
<h1>My Amazing Website !!!</h1> 
<br> 
<font color='yellow' size='20'>Hello (Name)</font> 
</body> 
</html> 
""" 

response = "HTTP/1.1 200 OK\r\n" 
response += "Content-Length: %d\r\n"%len(data) 
response += "Connection: Close\r\n" 
response += "Content-Type: text/html\r\n\r\n" 
response += data 

client.send(response) 
time.sleep(2) 
client.close() 

現在我不明白如何更換「(名稱)」在從URL中得到我的HTML代碼。可以說我的網址是:127.0.0.1:8282/?name = Someone。 我如何得到可以在這裏找到的名字「GET/* HTTP/1.1?」

回答

0

Python提供了urlparse模塊,其中包含實用程序從url獲取信息!

>>> from urlparse import urlparse, parse_qs 
>>> parse_qs(urlparse('/test?testing=test&greeting=smile').query) 
{'testing': ['test'], 'greeting': ['smile']} 

我覺得這裏最棘手的部分是讓GETrequest path from the header

Python提供更高水平的方式來構建Web服務器。 https://wiki.python.org/moin/BaseHttpServer,以及一些優秀的全棧web框架

+0

謝謝, 你能給我一個簡單的方法來獲得'get'嗎? – Nityuiop18