Python: run SimpleHTTPServer and make request to it in a script
Python: run SimpleHTTPServer and make request to it in a script
Run the server as a different process, that will allow you to run the rest of your script.
I would also rather use requests than urllib.
import SocketServer
import SimpleHTTPServer
import requests
import multiprocessing
# Variables
PORT = 8000
URL = localhost:{port}.format(port=PORT)
# Setup simple sever
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer((, PORT), Handler)
print Serving at port, PORT
# start the server as a separate process
server_process = multiprocessing.Process(target=httpd.serve_forever)
server_process.daemon = True
server_process.start()
# Getting HTML from the target page
values = {
name: Thomas Anderson,
location: unknown
}
r = requests.post(URL, data=values)
r.text
# stop the server
server_process.terminate()
Alternatively run it in the separate thread
:
import SimpleHTTPServer
import SocketServer
import urllib2
from threading import Thread
from datetime import time
# Variables
URL = localhost:8000
PORT = 8000
# Setup simple sever
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer((, PORT), Handler)
print serving at port, PORT
def simple_sever():
httpd.serve_forever()
simple_sever_T = Thread(target=simple_sever, name=simple_sever)
simple_sever_T.daemon = True
simple_sever_T.start()
while not simple_sever_T.is_alive():
time.sleep(1)
# Getting test file
req = urllib2.Request(http://localhost:%s/test_file % PORT)
response = urllib2.urlopen(req)
print response.read()
httpd.shutdown()