python web服务器(一)

# coding=utf-8
'''
Created on 2015-7-20
@author: xhw
@explain: 实现GET方法和POST方法请求
'''
from  BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import urllib


class ServerHTTP(BaseHTTPRequestHandler):
    def do_GET(self):
        path = self.path
        print path
        # 拆分url(也可根据拆分的url获取Get提交才数据),可以将不同的path和参数加载不同的html页面,或调用不同的方法返回不同的数据,来实现简单的网站或接口
        query = urllib.splitquery(path)
        print query
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.send_header("test", "This is test!")
        self.end_headers()
        buf = '''<!DOCTYPE HTML>
                <html>
                <head><title>Get page</title></head>
                <body>

                <form action="post_page" method="post">
                  username: <input type="text" name="username" /><br />
                  password: <input type="text" name="password" /><br />
                  <input type="submit" value="POST" />
                </form>

                </body>
                </html>'''
        self.wfile.write(buf)

    def do_POST(self):
        path = self.path
        print path
        # 获取post提交的数据
        datas = self.rfile.read(int(self.headers['content-length']))
        datas = urllib.unquote(datas).decode("utf-8", 'ignore')

        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.send_header("test", "This is test!")
        self.end_headers()
        buf = '''<!DOCTYPE HTML>
        <html>
            <head><title>Post page</title></head>
            <body>Post Data:%s  <br />Path:%s</body>
        </html>''' % (datas, self.path)
        self.wfile.write(buf)


def start_server(port):
    http_server = HTTPServer(('', int(port)), ServerHTTP)
    http_server.serve_forever()


if __name__ == "__main__":
    start_server(8000)

在浏览器输入:http://127.0.0.1:8000 即可出现界面。

点击“检查”,查看network:可以看到response Headers 为:

HTTP/1.0 200 OK

Server: BaseHTTP/0.3 Python/2.7.14

Date: Thu, 26 Jul 2018 08:54:40 GMT

Content-type: text/html

test: This is test!

2.利用socket创建web服务器:

#coding=utf-8
import socket

from multiprocessing import Process

HTML_ROOT_DIR = ""


def handle_client(client_socket):
    '''
    处理客户端请求
    '''
    #获取客户端数据
    request_data = client_socket.recv(1024)
    print 'request_data:',request_data

    #构造响应数据
    response_start_line = 'HTTP/1.1 200 ok\r\n'
    response_head = 'Server:My server\r\n'
    response_body = 'hello nanxiaoting'
    response = response_start_line + response_head + '\r\n' + response_body
    print 'response:',response

    #向客户端返回响应数据
    #client_socket.send(bytes(response,'utf-8'))   #python3
    client_socket.send(bytes(response.encode))   #python2

    #关闭客户端连接
    client_socket.close()

if __name__ == "__main__":
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(('', 8000))
    server_socket.listen(128)

    while(1):
        client_socket,client_address = server_socket.accept()
        print "[%s,%s]用户连接上了" % client_address
        handele_client_process = Process(target=handle_client,args=(client_socket,))
        handele_client_process.start()
        client_socket.close()



在浏览器输入:http://127.0.0.1:8000

这时,会在pycharm运行出结果:

[127.0.0.1,45214]用户连接上了
[127.0.0.1,45216]用户连接上了
request_data: GET / HTTP/1.1
Host: 127.0.0.1:8000
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9


response: HTTP/1.1 200 ok
Server:My server

hello nanxiaoting

由于才开始接触web服务,对这个理解不是很深,这个程序相当于为服务器。而我们的浏览器相当于客户端,发送请求。在后期,我们可以自己编写测试程序,就是扮演浏览器客户端的角色。

3.静态文件的web服务器代码

#coding=utf-8
import socket
import re

from multiprocessing import Process
'''
静态文件的web服务器代码
'''

#常量所有的字母必须大写,设置静态文件根目录
HTML_ROOT_DIR = "./"


def handle_client(client_socket):
    '''
    处理客户端请求
    '''
    #获取客户端数据
    request_data = client_socket.recv(1024)
    print 'request_data:',request_data
    request_lines = request_data.splitlines()
    for line in request_lines:
        print 'line:',line

    #GET / HTTP/1.1
    request_start_line = request_lines[0]
    print 'request_start_line:',request_start_line
    #提取用户请求的文件名
    file_name = re.match(r"\w+ +/([^ ]*) ",request_start_line).group(1)
    print 'file_name:',file_name

    if '/' == '/index.html':
        file_name = '/index.html'

    #打开文件,读取内容
    try:
        file = open(HTML_ROOT_DIR + file_name,'rb')
        print 'file:',file
    except IOError:
        response_start_line = 'HTTP/1.1 404 not found\r\n'
        response_head = 'Server:My server\r\n'
        response_body = 'The file is not found'  # !!!!!!
    else:
        file_data = file.read()
        file.close()
        # 构造响应数据
        response_start_line = 'HTTP/1.1 200 ok\r\n'
        response_head = 'Server:My server\r\n'
        response_body = file_data  # !!!!!!
    finally:
        response = response_start_line + response_head + '\r\n' + response_body
        print 'response:', response

    #向客户端返回响应数据
    #client_socket.send(bytes(response,'utf-8'))   #python3
    client_socket.send(bytes(response.encode))   #python2

    #关闭客户端连接
    client_socket.close()

if __name__ == "__main__":
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)  #可重复利用,不然重新运行,显示端口已被占用
    server_socket.bind(('', 8000))
    server_socket.listen(128)

    while(1):
        client_socket,client_address = server_socket.accept()
        print "[%s,%s]用户连接上了" % client_address
        handele_client_process = Process(target=handle_client,args=(client_socket,))
        handele_client_process.start()
        client_socket.close()



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My web</title>
</head>
<body>
     <h1>hi</h1>
     <p1>hello world</p1>

</body>
</html>

在浏览器输入:http://127.0.0.1:8000/index.html

在pycharm下运行结果为:

[127.0.0.1,53972]用户连接上了
[127.0.0.1,53974]用户连接上了
request_data: GET /index.html HTTP/1.1
Host: 127.0.0.1:8000
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9


line: GET /index.html HTTP/1.1
line: Host: 127.0.0.1:8000
line: Connection: keep-alive
line: Cache-Control: max-age=0
line: Upgrade-Insecure-Requests: 1
line: User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36
line: Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
line: Accept-Encoding: gzip, deflate, br
line: Accept-Language: zh-CN,zh;q=0.9
line: 
request_start_line: GET /index.html HTTP/1.1
file_name: index.html
file: <open file './index.html', mode 'rb' at 0x7f1ddbec99c0>
response: HTTP/1.1 200 ok
Server:My server

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My web</title>
</head>
<body>
     <h1>hi</h1>
     <p1>hello world</p1>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/nanxiaoting/article/details/81203281