forked from CursosWeb/X-Serv-14.7-ServURLAleat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webapp.py
65 lines (48 loc) · 2.06 KB
/
webapp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/python
"""
webApp class
Root for hierarchy of classes implementing web applications
Copyright Jesus M. Gonzalez-Barahona and Gregorio Robles (2009-2015)
jgb @ gsyc.es
TSAI, SAT and SARO subjects (Universidad Rey Juan Carlos)
October 2009 - February 2015
"""
import socket
class webApp:
"""Root of a hierarchy of classes implementing web applications
This class does almost nothing. Usually, new classes will
inherit from it, and by redefining "parse" and "process" methods
will implement the logic of a web application in particular.
"""
def parse(self, request):
"""Parse the received request, extracting the relevant information."""
return None
def process(self, parsedRequest):
"""Process the relevant elements of the request.
Returns the HTTP code for the reply, and an HTML page.
"""
return ("200 OK", "<html><body><h1>It works!</h1></body></html>")
def __init__(self, hostname, port):
"""Initialize the web application."""
# Create a TCP objet socket and bind it to a port
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mySocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
mySocket.bind((hostname, port))
# Queue a maximum of 5 TCP connection requests
mySocket.listen(5)
# Accept connections, read incoming data, and call
# parse and process methods (in a loop)
while True:
print 'Waiting for connections'
(recvSocket, address) = mySocket.accept()
print 'HTTP request received (going to parse and process):'
request = recvSocket.recv(2048)
print request
parsedRequest = self.parse(request)
(returnCode, htmlAnswer) = self.process(parsedRequest)
print 'Answering back...'
recvSocket.send("HTTP/1.1 " + returnCode + " \r\n\r\n"
+ htmlAnswer + "\r\n")
recvSocket.close()
if __name__ == "__main__":
testWebApp = webApp("localhost", 1234)