What is the Python equivalent to Django File object? -


i need modify http header of file within python, , know possible using django 'file' object (https://docs.djangoproject.com/en/dev/topics/files/) documented in example i'm following here: http://tmanstwobits.com/convert-your-web-pages-to-pdf-files-using-phantomjs.html

here's basic code i'm trying duplicate without django:

file_name = '/tmp/current_page.pdf' url = ('user_current_url') external_process = popen(["phantomjs", phantomjs_script, url, file_name],                          stdout=pipe, stderr=stdout) # open file created phantomjs return_file = file(open(file_name, 'r')) response = httpresponse(return_file, mimetype='application/force-download') response['content-disposition'] = 'attachment; filename=current_page.pdf' # return file browser , force download item return response 

i've tried using urllib.urlopen, allows me modify http header, run other problems , doesn't seem best approach. how can accomplish this?

since you're using tornado, have setup request handler:

import tornado.ioloop import tornado.web  class pdfhandler(tornado.web.requesthandler):     def get(self):         filename = 'current_page.pdf'          self.set_header('content-disposition', 'attachment; filename=current_page.pdf')         self.set_header('content-type', 'application/force-download')          open(filename, 'r') handle:             data = handle.read()             self.set_header('content-length', len(data))             self.write(data)  if __name__ == "__main__":     application = tornado.web.application([         (r'/', pdfhandler),     ])      application.listen(8888)     tornado.ioloop.ioloop.instance().start() 

i use tempfile module instead of hard-coding paths. also, streaming file in chunks if you're concerned memory usage.


Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -