⠛⠥⠝⠑⠽⠎⠥⠎ /home/asguneysu

File Upload with Tornado

by Ahmed Şeref Güneysu

Tornado Application download
#!/usr/bin/env python
# coding:utf-8

import os
import uuid

from fs import open_fs
from tornado.web import Application, RequestHandler, url, StaticFileHandler

from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop

fs = open_fs('osfs://uploads/')

class Userform(RequestHandler):

    def get(self):
        self.render("upload.html")



# noinspection PyAbstractClass
class AsyncFileUploadHandler(RequestHandler):
    """
    Uploader
    """

    def upload_async(self, filepart):
        filename = filepart['filename']
        extension = os.path.splitext(filename)[1]
        unique_name = str(uuid.uuid4()) + extension
        fs.setbytes(unique_name, filepart['body'])
        return unique_name

    def post(self):
        files = tuple(map(self.upload_async, self.request.files['file']))
        urls = tuple(map(lambda name: f'/uploads/{name}', files))
        data = dict(files=files, urls=urls)
        self.finish(data)


handlers = [
    (r"/", Userform),
    url(pattern=r'/upload', handler=AsyncFileUploadHandler, name='upload'),
    (r"/uploads/(.*)", StaticFileHandler, {"path": "uploads"})
]

App = Application(handlers=handlers, **dict(debug=False,
                                            autoreload=False, logging='debug'))
if __name__ == "__main__":
    server = HTTPServer(App)
    server.bind(port=8000)
    server.start(num_processes=1)
    IOLoop.current().start()
Docker Compose download
version: "3"

services:
  app:
    build: .
    volumes:
      -  ./uploads:/uploads
    ports:
      - "8000:8000"
Dockerfile download
FROM guneysu/python:3-onbuild
VOLUME ["/uploads"]
ADD app /app
WORKDIR /
CMD python -m app
Requirements download
fs==2.0.4
tornado==4.5.1
Makefile download
default: run

build:
    @docker-compose build

run: build
    @docker-compose up

test:
    @http -f POST :8000/upload file@requirements.txt file@requirements.txt

down:
    @docker-compose down
    
develop:
    @docker-compose up --build

.PHONY: default build run test down develop

Running

docker-compose up -d

Testing

http -f POST :8000/ file@requirements.txt
HTTP/1.1 200 OK
Content-Length: 215
Content-Type: application/json; charset=UTF-8
Date: Sat, 02 May 2020 14:36:36 GMT
Server: TornadoServer/4.5.1

{
    "files": [
        "6936cd27-01dc-4af6-adf9-970ad168ed6b.txt",
        "1c7052d7-0e29-4eb4-a914-f58d78289add.txt"
    ],
    "urls": [
        "/uploads/6936cd27-01dc-4af6-adf9-970ad168ed6b.txt",
        "/uploads/1c7052d7-0e29-4eb4-a914-f58d78289add.txt"
    ]
}
DMCA.com Protection Status