How do I avoid the console logging of http.server - python

I have an http.server running inside my code to load a local html, but I don't want the server to log on console every time a request is made.
I looked into this post:
How to silent/quiet HTTPServer and BasicHTTPRequestHandler's stderr output?
And tried it out but it returns an error: missing 3 required positional arguments
class main()
def openHttpServer(self):
port = 8000
Handler = http.server.SimpleHTTPRequestHandler
self.httpd = socketserver.TCPServer(("", port), Handler)
self.httpd.serve_forever()
I expect it to work the same but without the SimpleHTTPRequestHandler logging in console.

I fixed it by sub classing as suggested in several post
So, if I was using http.server.SimpleHTTPRequestHandler as Handler I now pass it as a subclass here:
class quietServer(http.server.SimpleHTTPRequestHandler):
And just write the function for the log_message with pass so it doesn't return a log on requests.
def log_message(self, format, *args):
pass
So the whole code would be like this:
import http.server
import socketserver
PORT = 8080
class quietServer(http.server.SimpleHTTPRequestHandler):
def log_message(self, format, *args):
pass
with socketserver.TCPServer(("", PORT), quietServer) as httpd:
httpd.serve_forever()

Related

How can i make a python server open an html file as deafult instead of directory?

here is an example for a simple server:
import http.server
import socketserver
PORT = 80
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
the server itself works and the port is open but it opens the directory the code is in while i need it to open an html file that is in that directory.
How can i make it open the html file i want instead of the directory?
You can extend SimpleHTTPServer.SimpleHTTPRequestHandler and override the do_GET method to replace self.path with your_file.html if / is requested.
import SimpleHTTPServer
import SocketServer
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.path = '/your_file.html'
return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
Handler = MyRequestHandler
server = SocketServer.TCPServer(('0.0.0.0', 8080), Handler)
server.serve_forever()
More: Documentation

access underlying socket using http.server

I have the following code to run a simple http server
from http.server import SimpleHTTPRequestHandler, HTTPServer
host = "localhost"
port = 8881
server_class = HTTPServer
httpd = server_class((host, port), SimpleHTTPRequestHandler)
print("http server is running {}:{}".format(host, port))
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
At some point in my code I'd like to access the underlying socket s of the server (which I assume has to acessible somehow) to do something like s.getsockname() for example. Is that possible?
You can access it as self.socket, like so.
httpd.socket.getsockname()
See the source code of the base class SocketServer for more info.
However, for this use case the proper way of doing it is httpd.server_address. In general, you should not try to use the raw socket. Also I would skip the server_class variable and just go HTTPServer((host, port), SimpleHTTPRequestHandler) to keep things simple.

global name 'WebServer' is not defined

Please find below code as it is throwing the error - global name 'webserver' is not defined.
import SimpleHTTPServer
import SocketServer
import os
from threading import Thread
import threading
class WebServer(Thread):
def __init__(self, stream_path):
"""
Class to create a Web server and add given folder to the web server which is passed as an argument.
In this case it creates the web server to the incoming streams pushed by VLC to temp folder
"""
Thread.__init__(self)
self.stream_path = stream_path
def run(self):
global WebServer
"""
This method is built in Thread object method invoked by start()
and the code which is under run() will be executed.
"""
os.chdir(self.stream_path)
PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
print "function thread", threading.currentThread()
httpd.serve_forever()
print "test1"
def create_web_server(self,stream_path):
global WebServer
"""
This method is to create the web server to a given path
"""
obj1 = WebServer(self,stream_path)
obj1.start()
print "server created"
def stop_web_server(self):
cmd='tskill python /A'
os.system(cmd)
if __name__ == '__main__':
create_web_server("","C:\\\\QED")
You don't need the two global WebServer lines in your code. The global keyword is used to grant write access to a global variable, and you don't have a global variable named WebServer.
Your code should look like the following to resolve your error, though in its state, it will still throw errors because your code has multiple problems, including calling the create_web_server method by itself, as it's a method that needs to be run on a WebServer object.
I've included a working prototype example of your code at the bottom of my post.
import SimpleHTTPServer
import SocketServer
import os
from threading import Thread
import threading
class WebServer(Thread):
def __init__(self, stream_path):
"""
Class to create a Web server and add given folder to the web server which is passed as an argument.
In this case it creates the web server to the incoming streams pushed by VLC to temp folder
"""
Thread.__init__(self)
self.stream_path = stream_path
def run(self):
"""
This method is built in Thread object method invoked by start()
and the code which is under run() will be executed.
"""
os.chdir(self.stream_path)
PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
print "function thread", threading.currentThread()
httpd.serve_forever()
print "test1"
def create_web_server(self,stream_path):
"""
This method is to create the web server to a given path
"""
obj1 = WebServer(self,stream_path)
obj1.start()
print "server created"
def stop_web_server(self):
cmd='tskill python /A'
os.system(cmd)
if __name__ == '__main__':
create_web_server("","C:\\\\QED")
Here is a simplified version of your code that should do the same thing (serve a directory with a basic SimpleHTTPRequestHandler).
It runs the thread in daemon mode so that it can be interrupted with Ctrl-C. I removed several methods as they didn't seem to serve a purpose in your original code, and to show you a basic framework of what your WebServer class would probably look like.
import threading
import os
import time
import SimpleHTTPServer
import SocketServer
class WebServer(threading.Thread):
# Let's specify additional constructor arguments for host/port
# so you don't have to hardcode those values.
# We can specify default values for them as well.
def __init__(self, stream_path, host='localhost', port=8000):
super(WebServer, self).__init__()
self.stream_path = stream_path
self.host = host
self.port = port
# This is the method that will be called when you call
# .start() on a WebServer object.
def run(self):
os.chdir(self.stream_path)
handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer((self.host, self.port), handler)
httpd.serve_forever()
if __name__ == '__main__':
# Create a WebServer thread object, set it to daemonize
# and start it
ws = WebServer(r'C:\QED')
ws.daemon = True
ws.start()
# Since the main thread doesn't do anything after daemonizing
# the WebServer, it would exit immediately.
# This forever loop just ensures that the main thread runs
while True: time.sleep(1)
And to take it a step further, you don't need to create a Thread subclass. It's allowed because it feels more 'natural' to developers who are familiar with Java, where subclassing Thread or implementing Runnable is standard practice.
You can just do something like:
import threading
import os
import time
import SimpleHTTPServer
import SocketServer
def run_http_server(serve_dir, host='localhost', port=8000):
os.chdir(serve_dir)
handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer((host, port), handler)
httpd.serve_forever()
if __name__ == '__main__':
thread = threading.Thread(target=run_http_server, args=(r'C:\QED',))
thread.daemon = True
thread.start()
while True: time.sleep(1)

How to communicate from the Request Handler to a Socket Server

I have the following two Python classes:
import socketserver
class MyServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
def __init__(self, server_address):
socketserver.TCPServer.__init__(self, server_address, MyTcpHandler)
self.allow_reuse_address = True
self.serve_forever()
class MyTcpHandler(socketserver.BaseRequestHandler):
data = ""
def handle(self):
self.data = self.request.recv(BUFF_SIZE).strip()
if self.data == b"shutdown":
self.request.close()
import threading
threading.Thread(target=SERVER.shutdown).start()
Thus, when the client sends "shutdown", the server itself should shutdown. As a workaround I set the global variable SERVER to the MyServer object, then I call SERVER.shutdown in another thread, as shown above.
But using a global variable is ugly as hell. So how can I communicate directly from the request handler with the socket server instead?
The server is available as self.server according to the Python docs here https://docs.python.org/2/library/socketserver.html#SocketServer.BaseRequestHandler.handle

How do I serve and log my current directory with a python web server?

I need to create a webserver that will respond to GET requests by serving pages from a specified folder, as well as log the pages the user is GETting, and the IP of the user.
The main trouble comes from me not knowing how to serve the directory listing to the user when overriding the do_GET method. Here is my code so far:
#!/usr/bin/env python
import logging
import SimpleHTTPServer
import SocketServer
import SimpleHTTPServer
import BaseHTTPServer
import os
PORT = 8001
LOG_FILENAME = 'log.txt'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
try:
#self.send_response(200)
#self.send_header('Content-type', 'text/html')
#self.end_headers();
#self.list_directory(self.path)
#os.listdir()
logging.debug('Test text')
except IOError:
print "nothing"
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), MyHandler)
print "serving at port", PORT
httpd.serve_forever()
You need to use dir_listing() to list directories.
Rather than writing it here, I would suggest you look at the python cookbook/ recipes for detailed directions and understanding.
http://code.activestate.com/recipes/392879-my-first-application-server/

Categories