Add files via upload
[PyWWW-Get.git] / pyhttpserv.py
blob0cd20daf06afdd5735d1178543177f0d5c0226ab
1 #!/usr/bin/env python
3 '''
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the Revised BSD License.
7 This program is distributed in the hope that it will be useful,
8 but WITHOUT ANY WARRANTY; without even the implied warranty of
9 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 Revised BSD License for more details.
12 Copyright 2016-2023 Game Maker 2k - https://github.com/GameMaker2k
13 Copyright 2016-2023 Kazuki Przyborowski - https://github.com/KazukiPrzyborowski
15 $FileInfo: pyhttpserv.py - Last Update: 9/24/2023 Ver. 1.5.0 RC 1 - Author: cooldude2k $
16 '''
18 enablessl = False;
19 sslkeypem = None;
20 sslcertpem = None;
21 servport = 8080;
22 if(isinstance(servport, int)):
23 if(servport<1 or servport>65535):
24 servport = 8080;
25 elif(isinstance(servport, str)):
26 if(servport.isnumeric()):
27 servport = int(servport);
28 if(servport<1 or servport>65535):
29 servport = 8080;
30 else:
31 servport = 8080;
32 else:
33 servport = 8080;
34 if(enablessl):
35 if(sslkeypem is not None and
36 (not os.path.exists(sslkeypem) or not os.path.isfile(sslkeypem))):
37 sslkeypem = None;
38 enablessl = False;
39 if(sslcertpem is not None and
40 (not os.path.exists(sslkeypem) or not os.path.isfile(sslkeypem))):
41 sslcertpem = None;
42 enablessl = False;
43 pyoldver = True;
44 try:
45 from BaseHTTPServer import HTTPServer;
46 from SimpleHTTPServer import SimpleHTTPRequestHandler;
47 from urlparse import parse_qs;
48 from Cookie import SimpleCookie
49 except ImportError:
50 from http.server import SimpleHTTPRequestHandler, HTTPServer;
51 from urllib.parse import parse_qs;
52 from http.cookies import SimpleCookie;
53 pyoldver = False;
54 if(enablessl and
55 (sslkeypem is not None and (os.path.exists(sslkeypem) and os.path.isfile(sslkeypem))) and
56 (sslcertpem is not None and (os.path.exists(sslkeypem) and os.path.isfile(sslkeypem)))):
57 import ssl;
58 # HTTP/HTTPS Server Class
59 class CustomHTTPRequestHandler(SimpleHTTPRequestHandler):
60 def display_info(self):
61 # Setting headers for the response
62 self.send_response(200);
63 self.send_header('Content-type', 'text/plain');
64 # Set a sample cookie in the response;
65 self.send_header('Set-Cookie', 'sample_cookie=sample_value; Path=/;');
66 self.end_headers();
67 # Displaying request method
68 response = 'Method: {}\n'.format(self.command);
69 response += 'Path: {}\n'.format(self.path);
70 # Displaying all headers
71 headers_list = ["{}: {}".format(key.title(), self.headers[key]) for key in self.headers];
72 response += '\nHeaders:\n' + '\n'.join(headers_list) + '\n';
73 # Extract and display cookies from headers
74 if 'Cookie' in self.headers:
75 response += '\nCookies:\n';
76 cookies = SimpleCookie(self.headers['Cookie']);
77 for key, morsel in cookies.items():
78 response += '{}: {}\n'.format(key, morsel.value);
79 # Displaying GET parameters (if any)
80 if self.command == 'GET':
81 query = self.path.split('?', 1)[-1];
82 params = parse_qs(query);
83 if params:
84 response += '\nGET Parameters:\n';
85 for key, values in params.items():
86 response += '{}: {}\n'.format(key, ', '.join(values));
87 # Sending the response
88 self.wfile.write(response.encode('utf-8'));
89 # Get Method
90 def do_GET(self):
91 self.display_info();
92 # Post Method
93 def do_POST(self):
94 if 'Transfer-Encoding' in self.headers and self.headers['Transfer-Encoding'] == 'chunked':
95 post_data = '';
96 while True:
97 chunk_size_line = self.rfile.readline().decode('utf-8');
98 chunk_size = int(chunk_size_line, 16);
99 if chunk_size == 0:
100 self.rfile.readline();
101 break;
102 chunk_data = self.rfile.read(chunk_size).decode('utf-8');
103 post_data += chunk_data;
104 self.rfile.readline();
105 else:
106 content_length = int(self.headers['Content-Length']);
107 post_data = self.rfile.read(content_length).decode('utf-8');
108 params = parse_qs(post_data);
109 response = 'POST Parameters:\n';
110 for key, values in params.items():
111 response += '{}: {}\n'.format(key, ', '.join(values));
112 self.send_response(200);
113 self.send_header('Content-type', 'text/plain');
114 self.send_header('Set-Cookie', 'sample_cookie=sample_value; Path=/;');
115 self.end_headers();
116 self.wfile.write(response.encode('utf-8'));
117 # Start Server Forever
118 if __name__ == "__main__":
119 server_address = ('', int(servport));
120 httpd = HTTPServer(server_address, CustomHTTPRequestHandler);
121 if(enablessl and sslkeypem is not None and sslcertpem is not None):
122 httpd.socket = ssl.wrap_socket (httpd.socket,
123 keyfile=sslkeypem, certfile=sslcertpem, server_side=True);
124 if(enablessl):
125 print("Server started at https://localhost:"+str(servport));
126 else:
127 print("Server started at http://localhost:"+str(servport));
128 httpd.serve_forever();