1 year ago
#358277
Pradeep Padmanaban C
Python SimpleHTTPServer : Desired Response Code generator
I have written a python code to generate desired response code for curl request
from email import message
from http.server import HTTPServer, BaseHTTPRequestHandler
import sys
server_ip = '0.0.0.0'
server_port = int(sys.argv[1])
response_code = int(sys.argv[2])
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(response_code)
self.send_header('Content-Type',
'text/plain; charset=utf-8')
self.end_headers()
message = "Current Response Code is : "+ str(response_code)
self.wfile.write(message.encode('utf-8'))
self.wfile.write(b'\n')
if __name__ == '__main__':
server = HTTPServer((server_ip, server_port), Handler)
print('Starting server, use <Ctrl-C> to stop')
server.serve_forever()
from this script i can generate any response code i want , from any port
% python HTTPResponseServer.py 3389 300
Starting server, use <Ctrl-C> to stop
127.0.0.1 - - [31/Mar/2022 14:50:58] "GET / HTTP/1.1" 300 -
127.0.0.1 - - [31/Mar/2022 14:51:01] "GET / HTTP/1.1" 300 -
curl output
% curl -v localhost:3389
* Trying ::1...
* TCP_NODELAY set
* Connection failed
* connect to ::1 port 3389 failed: Connection refused
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 3389 (#0)
> GET / HTTP/1.1
> Host: localhost:3389
> User-Agent: curl/7.64.1
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 300 Multiple Choices. <----------------------------- Response code check
< Server: BaseHTTP/0.6 Python/3.9.5
< Date: Thu, 31 Mar 2022 09:26:52 GMT
< Content-Type: text/plain; charset=utf-8
<
Current Response Code is : 300
* Closing connection 0
Now Do i have to do this or is there a inbuilt way in python to do this ? for
% python3 -m http.server <port number>
python
http
response
httpresponse
0 Answers
Your Answer