From 1963af74380cd8ba71c6f568bbb18f47c0ade1cc Mon Sep 17 00:00:00 2001 From: David Larlet Date: Mon, 14 Mar 2016 15:14:33 +0100 Subject: [PATCH] docs(tutorial): Use mimetypes from standard lib --- doc/user/tutorial.rst | 44 ++++++++----------------------------------- 1 file changed, 8 insertions(+), 36 deletions(-) diff --git a/doc/user/tutorial.rst b/doc/user/tutorial.rst index 9f92380..e12da10 100644 --- a/doc/user/tutorial.rst +++ b/doc/user/tutorial.rst @@ -253,31 +253,20 @@ Next, let's implement the POST responder: .. code:: python import os - import time import uuid + import mimetypes import falcon - def _media_type_to_ext(media_type): - # Strip off the 'image/' prefix - return media_type[6:] - - - def _generate_id(): - return str(uuid.uuid4()) - - class Resource(object): def __init__(self, storage_path): self.storage_path = storage_path def on_post(self, req, resp): - image_id = _generate_id() - ext = _media_type_to_ext(req.content_type) - filename = image_id + '.' + ext - + ext = mimetypes.guess_extension(req.content_type) + filename = '{uuid}{ext}'.format(uuid=uuid.uuid4(), ext=ext) image_path = os.path.join(self.storage_path, filename) with open(image_path, 'wb') as image_file: @@ -289,7 +278,7 @@ Next, let's implement the POST responder: image_file.write(chunk) resp.status = falcon.HTTP_201 - resp.location = '/images/' + image_id + resp.location = '/images/' + filename As you can see, we generate a unique ID and filename for the new image, and then write it out by reading from ``req.stream``. It's called ``stream`` instead @@ -350,35 +339,20 @@ Go ahead and edit your ``images.py`` file to look something like this: .. code:: python import os - import time import uuid + import mimetypes import falcon - def _media_type_to_ext(media_type): - # Strip off the 'image/' prefix - return media_type[6:] - - - def _ext_to_media_type(ext): - return 'image/' + ext - - - def _generate_id(): - return str(uuid.uuid4()) - - class Collection(object): def __init__(self, storage_path): self.storage_path = storage_path def on_post(self, req, resp): - image_id = _generate_id() - ext = _media_type_to_ext(req.content_type) - filename = image_id + '.' + ext - + ext = mimetypes.guess_extension(req.content_type) + filename = '{uuid}{ext}'.format(uuid=uuid.uuid4(), ext=ext) image_path = os.path.join(self.storage_path, filename) with open(image_path, 'wb') as image_file: @@ -399,9 +373,7 @@ Go ahead and edit your ``images.py`` file to look something like this: self.storage_path = storage_path def on_get(self, req, resp, name): - ext = os.path.splitext(name)[1][1:] - resp.content_type = _ext_to_media_type(ext) - + resp.content_type = mimetypes.guess_type(name)[0] image_path = os.path.join(self.storage_path, name) resp.stream = open(image_path, 'rb') resp.stream_len = os.path.getsize(image_path)