I'm trying to set up very basic http server on my hosting(centos)
The script is:
#!/usr/bin/env python3.8
from http.server import HTTPServer, BaseHTTPRequestHandler
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b'Hello, world!')
httpd = HTTPServer(('0.0.0.0', 8080), SimpleHTTPRequestHandler)
httpd.serve_forever()
Everything looks normal: ss -t -a -n
LISTEN 0 5 0.0.0.0:8080 0.0.0.0:*
But when im trying to get to my websitename:8080 nothing is happening and i get connection timed out response.
I've been googling about http, networking, even centos for a few days, got lots of usefull information but i still have no idea what's going on here.
Ty for your time!
Related
This is interesting. I did a simple script to bind and serve http but I hadn't done this in Python3. I can write a simple server:
import http.server
import socketserver
PORT = 8002
Handler = http.server.SimpleHTTPRequestHandler
#https://docs.python.org/3/library/http.server.html
class MyHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, request, client_addr, server):
super().__init__(request, client_addr, server)
def do_GET(self, ):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.wfile.write('Hey!'.encode())
httpd = socketserver.TCPServer(("0.0.0.0", PORT), MyHandler)
print("serving at port", PORT)
httpd.serve_forever()
but when I run it, then Ctrl+c, then run it again it says:
OSError: [Errno 98] Address already in use
Why is that if I kill the previous process?
Also, is there any reason other than that that this couldn't be used as a simple, testing webapp for a test server at IP:port/somesamplewebapp - They say "http.server is not recommended for production. It only implements basic security checks." but if it does not need https or extra security... what are the risks?
The operating system prevents, by default, the reuse of an address by a different PID. You can defeat that with the socket option SO_REUSEADDR. However, since you are using the TCPServer class and it has it's own, different, way of specifying that. You can use this code.
import http.server
import socketserver
PORT = 8002
Handler = http.server.SimpleHTTPRequestHandler
#https://docs.python.org/3/library/http.server.html
class MyHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, request, client_addr, server):
super().__init__(request, client_addr, server)
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.wfile.write('Hey!'.encode())
class MyServer(socketserver.TCPServer):
allow_reuse_address = True # <-- This is what you need
httpd = MyServer(("0.0.0.0", PORT), MyHandler)
print("serving at port", PORT)
httpd.serve_forever()
my python codes
# _*_ coding:utf-8 _*_
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import SocketServer
class testHTTPSERVER_RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write("<html><body><h1>Hello world</h1></body></html>")
def run(server_class=HTTPServer,handler_class=BaseHTTPRequestHandler):
print('starting server ....')
server_address = ('127.0.0.1',8081)
httpd = server_class(server_address,testHTTPSERVER_RequestHandler)
print('running server')
httpd.serve_forever()
run()
and docker file
FROM python:2.7-onbuild
#python:2.7.13-alpine dene
ADD testhttp_server.py /src/app/testhttp_server.py
WORKDIR /src/app/
EXPOSE 8081
CMD ["python","testhttp_server.py"]
docker run and logs
mozilla
so where is my mistake??I'm working on that during two days but I didn't find anything else
Change this
server_address = ('127.0.0.1',8081)
to
server_address = ('0.0.0.0',8081)
Listening to 127.0.0.1 inside docker container means you want to listen to traffic generated from inside the container only but when you map a host to container. It is sending the traffic from host to the IP of the container. Which id dynamic and not know before hand. So you need to listen to all interfaces inside the container. And that is why you should use 0.0.0.0
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
I just want to allow make ajax request to any origin using Python SimpleHttpServer:
import SimpleHTTPServer
import SocketServer
PORT = 8000
class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_header("Access-Control-Allow-Origin", "*")
SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)
httpd = SocketServer.TCPServer(("", PORT), MyHTTPRequestHandler)
print "serving at port", PORT
httpd.serve_forever()
Still the error remains:
XMLHttpRequest cannot load https://abcd.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access.
I launch it by python -m SimpleHTTPServer 8000
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.