Karthik Gullapalli
Karthik Gullapalli

Reputation: 53

How do I launch Python SimpleHTTPServer on heroku?

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()

Upvotes: 2

Views: 3777

Answers (2)

Noskcaj
Noskcaj

Reputation: 703

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.

Upvotes: 4

Yuval Adam
Yuval Adam

Reputation: 165232

Create a Procfile with a single line:

web: python yourscript.py

Upvotes: 2

Related Questions