Created
August 13, 2021 08:06
-
-
Save jarlostensen/7cf211dc763c83e7f22c4ec8c729986c to your computer and use it in GitHub Desktop.
python Flask POST binary float array using numpy
This file contains hidden or 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
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) | |
This file contains hidden or 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
# 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