程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python builds a static web server

編輯:Python

The core is to use Python Of socket Realized ,socket The previous article has written , There are not too many comments here .

1. The local structures, python static state web The server

Open the command terminal in the resource directory , Enter the command :python -m http.server [ Port number ], Port number not written default 8000 that will do

Then type in the browser localhost:8000/ The resource path can access the page you want to visit

2. Returns the static of fixed data web The server

'''
Returns the static of fixed data web The server
'''
# The import module
import socket
# establish socket object
static_web_server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
static_web_server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True) # Set up port multiplexing
static_web_server_socket.bind(('',7777))
static_web_server_socket.listen(128)
# Receiving request ()
while True:
client,ip_port=static_web_server_socket.accept()
print(f' client {ip_port[0]} The use of port {ip_port[1]} Successful connection ...')
# Receive the request information from the client
request_data=client.recv(1024).decode('gbk')
print(request_data)
# Read resource content , No matter which file the client accesses , All that is returned is this file
with open('static/index.html','rb') as file:
file_content=file.read() # As a response
# Response line
response_line='HTTP/1.1 200 OK\r\n'
# Response head
response_header='Server: Tengine\r\nContent-Type: text/html; charset=UTF-8\r\nConnection: keep-alive\r\n'
# Splice corresponding messages ( Response line + Response head + Blank line + Response body ), Binary data is required
response_data=(response_line+response_header+'\r\n').encode('utf-8')+file_content
# Send message
client.send(response_data)
# Close the client connection
client.close()
print(f' client {ip_port[0]} Close the connection ')
# Shut down the server
static_web_server_socket.close()
print('Stop!')

3. Returns the static of the specified data web The server

'''
Returns the static of the specified data web The server
'''
import socket
def server_start(port):
web_server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
web_server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
web_server.bind(('',port))
web_server.listen(128)
while True:
client,ip_port=web_server.accept()
print(f' client {ip_port[0]} Use {ip_port[1]} Port connection successful ')
request_info=client.recv(1024).decode('gbk')
if len(request_info)==0:
client.close()
continue
# print(request_info)
resource_path=request_info.split()[1]
print(f'{ip_port[0]} The requested resource path is :{resource_path}')
if resource_path=='/':
resource_path='index.html'
try:
with open(f'static/{resource_path}','rb') as f:
response_body=f.read()
except Exception as e:
print(' The requested file does not exist , Please check ',e)
with open('static/404.html','rb') as f:
response_body=f.read()
response_line = 'HTTP/1.1 404 NOT FOUND\r\n'
else:
print(' Resource request succeeded !')
response_line='HTTP/1.1 200 OK'
finally:
response_header='Server:PSWS1.0\r\nContent-Type:text/html;Charset=UTF-8\r\n'
response_data=(response_line+response_header+'\r\n').encode()+response_body
client.send(response_data)
client.close()
if __name__ == '__main__':
server_start(7777)
print('Stop')

4. Multitasking static web The server

'''
Multitasking static web The server
'''
import socket
import multiprocessing
import threading
def server_start(port):
web_server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
web_server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
web_server.bind(('',port))
web_server.listen(128)
while True:
client,ip_port=web_server.accept()
# Multi process realizes multi task
# t=multiprocessing.Process(target=transit,args=(client,ip_port))
# t.daemon=True
# Multithreading for multitasking
t=threading.Thread(target=transit,args=(client,ip_port))
t.setDaemon(True)
t.start()
# Multithreaded no write , But multi process must write
# client.close()
# Unable to execute , It's OK not to write
web_server.close()
def transit(client,ip_port):
print(f' client {ip_port[0]} Use {ip_port[1]} Port connection successful ')
request_info = client.recv(1024).decode('gbk')
if len(request_info) == 0:
print(f'{ip_port[0]} Close the connection ')
client.close()
return
# print(request_info)
resource_path = request_info.split()[1]
print(f'{ip_port[0]} The requested resource path is :{resource_path}')
if resource_path == '/':
resource_path = 'index.html'
try:
with open(f'static/{resource_path}', 'rb') as f:
response_body = f.read()
except Exception as e:
print(' The requested file does not exist , Please check ', e)
with open('static/404.html', 'rb') as f:
response_body = f.read()
response_line = 'HTTP/1.1 404 NOT FOUND\r\n'
else:
print(' Resource request succeeded !')
response_line = 'HTTP/1.1 200 OK'
finally:
response_header = 'Server:PSWS1.0\r\nContent-Type:text/html;Charset=UTF-8\r\n'
response_data = (response_line + response_header + '\r\n').encode() + response_body
client.send(response_data)
client.close()
if __name__ == '__main__':
server_start(7777)
print('Stop')

5. Multitasking static web The server ( object-oriented )

'''
Multitasking static web The server ( object-oriented )
'''
import socket
# import multiprocessing
import threading
class WebServer(object):
def __init__(self,port):
self.web_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.web_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
self.web_server.bind(('', port))
self.web_server.listen(128)
def server_start(self):
while True:
client,ip_port=self.web_server.accept()
# Multi process realizes multi task
# t=multiprocessing.Process(target=self.transit,args=(client,ip_port))
# t.daemon=True
# Multithreading for multitasking
t=threading.Thread(target=self.transit,args=(client,ip_port))
t.setDaemon(True)
t.start()
# Multithreaded no write , But multi process must write
# client.close()
# Unable to execute , It's OK not to write
self.web_server.close()
def transit(self,client,ip_port):
print(f' client {ip_port[0]} Use {ip_port[1]} Port connection successful ')
request_info = client.recv(1024).decode('gbk')
if len(request_info) == 0:
print(f'{ip_port[0]} Close the connection ')
client.close()
return
# print(request_info)
resource_path = request_info.split()[1]
print(f'{ip_port[0]} The requested resource path is :{resource_path}')
if resource_path == '/':
resource_path = 'index.html'
try:
with open(f'static/{resource_path}', 'rb') as f:
response_body = f.read()
except Exception as e:
print(' The requested file does not exist , Please check ', e)
with open('static/error.html', 'rb') as f:
response_body = f.read()
response_line = 'HTTP/1.1 404 NOT FOUND\r\n'
else:
print(' Resource request succeeded !')
response_line = 'HTTP/1.1 200 OK'
finally:
response_header = 'Server:PSWS1.0\r\nContent-Type:text/html;Charset=UTF-8\r\n'
response_data = (response_line + response_header + '\r\n').encode() + response_body
client.send(response_data)
client.close()
if __name__ == '__main__':
WebServer(7777).server_start()

6. Multitasking static web The server ( Command line arguments )

Format :python( or python3) file name .py Parameters

'''
Multitasking static web The server ( Command line arguments )
python( or python3) file name .py Parameters
'''
import socket
# import multiprocessing
import threading
import sys
class WebServer(object):
def __init__(self,port):
self.web_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.web_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
self.web_server.bind(('', port))
self.web_server.listen(128)
def server_start(self):
while True:
client,ip_port=self.web_server.accept()
# Multi process realizes multi task
# t=multiprocessing.Process(target=self.transit,args=(client,ip_port))
# t.daemon=True
# Multithreading for multitasking
t=threading.Thread(target=self.transit,args=(client,ip_port))
t.setDaemon(True)
t.start()
# Multithreaded no write , But multi process must write
# client.close()
# Unable to execute , It's OK not to write
self.web_server.close()
def transit(self,client,ip_port):
print(f' client {ip_port[0]} Use {ip_port[1]} Port connection successful ')
request_info = client.recv(1024).decode('gbk')
if len(request_info) == 0:
print(f'{ip_port[0]} Close the connection ')
client.close()
return
# print(request_info)
resource_path = request_info.split()[1]
print(f'{ip_port[0]} The requested resource path is :{resource_path}')
if resource_path == '/':
resource_path = 'index.html'
try:
with open(f'static/{resource_path}', 'rb') as f:
response_body = f.read()
except Exception as e:
print(' The requested file does not exist , Please check ', e)
with open('static/404.html', 'rb') as f:
response_body = f.read()
response_line = 'HTTP/1.1 404 NOT FOUND\r\n'
else:
print(' Resource request succeeded !')
response_line = 'HTTP/1.1 200 OK'
finally:
response_header = 'Server:PSWS1.0\r\nContent-Type:text/html;Charset=UTF-8\r\n'
response_data = (response_line + response_header + '\r\n').encode() + response_body
client.send(response_data)
client.close()
if __name__ == '__main__':
if len(sys.argv)!=2:
print(' Please enter python3 file name .py Port number ')
else:
port=sys.argv[1]
if port.isdigit():
WebServer(int(port)).server_start()
else:
print(' The port number must be a number ')


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved