I am using python http.server to init 2 instances at different ports and serve up a html file from a folder...
import http.server
import socketserver
import os
PORT1 = 8000
PORT2 = 8001
os.chdir("html/folder1/")
Handler1 = http.server.SimpleHTTPRequestHandler
os.chdir("../folder2/")
Handler2 = http.server.SimpleHTTPRequestHandler
httpd1 = socketserver.TCPServer(("", PORT1), Handler1)
httpd2 = socketserver.TCPServer(("", PORT2), Handler2)
print("serving at port", PORT1)
print("serving at port", PORT2)
httpd1.serve_forever()
httpd2.serve_forever()
This loads without errors but I am only able to load http://localhost:8000
Any ideas where I am going wrong?
The serve_forever method does just that...serves http requests, and never exits. So when you do this:
httpd1.serve_forever()
httpd2.serve_forever()
The second statement is never executed because the first never exits. Possibly you could make this work by putting each call to serve_forever in a dedicated thread, and then just waiting for all threads to complete, but there may be a better solution.
Related
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()
I am attempting to start a simple HTTP web server in python and then ping it with the selenium driver. I can get the web server to start but it "hangs" after the server starts even though I have started it in a new thread.
from socket import *
from selenium import webdriver
import SimpleHTTPServer
import SocketServer
import thread
def create_server():
port = 8000
handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", port), handler)
print("serving at port:" + str(port))
httpd.serve_forever()
thread.start_new_thread(create_server())
print("Server has started. Continuing..")
browser = webdriver.Firefox()
browser.get("http://localhost:8000")
assert "<title>" in browser.page_source
thread.exit()
The server starts but the script execution stops after the server has started. The code after I start the thread is never executed.
How do I get the server to start and then have the code continue execution?
Start your thread with function create_server (without calling it ()):
thread.start_new_thread(create_server, tuple())
If you call create_server(), it will stop at httpd.serve_forever().
For Python 3 you can use this:
import threading
threading.Thread(target=create_server).start()
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.
When I run my python server file simplehttpwebsite.py in the linux shell and I do control+c and run it again I get socket.error: [Errno 98] Address already in use.
How do I make sure the socket closes down when I do ctrl+c?
simplehttpwebsite.py
#!/usr/bin/env python
import SimpleHTTPServer
import SocketServer
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
server = SocketServer.TCPServer(('0.0.0.0', 8080), Handler)
server.serve_forever()
Here is how you do it
#!/usr/bin/env python
import SimpleHTTPServer
import SocketServer
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
class MyTCPServer(SocketServer.TCPServer):
allow_reuse_address = True
server = MyTCPServer(('0.0.0.0', 8080), Handler)
server.serve_forever()
IMHO this isn't very well documented, and it should definitely be the default.
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/