Last active
July 31, 2017 11:46
-
-
Save hoto17296/28cd740cac58dfbf2012fe1b8249dc53 to your computer and use it in GitHub Desktop.
Python 3 標準モジュールで HTTP + numpy array をやりとり
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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