1

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)
KHAN
  • 57
  • 7

1 Answers1

0

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

Tlaloc-ES
  • 4,825
  • 7
  • 38
  • 84