Prosty web czatowy w pythonie 🙂
Tworzymy dwa pliczki:
touch www.py # kod serwera www touch chat.txt # baza danych czatu
Zawartość pliku www.py :
Very simple python web-server
import http.server
import string
from os import curdir, sep
import cgi
import time
PORT_NUMBER = 8080
class myHandler(http.server.BaseHTTPRequestHandler):
#Handler GET
def do_GET(self):
try:
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(bytes("<html><head><title>Simple-CHAT</title></head>", "utf-8"))
self.wfile.write(bytes("<body><frameset cols='90%,10%'><frame>", "utf-8"))
with open(curdir + sep + "chat.txt") as f:
for line in f:
line=str.split(line,'\t')
self.wfile.write(bytes("<p>"+line[0]+":"+line[1]+": "+line[2]+"</p>", "utf-8"))
self.wfile.write(bytes("</frame><frame>", "utf-8"))
self.wfile.write(bytes("<form action='/' method='POST'>", "utf-8"))
self.wfile.write(bytes("Name:<br>", "utf-8"))
self.wfile.write(bytes("<input type='text' name='name' value='Noname'>", "utf-8"))
self.wfile.write(bytes("<input type='text' name='mes' value='blabllablalb'>", "utf-8"))
self.wfile.write(bytes("<input type='submit' value='Send'>", "utf-8"))
self.wfile.write(bytes("</form>", "utf-8"))
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
def do_POST(self):
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
print ("Your name is: %s" % form["name"].value)
self.send_response(200)
self.end_headers()
self.wfile.write(bytes("<html><head> <meta http-equiv='refresh' content='1;url='/'></head><body><p>", "utf-8"))
self.wfile.write(bytes("Thanks %s !" % form["name"].value, "utf-8"))
with open(curdir + sep + "chat.txt", "a") as f:
f.write("\n"+time.asctime()+"\t"+form["name"].value+"\t"+form["mes"].value)
try:
server = http.server.HTTPServer(('', PORT_NUMBER), myHandler)
print ("Start chat on " , PORT_NUMBER)
server.serve_forever()
except KeyboardInterrupt:
print ('^C received, chat off')
server.socket.close()
uruchamiamy skrypt poleceniem:
chmod +x www.py python www.py
Czat znajduje sie pod adresm $adres_hosta:8080 ( w moim przypadku localhost:8080)
A teraz pod lupa jak wygląda w pakietach komunikacja HTTP POST/GET:
Komunikat GET / od klienta
Komunikat 200 OK od serwera
POST od klienta