Python:编写HTTP Server处理GET请求

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

##代码:

下面代码修改自http://www.binarytides.com/python-socket-server-code-example/,支持GET请求这一部分是自己写的。

# coding: UTF-8

import socket
import sys

HOST = ''   # Symbolic name, meaning all available interfaces
PORT = 8000  # Arbitrary non-privileged port

socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # 避免出现端口占用的错误
print 'Socket created'

# Bind socket to local host and port
try:
    socket_server.bind((HOST, PORT))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

# Start listening on socket
socket_server.listen(10)
print 'Socket now listening'

# now keep talking with the client
while 1:
    # wait to accept a connection - blocking call
    conn, addr = socket_server.accept()
    conn.setblocking(False)  # 非阻塞,接收数据需要try...except...
    print 'Connected with ' + addr[0] + ':' + str(addr[1])
    # Receiving from client
    data = ''
    response = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n'
    while True:
        if '\r\n\r\n' in data:  # 如果是POST方法,还要继续接收数据;如果含有图片,会更麻烦
            break
        try:
            data += conn.recv(1024)
        except:
            pass

    print '接收的数据->start'
    print data
    print '接收的数据->end'
    print '向客户端发送数据:'
    conn.sendall(response+'''

Hi

''') print '发送完毕,关闭该连接' conn.close() # 别忘了 socket_server.close()

可以在浏览器中访问http://127.0.0.1:8000/,或者curl:

letian $ curl -i http://127.0.0.1:8000
HTTP/1.1 200 OK
Content-Type: text/html

Hi

对于GET方法,接收完请求头后,分析一下请求头,生成数据返回即可。

对于POST方法,接收完请求头,需要在请求头中找Content-Length,然后继续接收Content-Length制订长度的数据。

可用的HTTP server还需要多线程、epoll等来完善。Code a simple socket server in Python给出了示例。

##资料 Code a simple socket server in Python
A simple Python webserver
Simple Python HTTP server using sockets
用Python socket 实现一个简单的http服务器(post 与get 的区别)、CGI、WSGI、MVC
17.2. socket — Low-level networking interface
HTTP Headers for Dummies
How are parameters sent in an HTTP POST request?

转载于:https://my.oschina.net/letiantian/blog/423892

你可能感兴趣的:(Python:编写HTTP Server处理GET请求)