Python入门教程: Socket中Get/Post方法连用

可以直接用浏览器测试, 或者用curl

curl -d 'input=Input data' -X POST localhost:8000

Python 源码

#/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import sys
import requests

HOST, PORT = '', 8000


class Util():
    def dealConnection(self, conn):
        request = conn.recv(1024)

        print ''.join('> {line}\n'.format(line=line)
                      for line in request.splitlines())

        data = request.split('\r\n\r\n')
        headers = data[0].splitlines()
        body = data[1]
        header = headers[0].rstrip('\r\n')
        method, url, protcl = header.split()
        for h in headers[1:]:
            key,value = h.split(u': ')
            if key == 'Content-Length':
                content_len = value

        if method == 'POST':
            response = Util().do_POST(conn, body, content_len)
        else:
            response = '''\
HTTP/1.1 200 OK


    
        A webserver powered by Python
    
    
        

Hello, world!


''' conn.sendall(response) conn.close() def do_POST(self, conn, body, data_len): response = '''\ HTTP/1.1 200 OK A webserver powered by Python

This is from POST request!

We get the following data: ''' response += '
' data = body.split(u'=') response += 'The Key is: '+data[0] response += '
The Value is:'+data[1].decode() response += '

' return response s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: s.bind((HOST, PORT)) s.listen(5) print 'Serving HTTP on port %s ...' % PORT except socket.error as e: print 'Server error >> %s' % e sys.exit(1) while True: conn, addr = s.accept() try: Util().dealConnection(conn) except socket.error as e: print 'Server error >> %s' % e sys.exit(1)

你可能感兴趣的:(Python入门教程: Socket中Get/Post方法连用)