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()
Related
Can anyone tell me what's the solution for this?
When I run it and load it from the browser... It's only loading and never displaying the "Hello Word!" text.
But the text will appear in the browser after I shutdown the server by triggering the KeyboardInterrupt.
PS: SSL is enabled in python 2.6 interpreter on Linux. Also, it's not working in Windows 7.
Here's the code:
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import ssl
import sys
PORT_NUMBER = int(sys.argv[1])
#This class will handles any incoming request from the browser
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
print(self.requestline)
#print(self.rfile.read(content_length))
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
# Send the html message
self.wfile.write("Hello World !".encode())
return
try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
server.socket = ssl.wrap_socket(server.socket, certfile='cert.pem',keyfile='key.pem', server_side=True)
print 'Started httpserver on port ' , PORT_NUMBER
#Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
in order to run this in Python 2.x, command: python this_code.py [port]
Example:
python this_code.py 8080
Then navigate to the browser with the address: https://localhost:8080/
If I remove this line, it'll work but it's just running under HTTP protocol and not in HTTPS (which I'm intended to run in):
server.socket = ssl.wrap_socket(server.socket, certfile='cert.pem',keyfile='key.pem', server_side=True)
Please refer the below code:
import grpc
from concurrent import futures
import time
import calculator_pb2
import calculator_pb2_grpc
import calculator
class CalculatorServicer(calculator_pb2_grpc.CalculatorServicer):
def SquareRoot(selfself, request, context):
response = calculator_pb2.Number()
response.value = calculator.square_root((request.value))
return response
# Creating gRPC server
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
calculator_pb2_grpc.add_CalculatorServicer_to_server(CalculatorServicer(), server)
print('Starting server. Listening on port 50051.')
server.add_insecure_port('[::]:50051')
server.start()
# The below line is what is keeping the server alive
try:
while True:
time.sleep(86400)
except KeyboardInterrupt:
server.stop(0)
**********************************
try:
while True:
time.sleep(86400)
except KeyboardInterrupt:
server.stop(0)
***********************************
In the above code block, is it possible to not to using a sleep condition and still the server will be alive?
Currently gRPC Python servers do not have an equivalent to the C++ server's Wait() API. You will need to keep the calls to Python's time.sleep, as in our example server code.
I am trying to figure out how to run my overloaded customized BaseHTTPServer instance in the background after running the "".serve_forever() method.
Normally when you run the method execution will hang until you execute a keyboard interrupt, but I would like it to serve requests in the background while continuing script execution. Please help!
You can start the server in a different thread: https://docs.python.org/3/library/_thread.html#thread.start_new_thread
So something like:
def start_server():
# Setup stuff here...
server.serve_forever()
# start the server in a background thread
thread.start_new_thread(start_server)
print('The server is running but my script is still executing!')
I was trying to do some long-term animation using async and thought I'd have to rewrite server to use aiohttp (https://docs.aiohttp.org/en/v0.12.0/web.html), but Olivers technique of using seperate thread saved me all that pain. My code looks like this, where MyHTTPServer is simply my custom sublass of HTTPServer
import threading
import asyncio
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver
import io
import threading
async def tick_async(server):
while True:
server.animate_something()
await asyncio.sleep(1.0)
def start_server():
httpd.serve_forever()
try:
print('Server listening on port 8082...')
httpd = MyHTTPServer(('', 8082), MyHttpHandler)
asyncio.ensure_future(tick_async(httpd))
loop = asyncio.get_event_loop()
t = threading.Thread(target=start_server)
t.start()
loop.run_forever()
I want to start a simple web server locally, then launch a browser with an url just served. This is something that I'd like to write,
from wsgiref.simple_server import make_server
import webbrowser
srv = make_server(...)
srv.blocking = False
srv.serve_forever()
webbrowser.open_new_tab(...)
try:
srv.blocking = True
except KeyboardInterrupt:
pass
print 'Bye'
The problem is, I couldn't find a way to set a blocking option for the wsgiref simple server. By default, it's blocking, so the browser would be launched only after I stopped it. If I launch the browser first, the request is not handled yet. I'd prefer to use a http server from the standard library, not an external one, like tornado.
You either have to spawn a thread with the server, so you can continue with your control flow, or you have to use 2 python processes.
untested code, you should get the idea
class ServerThread(threading.Thread):
def __init__(self, port):
threading.Thread.__init__(self)
def run(self):
srv = make_server(...)
srv.serve_forever()
if '__main__'==__name__:
ServerThread().start()
webbrowser.open_new_tab(...)
Using the following example I can get a basic web server running but my problem is that the handle_request() blocks the do_something_else() until a request comes in. Is there any way around this to have the web server do other back ground tasks?
def run_while_true(server_class=BaseHTTPServer.HTTPServer,
handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
while keep_running():
httpd.handle_request()
do_something_else()
You can use multiple threads of execution through the Python threading module. An example is below:
import threading
# ... your code here...
def run_while_true(server_class=BaseHTTPServer.HTTPServer,
handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
while keep_running():
httpd.handle_request()
if __name__ == '__main__':
background_thread = threading.Thread(target=do_something_else)
background_thread.start()
# ... web server start code here...
background_thread.join()
This will cause a thread which executes do_something_else() to start before your web server. When the server shuts down, the join() call ensures do_something_else finishes before the program exits.
You should have a thread that handles http requests, and a thread that does do_something_else().