'How to send stream data using just python?
I am currently learning NodeJS and I learned a really neat way of sending big files, using streams, I already have a bit of an experience with Django but how can I do the following in Django (or python)
const http = require('http')
const fs = require('fs')
const server = http.createServer((req, res)=>{
const fileContent = fs.createReadStream('./content/bigFile.txt', 'utf8')
fileContent.on('open', ()=>{
fileContent.pipe(res)
})
fileContent.on('error',(err)=>res.end(err) )
})
server.listen(5000)
Solution 1:[1]
You could use open like this
f = open("myfile", "rb")
try:
byte = f.read(1)
while byte != "":
# Do stuff with byte.
byte = f.read(1)
finally:
f.close()
Or if is an image you could you use this
from io import StringIO # "import StringIO" directly in python2
from PIL import Image
im1 = Image.open(IMAGE_FILE)
# here, we create an empty string buffer
buffer = StringIO.StringIO()
im1.save(buffer, "JPEG", quality=10)
# ... do something else ...
# write the buffer to a file to make sure it worked
with open("./photo-quality10.jpg", "w") as handle:
handle.write(buffer.contents())
References
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tlaloc-ES |
