Python_Web-静的サーバ
30933 ワード
非ブロックネットワークIO非ブロックの特徴:データが来ない場合、現在のプロセス待機をブロックするのではなく、異常(ソケット.setblocking(False)) を報告する.
IO多重化多重IOの利点は、単一のprocessで複数のネットワーク接続を同時に処理できるIO である.の特徴:1つのプロセスが複数のファイル記述子を同時に待つことができるメカニズムによって、これらのファイル記述(ソケット記述子)のいずれかが読み取り準備完了状態に入ると、epoll()関数は に戻ることができる. epollはLinuxでのみ を使用できます. EPOLLIN(読み取り可能) EPOLLOUT(書き込み可能) EPOLLET(ETモード) 水平トリガとエッジトリガ LT(level trigger):データが存在する場合、 に通知されます. ET(edge trigger):データが到着した瞬間にのみ を通知する
ファイル記述子ファイル記述子は、プロセス内部に所有するファイルリソースの記述のシンボルであり、シンボルレス整数(0,1,2...) である.プログラムのデフォルト起動標準入力、標準出力、標準エラーsockを起動する.fileno()
Webサーバ-マルチスレッド
Webサーバ-マルチプロセス
Webサーバ-オブジェクト向け
Webサーバ-コパス
Webサーバ-コマンドラインパラメータ制御ポート
IO多重化
ファイル記述子
Webサーバ-マルチスレッド
import socket
import threading
def request_handler(client_socket):
""" """
#
recv_data = client_socket.recv(1024)
if not recv_data:
print(" ")
client_socket.close()
return
#
recv_str_data = recv_data.decode()
# --> , 0 GET /index2.html HTTP/1.1\r
request_line = recv_str_data.split("\r
")[0]
# /index2.html
path_info = request_line.split(" ")[1]
if path_info == "/":
path_info = "/index.html"
try:
# # ,
# f = open("./static" + path_info, "rb")
# #
# #
# ret = f.read()
# f.close()
# with -->
# socket
# static ( ),
with open("./static" + path_info, "rb") as f:
#
ret = f.read()
except Exception as e:
response_line = "HTTP/1.1 404 NOt Found\r
"
response_header = "Server: PythonServer2.0\r
"
response_body = "ERROR"
response_data = response_line + response_header + "\r
" + response_body
client_socket.send(response_data.encode())
else:
# \r
#
response_line = "HTTP/1.1 200 OK\r
"
#
response_header = "Server: PythonServer1.0\r
"
#
request_body = ret
#
data = (response_line + response_header + "\r
").encode() + request_body
#
client_socket.send(data)
finally:
#
client_socket.close()
if __name__ == '__main__':
#
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# (1. 0. )
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#
server_socket.bind(("", 8888))
#
server_socket.listen(128)
while True:
#
client_socket, client_address = server_socket.accept()
print(" %s " % str(client_address))
# request_handler(client_socket)
#
#
thd = threading.Thread(target=request_handler, args=(client_socket, ))
thd.start()
Webサーバ-マルチプロセス
import socket
import multiprocessing
def request_handler(client_socket):
""" """
#
recv_data = client_socket.recv(1024)
if not recv_data:
print(" ")
client_socket.close()
return
#
recv_str_data = recv_data.decode()
# --> , 0 GET /index2.html HTTP/1.1\r
request_line = recv_str_data.split("\r
")[0]
# /index2.html
path_info = request_line.split(" ")[1]
if path_info == "/":
path_info = "/index.html"
try:
# # ,
# f = open("./static" + path_info, "rb")
# #
# #
# ret = f.read()
# f.close()
# with -->
# socket
# static ( ),
with open("./static" + path_info, "rb") as f:
#
ret = f.read()
except Exception as e:
response_line = "HTTP/1.1 404 NOt Found\r
"
response_header = "Server: PythonServer2.0\r
"
response_body = "ERROR"
response_data = response_line + response_header + "\r
" + response_body
client_socket.send(response_data.encode())
else:
# \r
#
response_line = "HTTP/1.1 200 OK\r
"
#
response_header = "Server: PythonServer1.0\r
"
#
request_body = ret
#
data = (response_line + response_header + "\r
").encode() + request_body
#
client_socket.send(data)
finally:
#
client_socket.close()
if __name__ == '__main__':
#
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# (1. 0. )
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#
server_socket.bind(("", 8888))
#
server_socket.listen(128)
while True:
#
client_socket, client_address = server_socket.accept()
print(" %s " % str(client_address))
# request_handler(client_socket)
#
#
pro = multiprocessing.Process(target=request_handler, args=(client_socket,))
pro.start()
# , ,
#
client_socket.close()
Webサーバ-オブジェクト向け
import socket
import multiprocessing
class HTTPServer(object):
def __init__(self):
""" """
#
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# (1. 0. )
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#
server_socket.bind(("", 8888))
#
server_socket.listen(128)
self.server_socket = server_socket
def request_handler(self, client_socket):
""" """
#
recv_data = client_socket.recv(1024)
if not recv_data:
print(" ")
client_socket.close()
return
#
recv_str_data = recv_data.decode()
# --> , 0 GET /index2.html HTTP/1.1\r
request_line = recv_str_data.split("\r
")[0]
# /index2.html
path_info = request_line.split(" ")[1]
if path_info == "/":
path_info = "/index.html"
try:
# # ,
# f = open("./static" + path_info, "rb")
# #
# #
# ret = f.read()
# f.close()
# with -->
# socket
# static ( ),
with open("./static" + path_info, "rb") as f:
#
ret = f.read()
except Exception as e:
response_line = "HTTP/1.1 404 NOt Found\r
"
response_header = "Server: PythonServer2.0\r
"
response_body = "ERROR"
response_data = response_line + response_header + "\r
" + response_body
client_socket.send(response_data.encode())
else:
# \r
#
response_line = "HTTP/1.1 200 OK\r
"
#
response_header = "Server: PythonServer1.0\r
"
#
request_body = ret
#
data = (response_line + response_header + "\r
").encode() + request_body
#
client_socket.send(data)
finally:
#
client_socket.close()
def start(self):
while True:
#
client_socket, client_address = self.server_socket.accept()
print(" %s " % str(client_address))
# request_handler(client_socket)
#
#
pro = multiprocessing.Process(target=self.request_handler, args=(client_socket,))
pro.start()
# , ,
#
client_socket.close()
if __name__ == '__main__':
# web
hs = HTTPServer()
#
hs.start()
Webサーバ-コパス
from gevent import monkey
monkey.patch_all()
import gevent
import socket
class HTTPServer(object):
def __init__(self):
""" """
#
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# (1. 0. )
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#
server_socket.bind(("", 8888))
#
server_socket.listen(128)
self.server_socket = server_socket
def request_handler(self, client_socket):
""" """
#
recv_data = client_socket.recv(1024)
if not recv_data:
print(" ")
client_socket.close()
return
#
recv_str_data = recv_data.decode()
# --> , 0 GET /index2.html HTTP/1.1\r
request_line = recv_str_data.split("\r
")[0]
# /index2.html
path_info = request_line.split(" ")[1]
if path_info == "/":
path_info = "/index.html"
try:
# # ,
# f = open("./static" + path_info, "rb")
# #
# #
# ret = f.read()
# f.close()
# with -->
# socket
# static ( ),
with open("./static" + path_info, "rb") as f:
#
ret = f.read()
except Exception as e:
response_line = "HTTP/1.1 404 NOt Found\r
"
response_header = "Server: PythonServer2.0\r
"
response_body = "ERROR"
response_data = response_line + response_header + "\r
" + response_body
client_socket.send(response_data.encode())
else:
# \r
#
response_line = "HTTP/1.1 200 OK\r
"
#
response_header = "Server: PythonServer1.0\r
"
#
request_body = ret
#
data = (response_line + response_header + "\r
").encode() + request_body
#
client_socket.send(data)
finally:
#
client_socket.close()
def start(self):
while True:
#
client_socket, client_address = self.server_socket.accept()
print(" %s " % str(client_address))
#
gevent.spawn(self.request_handler, client_socket)
if __name__ == '__main__':
# web
hs = HTTPServer()
#
hs.start()
Webサーバ-コマンドラインパラメータ制御ポート
from gevent import monkey
monkey.patch_all()
import socket
import gevent
import sys
class HTTPServer(object):
def __init__(self,port):
""" """
#
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 1 0
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#
server_socket.bind(('', port))
#
server_socket.listen(128)
self.server_socket = server_socket
def request_handler(self, client_socket):
""" """
#
recv_data = client_socket.recv(4096)
if not recv_data:
print(" ")
client_socket.close()
return #
#
recv_str_data = recv_data.decode()
# ---->
data_list = recv_str_data.split('\r
')
# print(data_list)
# 0 GET /index.html HTTP/1.1
request_line = data_list[0]
# print(request_line)
#
path_info = request_line.split(" ")[1]
# /index.html /home/python/1.txt
#
# ./static + /index.html
print(path_info)
# (IP) + [ ] /
if path_info == '/':
path_info = '/index.html'
try:
# #
# file = open("./static" + path_info, "rb")
# #
#
# #
# file_data = file.read()
#
# file.close()
# with ---->
# socket
# static ( ),
with open("./static" + path_info, "rb") as file:
#
file_data = file.read()
except Exception as e:
response_line = "HTTP/1.1 404 Not Found\r
"
response_header = "Server: PythonServer2.0\r
"
response_body = "ERROR"
response_data = response_line + response_header + "\r
" + response_body
client_socket.send(response_data.encode())
else:
# \r
#
response_line = "HTTP/1.1 200 OK\r
"
#
response_header = "Server: PythonServer2.0\r
"
#
response_body = file_data
# HTTP
response_data = (response_line + response_header + "\r
").encode() + response_body
# send sendall
# client_socket.send(response_data)
client_socket.sendall(response_data)
finally:
#
client_socket.close()
def start(self):
while True:
#
client_socket, client_addr = self.server_socket.accept()
print(" %s " % str(client_addr))
#
# request_handler(client_socket)
#
gevent.spawn(self.request_handler, client_socket)
def main():
# python3 web.py
# sys.argv
if len(sys.argv) != 2:
print(" ")
return
# print(sys.argv)
port = sys.argv[1]
if not port.isdigit():
print(" ")
return
port_number = int(port)
# web
httpserver = HTTPServer(port_number)
# web
httpserver.start()
if __name__ == '__main__':
main()