Giới thiệu
Web Server là gì?
Tổng quan
Web server là một máy tính lưu trữ những nội dung web.
Một máy chủ web dùng để phục vụ các trang web trên mạng internet hoặc mạng nội bộ.
Nó lưu trữ các
0 hay cácpython3 -m http.server + port[nếu không viết gì mặc định là 8000]
1 và sử dụng giao thứcpython3 -m http.server + port[nếu không viết gì mặc định là 8000]
2 để gửi các tệp đến trình duyệt web.python3 -m http.server + port[nếu không viết gì mặc định là 8000]
Một số máy chủ web nổi tiếng như : Nginx web server, Apache web server, IIS web server, Light Speed web server.Nginx web server, Apache web server, IIS web server, Light Speed web server.
Cách thức máy chủ web hoặc động.
Ví dụ người dùng muốn xem một trang web như
3, người dụng nhập url vào trình duyệt web với điều kiện người dùng cần kết nối Internet. Khi đó bộ giao thứcpython3 -m http.server + port[nếu không viết gì mặc định là 8000]
4 được sử dụng để thiết lập kết nối.python3 -m http.server + port[nếu không viết gì mặc định là 8000]
Khi kết nối được thiết lập, máy khách sẽ gửi một yêu cầu thông qua
2 và chờ phản hồi từ máy chủ. Phía bên kia máy chủ nhận được yêu cầu, xử lý yêu cầu, gửi lại phản hồi cho máy khách.python3 -m http.server + port[nếu không viết gì mặc định là 8000]
Giao thức HTTP
Giao thức
2 là viết tắt củapython3 -m http.server + port[nếu không viết gì mặc định là 8000]
7.python3 -m http.server + port[nếu không viết gì mặc định là 8000]
Nó là một giao thức ở tầng ứng dụng cho phép các ứng dụng web giao tiếp và trao đổi dữ liệu.
Nó là một giao thức dựa trên
4.python3 -m http.server + port[nếu không viết gì mặc định là 8000]
Nó được sử dụng để cung cấp nội dung:
9...python3 -m http.server + port[nếu không viết gì mặc định là 8000]
Sử dụng
2 là cách thuận tiện nhất để di chuyển dữ liệu nhanh chóng và đáng tin cậy trên web.python3 -m http.server + port[nếu không viết gì mặc định là 8000]
Ví dụ về HTTP message
Cách tạo HTTP Server bằng python
Python có một số thư viện được tích hợp để tạo một
DOCTYPE html>
Page Title
Sun* Cyber Security Research
1 dễ dàng hơn. Ví dụ bạn có thể tạo một DOCTYPE html>
Page Title
Sun* Cyber Security Research
2 với một câu lệnh đơn giản:- Với python2
python -m SimpleHTTPServer + port[nếu không viết gì mặc định là 8000]
- Với python3
python3 -m http.server + port[nếu không viết gì mặc định là 8000]
Nhưng bạn không thể custom server của bạn.
Tạo một Project HTTPServer
Tạo file HTML and CSS
DOCTYPE html>
Page Title
Sun* Cyber Security Research
@import url['//fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:100,200,300,400'];
body{
background-color: #222;
}
h2{
color: white;
padding: 20px 40px;
margin: 0 auto;
background-color: rgba[255, 255, 255, .7];
display: inline-block;
position: absolute;
top: 50%;
left: 50%;
transform: translateY[-50%] translateX[-50%];
border-radius: 4px;
border-bottom: 5px solid rgba[150, 150, 150, 1];
font-weight: 200;
font-family: 'IBM Plex Sans Condensed', sans-serif;
}
Thiết lập project
DOCTYPE html>
Page Title
Sun* Cyber Security Research
3from http.server import BaseHTTPRequestHandler
import os
class Server[BaseHTTPRequestHandler]:
def do_GET[self]:
if self.path == '/':
self.path = '/index.html'
try:
split_path = os.path.splitext[self.path]
request_extension = split_path[1]
if request_extension != ".py":
f = open[self.path[1:]].read[]
self.send_response[200]
self.end_headers[]
self.wfile.write[bytes[f, 'utf-8']]
else:
f = "File not found"
self.send_error[404,f]
except:
f = "File not found"
self.send_error[404,f]
from http.server import BaseHTTPRequestHandler
import os
BaseHTTPRequestHandler được sử dụng để xử lý các yêu cầu HTTP đến máy chủ. được sử dụng để xử lý các yêu cầu HTTP đến máy chủ.
Ngoài ra
4 còn hỗ trợ một số thuộc tính và phương thức sau:DOCTYPE html> Page Title Sun* Cyber Security Research
5: Phương thức này xử lý khi có yêu cầu GET gửi lên.DOCTYPE html> Page Title Sun* Cyber Security Research
6: Phương thức này xử lý khi có yêu cầu POST gửi lên.DOCTYPE html> Page Title Sun* Cyber Security Research
7: Thuộc tính này trả về path của request.DOCTYPE html> Page Title Sun* Cyber Security Research
8: Phương thức này trả về lỗi HTTP cho client.DOCTYPE html> Page Title Sun* Cyber Security Research
Đầu tiên định nghĩa một phương thứ
DOCTYPE html>
Page Title
Sun* Cyber Security Research
5. Phương thức này chạy khi có một yêu cầu GET gửi lên.self.path =='/' kiểm tra xem yêu cầu gửi lên có phải trang index hay không và nếu là trang
0 thì gán đường dẫn cho index self.path == '/index.html`. kiểm tra xem yêu cầu gửi lên có phải trang index hay không và nếu là trang@import url['//fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:100,200,300,400']; body{ background-color: #222; } h2{ color: white; padding: 20px 40px; margin: 0 auto; background-color: rgba[255, 255, 255, .7]; display: inline-block; position: absolute; top: 50%; left: 50%; transform: translateY[-50%] translateX[-50%]; border-radius: 4px; border-bottom: 5px solid rgba[150, 150, 150, 1]; font-weight: 200; font-family: 'IBM Plex Sans Condensed', sans-serif; }
0 thì gán đường dẫn cho index self.path == '/index.html`.@import url['//fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:100,200,300,400']; body{ background-color: #222; } h2{ color: white; padding: 20px 40px; margin: 0 auto; background-color: rgba[255, 255, 255, .7]; display: inline-block; position: absolute; top: 50%; left: 50%; transform: translateY[-50%] translateX[-50%]; border-radius: 4px; border-bottom: 5px solid rgba[150, 150, 150, 1]; font-weight: 200; font-family: 'IBM Plex Sans Condensed', sans-serif; }
Tiếp theo cố gắng đọc các tệp mà người dùng đang cố truy cập ngoại trừ những
1 tránh làm lộ@import url['//fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:100,200,300,400']; body{ background-color: #222; } h2{ color: white; padding: 20px 40px; margin: 0 auto; background-color: rgba[255, 255, 255, .7]; display: inline-block; position: absolute; top: 50%; left: 50%; transform: translateY[-50%] translateX[-50%]; border-radius: 4px; border-bottom: 5px solid rgba[150, 150, 150, 1]; font-weight: 200; font-family: 'IBM Plex Sans Condensed', sans-serif; }
2.@import url['//fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:100,200,300,400']; body{ background-color: #222; } h2{ color: white; padding: 20px 40px; margin: 0 auto; background-color: rgba[255, 255, 255, .7]; display: inline-block; position: absolute; top: 50%; left: 50%; transform: translateY[-50%] translateX[-50%]; border-radius: 4px; border-bottom: 5px solid rgba[150, 150, 150, 1]; font-weight: 200; font-family: 'IBM Plex Sans Condensed', sans-serif; }
Nếu tập tin yêu cầu được tìm thấy thì server gửi phản hồi
3.@import url['//fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:100,200,300,400']; body{ background-color: #222; } h2{ color: white; padding: 20px 40px; margin: 0 auto; background-color: rgba[255, 255, 255, .7]; display: inline-block; position: absolute; top: 50%; left: 50%; transform: translateY[-50%] translateX[-50%]; border-radius: 4px; border-bottom: 5px solid rgba[150, 150, 150, 1]; font-weight: 200; font-family: 'IBM Plex Sans Condensed', sans-serif; }
3 là phản hồi mà bất cứ khi nào bạn truy cập thành công một trang web.@import url['//fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:100,200,300,400']; body{ background-color: #222; } h2{ color: white; padding: 20px 40px; margin: 0 auto; background-color: rgba[255, 255, 255, .7]; display: inline-block; position: absolute; top: 50%; left: 50%; transform: translateY[-50%] translateX[-50%]; border-radius: 4px; border-bottom: 5px solid rgba[150, 150, 150, 1]; font-weight: 200; font-family: 'IBM Plex Sans Condensed', sans-serif; }
Nếu tập tin yêu cầu không được tìm thấy thì
5 gửi một mã lỗi tập tin yêu cầu không hợp lệ.@import url['//fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:100,200,300,400']; body{ background-color: #222; } h2{ color: white; padding: 20px 40px; margin: 0 auto; background-color: rgba[255, 255, 255, .7]; display: inline-block; position: absolute; top: 50%; left: 50%; transform: translateY[-50%] translateX[-50%]; border-radius: 4px; border-bottom: 5px solid rgba[150, 150, 150, 1]; font-weight: 200; font-family: 'IBM Plex Sans Condensed', sans-serif; }
Sử dụng phương thức
6 encode@import url['//fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:100,200,300,400']; body{ background-color: #222; } h2{ color: white; padding: 20px 40px; margin: 0 auto; background-color: rgba[255, 255, 255, .7]; display: inline-block; position: absolute; top: 50%; left: 50%; transform: translateY[-50%] translateX[-50%]; border-radius: 4px; border-bottom: 5px solid rgba[150, 150, 150, 1]; font-weight: 200; font-family: 'IBM Plex Sans Condensed', sans-serif; }
7 để chuyển đổi dạng văn bản sang bytes.@import url['//fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:100,200,300,400']; body{ background-color: #222; } h2{ color: white; padding: 20px 40px; margin: 0 auto; background-color: rgba[255, 255, 255, .7]; display: inline-block; position: absolute; top: 50%; left: 50%; transform: translateY[-50%] translateX[-50%]; border-radius: 4px; border-bottom: 5px solid rgba[150, 150, 150, 1]; font-weight: 200; font-family: 'IBM Plex Sans Condensed', sans-serif; }
@import url['//fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:100,200,300,400'];
body{
background-color: #222;
}
h2{
color: white;
padding: 20px 40px;
margin: 0 auto;
background-color: rgba[255, 255, 255, .7];
display: inline-block;
position: absolute;
top: 50%;
left: 50%;
transform: translateY[-50%] translateX[-50%];
border-radius: 4px;
border-bottom: 5px solid rgba[150, 150, 150, 1];
font-weight: 200;
font-family: 'IBM Plex Sans Condensed', sans-serif;
}
8import time
from http.server import HTTPServer
from server import Server
HOST_NAME = 'localhost'
PORT = 8000
if __name__ == "__main__":
httpd = HTTPServer[[HOST_NAME,PORT],Server]
print[time.asctime[], "Start Server - %s:%s"%[HOST_NAME,PORT]]
try:
httpd.serve_forever[]
except KeyboardInterrupt:
pass
httpd.server_close[]
print[time.asctime[],'Stop Server - %s:%s' %[HOST_NAME,PORT]]
import time
from http.server import HTTPServer
from server import Server
time sử dụng để kiếm soát thời gian
9 và@import url['//fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:100,200,300,400']; body{ background-color: #222; } h2{ color: white; padding: 20px 40px; margin: 0 auto; background-color: rgba[255, 255, 255, .7]; display: inline-block; position: absolute; top: 50%; left: 50%; transform: translateY[-50%] translateX[-50%]; border-radius: 4px; border-bottom: 5px solid rgba[150, 150, 150, 1]; font-weight: 200; font-family: 'IBM Plex Sans Condensed', sans-serif; }
0 server. sử dụng để kiếm soát thời gianfrom http.server import BaseHTTPRequestHandler import os class Server[BaseHTTPRequestHandler]: def do_GET[self]: if self.path == '/': self.path = '/index.html' try: split_path = os.path.splitext[self.path] request_extension = split_path[1] if request_extension != ".py": f = open[self.path[1:]].read[] self.send_response[200] self.end_headers[] self.wfile.write[bytes[f, 'utf-8']] else: f = "File not found" self.send_error[404,f] except: f = "File not found" self.send_error[404,f]
9 và@import url['//fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:100,200,300,400']; body{ background-color: #222; } h2{ color: white; padding: 20px 40px; margin: 0 auto; background-color: rgba[255, 255, 255, .7]; display: inline-block; position: absolute; top: 50%; left: 50%; transform: translateY[-50%] translateX[-50%]; border-radius: 4px; border-bottom: 5px solid rgba[150, 150, 150, 1]; font-weight: 200; font-family: 'IBM Plex Sans Condensed', sans-serif; }
0 server.from http.server import BaseHTTPRequestHandler import os class Server[BaseHTTPRequestHandler]: def do_GET[self]: if self.path == '/': self.path = '/index.html' try: split_path = os.path.splitext[self.path] request_extension = split_path[1] if request_extension != ".py": f = open[self.path[1:]].read[] self.send_response[200] self.end_headers[] self.wfile.write[bytes[f, 'utf-8']] else: f = "File not found" self.send_error[404,f] except: f = "File not found" self.send_error[404,f]
HTTPServer là một lớp con socketserver.TCPServer nó tạo và lắng nghe HTTP socket, gửi yêu cầu đến bộ xử lý. là một lớp con socketserver.TCPServer nó tạo và lắng nghe HTTP socket, gửi yêu cầu đến bộ xử lý.
Cấu hình máy chủ với 2 hằng số
from http.server import BaseHTTPRequestHandler
import os
class Server[BaseHTTPRequestHandler]:
def do_GET[self]:
if self.path == '/':
self.path = '/index.html'
try:
split_path = os.path.splitext[self.path]
request_extension = split_path[1]
if request_extension != ".py":
f = open[self.path[1:]].read[]
self.send_response[200]
self.end_headers[]
self.wfile.write[bytes[f, 'utf-8']]
else:
f = "File not found"
self.send_error[404,f]
except:
f = "File not found"
self.send_error[404,f]
1 với from http.server import BaseHTTPRequestHandler
import os
class Server[BaseHTTPRequestHandler]:
def do_GET[self]:
if self.path == '/':
self.path = '/index.html'
try:
split_path = os.path.splitext[self.path]
request_extension = split_path[1]
if request_extension != ".py":
f = open[self.path[1:]].read[]
self.send_response[200]
self.end_headers[]
self.wfile.write[bytes[f, 'utf-8']]
else:
f = "File not found"
self.send_error[404,f]
except:
f = "File not found"
self.send_error[404,f]
2 dùng để chạy máy chủ trên localhost và from http.server import BaseHTTPRequestHandler
import os
class Server[BaseHTTPRequestHandler]:
def do_GET[self]:
if self.path == '/':
self.path = '/index.html'
try:
split_path = os.path.splitext[self.path]
request_extension = split_path[1]
if request_extension != ".py":
f = open[self.path[1:]].read[]
self.send_response[200]
self.end_headers[]
self.wfile.write[bytes[f, 'utf-8']]
else:
f = "File not found"
self.send_error[404,f]
except:
f = "File not found"
self.send_error[404,f]
3 là cổng mà để chạy ứng dụng.from http.server import BaseHTTPRequestHandler
import os
class Server[BaseHTTPRequestHandler]:
def do_GET[self]:
if self.path == '/':
self.path = '/index.html'
try:
split_path = os.path.splitext[self.path]
request_extension = split_path[1]
if request_extension != ".py":
f = open[self.path[1:]].read[]
self.send_response[200]
self.end_headers[]
self.wfile.write[bytes[f, 'utf-8']]
else:
f = "File not found"
self.send_error[404,f]
except:
f = "File not found"
self.send_error[404,f]
4- Gọi HTTPServer mà python cung cấp với đối số thứ nhất là một cặp
5 và đối số thứ 2 là một classfrom http.server import BaseHTTPRequestHandler import os class Server[BaseHTTPRequestHandler]: def do_GET[self]: if self.path == '/': self.path = '/index.html' try: split_path = os.path.splitext[self.path] request_extension = split_path[1] if request_extension != ".py": f = open[self.path[1:]].read[] self.send_response[200] self.end_headers[] self.wfile.write[bytes[f, 'utf-8']] else: f = "File not found" self.send_error[404,f] except: f = "File not found" self.send_error[404,f]
6 để xử lý đã được thiết lập trước đó.HTTPServer mà python cung cấp với đối số thứ nhất là một cặpfrom http.server import BaseHTTPRequestHandler import os class Server[BaseHTTPRequestHandler]: def do_GET[self]: if self.path == '/': self.path = '/index.html' try: split_path = os.path.splitext[self.path] request_extension = split_path[1] if request_extension != ".py": f = open[self.path[1:]].read[] self.send_response[200] self.end_headers[] self.wfile.write[bytes[f, 'utf-8']] else: f = "File not found" self.send_error[404,f] except: f = "File not found" self.send_error[404,f]
5 và đối số thứ 2 là một classfrom http.server import BaseHTTPRequestHandler import os class Server[BaseHTTPRequestHandler]: def do_GET[self]: if self.path == '/': self.path = '/index.html' try: split_path = os.path.splitext[self.path] request_extension = split_path[1] if request_extension != ".py": f = open[self.path[1:]].read[] self.send_response[200] self.end_headers[] self.wfile.write[bytes[f, 'utf-8']] else: f = "File not found" self.send_error[404,f] except: f = "File not found" self.send_error[404,f]
6 để xử lý đã được thiết lập trước đó.from http.server import BaseHTTPRequestHandler import os class Server[BaseHTTPRequestHandler]: def do_GET[self]: if self.path == '/': self.path = '/index.html' try: split_path = os.path.splitext[self.path] request_extension = split_path[1] if request_extension != ".py": f = open[self.path[1:]].read[] self.send_response[200] self.end_headers[] self.wfile.write[bytes[f, 'utf-8']] else: f = "File not found" self.send_error[404,f] except: f = "File not found" self.send_error[404,f]
try:
httpd.serve_forever[]
except KeyboardInterrupt:
pass
httpd.server_close[]
print[time.asctime[],'Stop Server - %s:%s' %[HOST_NAME,PORT]]
- Khối tiếp theo để
9 và@import url['//fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:100,200,300,400']; body{ background-color: #222; } h2{ color: white; padding: 20px 40px; margin: 0 auto; background-color: rgba[255, 255, 255, .7]; display: inline-block; position: absolute; top: 50%; left: 50%; transform: translateY[-50%] translateX[-50%]; border-radius: 4px; border-bottom: 5px solid rgba[150, 150, 150, 1]; font-weight: 200; font-family: 'IBM Plex Sans Condensed', sans-serif; }
0 server, khi nhận được tín hiệu ngắt từ bàn phím server sẽ đóng kết nối vớifrom http.server import BaseHTTPRequestHandler import os class Server[BaseHTTPRequestHandler]: def do_GET[self]: if self.path == '/': self.path = '/index.html' try: split_path = os.path.splitext[self.path] request_extension = split_path[1] if request_extension != ".py": f = open[self.path[1:]].read[] self.send_response[200] self.end_headers[] self.wfile.write[bytes[f, 'utf-8']] else: f = "File not found" self.send_error[404,f] except: f = "File not found" self.send_error[404,f]
9.from http.server import BaseHTTPRequestHandler import os class Server[BaseHTTPRequestHandler]: def do_GET[self]: if self.path == '/': self.path = '/index.html' try: split_path = os.path.splitext[self.path] request_extension = split_path[1] if request_extension != ".py": f = open[self.path[1:]].read[] self.send_response[200] self.end_headers[] self.wfile.write[bytes[f, 'utf-8']] else: f = "File not found" self.send_error[404,f] except: f = "File not found" self.send_error[404,f]
Bây giờ chúng ta start server bằng cách chạy lệnh:
python3 main.py
Mở trình duyệt nhập url //localhost:8000//localhost:8000
Và đây là phản hồi từ phía máy chủ:
Vậy là chúng ta đã tạo thành công được một HTTP Server đơn giản với python, ngoài ra chúng ta còn có thể viết thêm các phương thức như
from http.server import BaseHTTPRequestHandler
import os
0 để cho Server có thể xử lý nhiều phương thức hơn.HTTP Server đơn giản với python, ngoài ra chúng ta còn có thể viết thêm các phương thức như from http.server import BaseHTTPRequestHandler
import os
0 để cho Server có thể xử lý nhiều phương thức hơn.Tài liệu
//docs.python.org/3/library/http.server.html