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

2017-12-20  本文已影响38人  破旧的大卡车

可以直接用浏览器测试, 或者用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

<html>
    <head>
        <title>A webserver powered by Python</title>
    </head>
    <body>
        <p>Hello, world!</p>
        <form method="POST" action='/'>
            <textarea name='input' rows='4' cols='40' placeholder='Input here...'></textarea>
            <br />
            <input type='submit' />
        </form>
    </body>
</html>
'''
        conn.sendall(response)
        conn.close()

    def do_POST(self, conn, body, data_len):
        response = '''\
HTTP/1.1 200 OK

<html>
<head>
<title>A webserver powered by Python</title>
</head>
<body>
<p>This is from POST request!</p>
<p>We get the following data:
'''
        response += '<br />'
        data = body.split(u'=')
        response += 'The Key is: '+data[0]
        response += '<br />The Value is:'+data[1].decode()
        response += '</p></body></html>'
        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)
上一篇 下一篇

猜你喜欢

热点阅读