수색…


간단한 HTTP 서버 실행하기

파이썬 2.x 2.3
python -m SimpleHTTPServer 9000
Python 3.x 3.0
python -m http.server 9000

이 명령을 실행하면 현재 디렉토리의 파일을 포트 9000 합니다.

인수가 포트 번호로 제공되지 않으면 서버는 기본 포트 8000 에서 실행됩니다.

-m 플래그는 sys.path 에서 해당 .py 파일이 모듈로 실행되도록 검색합니다.

localhost에서만 서비스하려면 다음과 같은 사용자 정의 Python 프로그램을 작성해야합니다.

import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

HandlerClass = SimpleHTTPRequestHandler
ServerClass  = BaseHTTPServer.HTTPServer
Protocol     = "HTTP/1.0"

if sys.argv[1:]:
   port = int(sys.argv[1])
else:
   port = 8000
server_address = ('127.0.0.1', port)

HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)

sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()

파일 검색

다음 파일 디렉토리가 있다고 가정합니다.

여기에 이미지 설명을 입력하십시오.

다음과 같이 이들 파일을 제공하도록 웹 서버를 설정할 수 있습니다.

파이썬 2.x 2.3
import SimpleHTTPServer
import SocketServer

PORT = 8000

handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("localhost", PORT), handler)
print "Serving files at port {}".format(PORT)
httpd.serve_forever()
Python 3.x 3.0
import http.server
import socketserver

PORT = 8000

handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), handler)
print("serving at port", PORT)
httpd.serve_forever()

SocketServer 모듈은 네트워크 서버를 설정하는 데 필요한 클래스와 기능을 제공합니다.

SocketServerTCPServer 클래스는 TCP 프로토콜을 사용하여 서버를 설정합니다. 생성자는 서버 주소 (즉, IP 주소 및 포트)와 서버 요청을 처리하는 클래스를 나타내는 튜플을 허용합니다.

SimpleHTTPServer 모듈의 SimpleHTTPRequestHandler 클래스를 사용하면 현재 디렉토리의 파일을 제공 할 수 있습니다.

동일한 디렉토리에 스크립트를 저장하고 실행하십시오.

HTTP 서버 실행 :

파이썬 2.x 2.3

파이썬 -m SimpleHTTPServer 8000

Python 3.x 3.0

파이썬 -m http.server 8000

'-m'플래그는 해당 '.py'파일이 모듈로 실행되도록 'sys.path'를 검색합니다.

브라우저에서 localhost : 8000 을 열면 다음과 같이 표시됩니다.

여기에 이미지 설명을 입력하십시오.

SimpleHTTPServer의 프로그래밍 API

python -m SimpleHTTPServer 9000 실행하면 어떻게됩니까?

이 질문에 대답하려면 SimpleHTTPServer ( https://hg.python.org/cpython/file/2.7/Lib/SimpleHTTPServer.py) 및 BaseHTTPServer ( https://hg.python.org/cpython/file ) 의 구조를 이해해야합니다. /2.7/Lib/BaseHTTPServer.py) .

첫째, Python은 9000 을 인수로 사용하여 SimpleHTTPServer 모듈을 호출합니다. 이제 SimpleHTTPServer 코드를 살펴보면,

def test(HandlerClass = SimpleHTTPRequestHandler,
         ServerClass = BaseHTTPServer.HTTPServer):
    BaseHTTPServer.test(HandlerClass, ServerClass)


if __name__ == '__main__':
    test()

테스트 기능은 요청 핸들러와 ServerClass 다음에 호출됩니다. 이제 BaseHTTPServer.test가 호출되었습니다.

def test(HandlerClass = BaseHTTPRequestHandler,
         ServerClass = HTTPServer, protocol="HTTP/1.0"):
"""Test the HTTP request handler class.

This runs an HTTP server on port 8000 (or the first command line
argument).

"""

if sys.argv[1:]:
    port = int(sys.argv[1])
else:
    port = 8000
server_address = ('', port)

HandlerClass.protocol_version = protocol
httpd = ServerClass(server_address, HandlerClass)

sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()

따라서 사용자가 인수로 전달한 포트 번호가 구문 분석되어 호스트 주소에 바인딩됩니다. 주어진 포트와 프로토콜을 이용한 소켓 프로그래밍의 기본 단계가 수행됩니다. 마지막으로 소켓 서버가 시작됩니다.

다음은 SocketServer 클래스에서 다른 클래스로의 상속에 대한 기본적인 개요입니다.

    +------------+
    | BaseServer |
    +------------+
          |
          v
    +-----------+        +------------------+
    | TCPServer |------->| UnixStreamServer |
    +-----------+        +------------------+
          |
          v
    +-----------+        +--------------------+
    | UDPServer |------->| UnixDatagramServer |
    +-----------+        +--------------------+

https://hg.python.org/cpython/file/2.7/Lib/BaseHTTPServer.pyhttps://hg.python.org/cpython/file/2.7/Lib/SocketServer.py 링크는 더 많은 것을 찾는데 유용하다. 정보.

BaseHTTPRequestHandler를 사용하는 GET, POST, PUT의 기본 처리

# from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer # python2
from http.server import BaseHTTPRequestHandler, HTTPServer # python3
class HandleRequests(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        self.wfile.write("received get request")
        
    def do_POST(self):
        '''Reads post request body'''
        self._set_headers()
        content_len = int(self.headers.getheader('content-length', 0))
        post_body = self.rfile.read(content_len)
        self.wfile.write("received post request:<br>{}".format(post_body))

    def do_PUT(self):
        self.do_POST()

host = ''
port = 80
HTTPServer((host, port), HandleRequests).serve_forever()

curl 사용한 예제 출력 :

$ curl http://localhost/
received get request%                                                                                                                                                                                       

$ curl -X POST http://localhost/
received post request:<br>%                                                                                                                                                                                 

$ curl -X PUT http://localhost/
received post request:<br>%                                                                                                                                                                                 

$ echo 'hello world' | curl --data-binary @- http://localhost/
received post request:<br>hello world


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow