How do I launch Python SimpleHTTPServer on heroku?

妖精的绣舞 提交于 2021-01-27 20:17:31

问题


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

回答1:


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.




回答2:


Create a Procfile with a single line:

web: python yourscript.py


来源:https://stackoverflow.com/questions/45172494/how-do-i-launch-python-simplehttpserver-on-heroku

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!