Skip to content

Instantly share code, notes, and snippets.

@hoto17296
Last active July 31, 2017 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoto17296/28cd740cac58dfbf2012fe1b8249dc53 to your computer and use it in GitHub Desktop.
Save hoto17296/28cd740cac58dfbf2012fe1b8249dc53 to your computer and use it in GitHub Desktop.
Python 3 標準モジュールで HTTP + numpy array をやりとり
from http.client import HTTPConnection
import numpy as np
# GET
conn = HTTPConnection('', 8080)
conn.request('GET', '/')
res = conn.getresponse()
conn.close()
print(res.status)
print(res.headers)
body = res.read()
print(np.loads(body))
# POST
conn = HTTPConnection('', 8080)
body = np.array([1,2,3]).dumps()
headers = { 'Content-Length': len(body) }
conn.request('POST', '/', body, headers)
res = conn.getresponse()
conn.close()
print(res.status)
print(res.headers)
from http.server import HTTPServer, BaseHTTPRequestHandler
import os
import numpy as np
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
body = np.array([1,2,3]).dumps()
self.wfile.write(body)
def do_POST(self):
size = int(self.headers['Content-Length'])
body = self.rfile.read(size)
print(np.loads(body))
self.send_response(200)
self.end_headers()
if __name__ == '__main__':
port = int(os.environ.get('PORT', 80))
server = HTTPServer(('', port), Handler)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.shutdown()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment