This is the code I got from Tutorial of how to make local server by using python script to run in Terminal
import SimpleHTTPServer
import SocketServer
import BaseHTTPServer
import os
HOSTNAME = "localhost"
PORT = 8000
HANDLER = SimpleHTTPServer.SimpleHTTPRequestHandler
os.chdir("/Users/Team/Desktop/python server")
httpd = SocketServer.TCPServer((HOSTNAME, PORT), HANDLER)
print "serving at port", PORT
httpd.serve_forever()
I wonder why they have to import the BaseHTTPServer? can anyone explain me about that? below is the version from Python.org
import SimpleHTTPServer
import SocketServer
PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
You'll see that there is no import BaseHTTPServer, can anyone explain to me why?
and these code are in Python 2.7 if I want to change it into python 3 Do I still need to import BaseHTTPServer?
Importing it has has meaningful impact, as you have discovered. As for why it is there - who knows? Maybe the author of the tutorial intended to use it later in the tutorial, or maybe it was adapted from a larger sample. The point is if nothing is referencing it, you don't need to import it.
The same applies to python 3.
Related
I want to launch Python HTTPServer on heroku. Note that this is no Python framework. The code snippet is attached below. How will I be able to launch this server on Heroku? I am able to run this server on my local machine. But I want it deployed on Heroku. Please provide insights.
Server Code:
import http.server
from http.server import HTTPServer, BaseHTTPRequestHandler
import socketserver
import threading
PORT = 5001
class myHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.write("Heroku is awesome")
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
try:
server = ThreadedTCPServer(('', PORT), myHandler)
print ('Started httpserver on port ' , PORT)
ip,port = server.server_address
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
allow_reuse_address = True
server.serve_forever()
except KeyboardInterrupt:
print ('CTRL + C RECEIVED - Shutting down the REST server')
server.socket.close()
When heroku runs your process, it defines the environment variable PORT to the internal port you should expose your server on. Your server will then be accessible from the internet on port 80, the default HTTP port.
Python can access environment variables with os.environ.
So you can use:
PORT = environ['PORT']
os.envron docs here
You can read more about how Heroku handles ports here.
Create a Procfile with a single line:
web: python yourscript.py
Building a simple file server using the SimpleHTTPServer module in Python, however I'm running into issues when trying to get the IP from a connecting client. Here is what I have..
import SimpleHTTPServer
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", 8080), Handler)
print "Serving local directory"
while True:
httpd.handle_request()
print Handler.client_address[0]
When a client connects I get..
AttributeError: class SimpleHTTPRequestHandler has no attribute 'client_address'
I know this is because I haven't instantiated the class yet, but is there another way to get the IP from the client without having to create a handler instance? The client's IP is outputted to the console when a connection is made, I just need a way to grab that IP within my script.
Thanks!
Indeed, the Handler class object is unrelated to specific instances. Set up your own handler class, like this:
import SimpleHTTPServer
import SocketServer
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def handle_one_request(self):
print(self.client_address[0])
return SimpleHTTPServer.SimpleHTTPRequestHandler.handle_one_request(self)
print("Serving local directory")
httpd = SocketServer.TCPServer(("", 8080), MyHandler)
while True:
httpd.handle_request()
I'm a total newbie when it comes to servers, so this question my sound silly to you, but I stucked and I need you help once more.
I have written a simple server in python, which looks like this:
#!/usr/bin/env python
from socket import *
import time
s = socket(AF_INET, SOCK_STREAM)
s.bind(('', 8888))
s.listen(5)
while 1:
client,addr = s.accept()
print 'Connected to ', addr
client.send(time.ctime(time.time()))
client.close()
So when i write localhost:8888 in my browser, i get the message with the current server time.
The next thing i want to do, is to configure my server to allow opening various files from my computer i.e. html or text ones. So when I write in my browser localhost:8888/text.html, this file opens. Where do i start with that?
I should mention I'm using linux mint and don't want to use any existing framework. I want to fully understand how the servers are working and responding.
Try this:
Create a script named webserver.py
import SimpleHTTPServer
import SocketServer
PORT = 8888
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
Create a file named text.html and place it on the same dir where your webserver.py script is.
Run python webserver.py
Navigate to http://localhost:8888/text.html
I'm trying to launch a simple server from a Python script:
server = Popen(['python' ,'-m', 'SimpleHTTPServer', '9090'], stderr=STDOUT, stdout=PIPE)
output = server.communicate()[0] # <- DEBUG
Reading the output, I see:
'/usr/bin/python: Import by filename is not supported.'
What's the problem? How to solve it?
I suggest change to code to this:
import SimpleHTTPServer
import SocketServer
PORT = 9090
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
from BaseHTTPServer import HTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler
import socket,ssl
import time
import Config
class StartHTTPServer:
'''Web server to serve out map image and provide cgi'''
def __init__(self):
# Start HTTP Server. Port and address defined in Config.py
srvraddr = ("", Config.HTTP_PORT) # my hostname, portnumber
srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler)
srvrobj.socket = ssl.wrap_socket(srvrobj.socket,server_side=True,
certfile="c:\users\shuen\desktop\servertryout 23022012\serverCert.crt",
keyfile="c:\users\shuen\desktop\servertryout 23022012\privateKey.key",
ssl_version=ssl.PROTOCOL_TLSv1,
do_handshake_on_connect=True)
print srvrobj.socket.cipher()
print srvrobj.socket.getsockname()
print "HTTP server running at IP Address %s port %s." % (Config.HTTP_ADDRESS, Config.HTTP_PORT)
srvrobj.serve_forever() # run as perpetual demon
srvrobj.socket.accept()
message='hello from server.<EOF>'
srvrobj.socket.send(message)
I have tried to send data with a normal socket, which works. However, the code i'm working on is using socketServer and can't be change. I cannot find any example which will send data across to the server. How can I do that?
If you really cannot change your server software, you must use a wrapper, e. g. openssl s_server.