Python tornado upload file function

Tornado is an open source version of web server software. Tornado has a clear difference from mainstream web server frameworks (including most Python frameworks): it is a non-blocking server and it is quite fast.

Thanks to its non-blocking method and the use of epoll, Tornado can handle thousands of connections per second, so Tornado is an ideal framework for real-time web services.

In the web development process, file upload is a frequently used function, such as uploading attachments, uploading photos, etc. Let's introduce the use of tornado to realize simple file upload function.

Normal upload

# coding: utf-8import tornado.ioloop
import tornado.web
import shutil
import os
import json
classFileUploadHandler(tornado.web.RequestHandler):
 def get(self):
 self.write('''
< html 
 < head <title Upload File</title </head 
 < body 
 < form action='file' enctype="multipart/form-data" method='post'<input type='file' name='file'/ <br/<input type='submit' value='submit'/</form 
 < /body 
< /html 
''')

 def post(self):
 ret ={'result':'OK'}
 upload_path = os.path.join(os.path.dirname(__file__),'files') #Temporary file path
 file_metas = self.request.files.get('file', None) #Extract the&#39;name'For&#39;file'File metadata

 if not file_metas:
  ret['result']='Invalid Args'return ret

 for meta in file_metas:
  filename = meta['filename']
  file_path = os.path.join(upload_path, filename)withopen(file_path,'wb')as up:
  up.write(meta['body'])
  # OR do other thing

 self.write(json.dumps(ret))

app = tornado.web.Application([(r'/file', FileUploadHandler),])if __name__ =='__main__':
 app.listen(8080)
 tornado.ioloop.IOLoop.instance().start()

Upload using ajax

With ajax upload, you need to modify the way the front-end sends requests. You can refer to the following methods:

< html 
 < head <title Upload File</title 
 < script type="text/javascript" src="/www/static/jquery.min.js"</script 
 < /head 
 < body 
 < form id='upload' action='upload' enctype="multipart/form-data" method='post'<input type='file' name='file'/ <br/<input type='button' id='submit' value='submit'/</form 
 < /body 
 < script 
 $('#submit').click(function(){var form =$('form')[0];var formData =newFormData(form);
  formData.append('image',$('input[type=file]')[0].files[0]);
  $.ajax({
  url:'/file/upload',
  data: formData,
  type:'POST',
  contentType:false,
  processData:false,
  success:function(data){var obj = jQuery.parseJSON(data);alert(obj.result);// TODO},
  error:function(data){var obj = jQuery.parseJSON(data);alert(data.result);}})});</script 
 < /html 

note

When tornado processes a file upload, it puts the entire file in memory.
If there is a need to upload large files, the file upload module of nginx (third-party module needs to be compiled) is generally used.

to sum up

So far, this article about the function of Python tornado uploading files is introduced. For more related Python tornado upload file content, please search for ZaLou.Cn's previous articles or continue to browse the related articles below. I hope everyone will support ZaLou.Cn in the future. !

Recommended Posts

Python tornado upload file function
Python implements ftp file transfer function
Python file operation
Python enumerate() function
Python function buffer
Python custom function basics
Python built-in function -compile()
Python function basic learning
Python data analysis-apply function
Python3 built-in function table.md
Python Print print timer function
Python high-order function usage summary!
Python implements TCP file transfer
Python magic function eval () learning
How Python implements FTP function
Quick start Python file operation
Python implements image stitching function
Supervisor + Nginx + Python3 deploy Tornado
Python high-order function usage summary!
Python| function using recursion to solve
Python file read and write operations
python ftp upload files and folders
Why doesn&#39;t Python support function overloading?
Learning Python third day one-line function
How to write python configuration file
Python file operation basic process analysis
Python function definition and parameter explanation
Python implements AI face change function
ubuntu fixed ip&amp;FDFS upload file error
Python realizes image recognition car function
Python realizes udp transmission picture function
How Python operates on file directories
How Python implements the timer function