Skip to content

Instantly share code, notes, and snippets.

@jarlostensen
Created August 13, 2021 08:06
Show Gist options
  • Save jarlostensen/7cf211dc763c83e7f22c4ec8c729986c to your computer and use it in GitHub Desktop.
Save jarlostensen/7cf211dc763c83e7f22c4ec8c729986c to your computer and use it in GitHub Desktop.
python Flask POST binary float array using numpy
def post_bin_example():
import requests
import numpy as np
#NOTE! the dtype used here and on the server have to match and byte ordering isn't considered in this example
x = np.random.rand(10).astype(np.float32)
print(f'sending {len(x)} floats : {x}')
res = requests.post(url=ROOT_PATH+r'/readbin',
data=x.tobytes(),
headers={'Content-Type': 'application/octet-stream'})
print(res)
# NOTE: this is code is a standard Flask view
@app.route('/readbin', methods=['POST'])
def read_bin_example():
chunk_size = 4096
data = bytearray()
while True:
chunk = request.stream.read(chunk_size)
if len(chunk) == 0:
break
data.extend(chunk)
if len(data):
import numpy as np
#NOTE! byte ordering not considered in this example
floats = np.frombuffer(data, dtype=np.float32)
print(f'got {len(data)} bytes, {len(floats)} floats')
print(floats)
return f'ok'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment