Giter Site home page Giter Site logo

sprockets / sprockets.mixins.mediatype Goto Github PK

View Code? Open in Web Editor NEW
0.0 15.0 3.0 220 KB

Handles Content-Type & Accept header serialization and deserialization for you

Home Page: https://sprocketsmixinsmedia-type.readthedocs.io

License: BSD 3-Clause "New" or "Revised" License

Python 100.00%
hacktoberfest python python3 tornado-web

sprockets.mixins.mediatype's Introduction

sprockets.mixins.mediatype

A mixin that performs Content-Type negotiation and request/response (de)serialization.

Documentation Build Badge Package Info

This mix-in adds two methods to a tornado.web.RequestHandler instance:

  • get_request_body() -> dict: deserializes the request body according to the HTTP Content-Type header and returns the deserialized body.
  • send_response(object): serializes the response into the content type requested by the Accept header.

Before adding support for specific content types, you SHOULD install the content settings into your tornado.web.Application instance. If you don't install the content settings, then an instance will be created for you by the mix-in; however, the created instance will be empty. You should already have a function that creates the Application instance. If you don't, now is a good time to add one.

from sprockets.mixins.mediatype import content
from tornado import web

def make_application():
    application = web.Application([
        # insert your handlers here
    ])
    content.install(application, 'application/json', 'utf-8')
    return application

Support for a content types is enabled by calling add_binary_content_type, add_text_content_type or the add_transcoder functions with the tornado.web.Application instance, the content type, encoding and decoding functions as parameters:

import json

from sprockets.mixins.mediatype import content
from tornado import web

def make_application():
    application = web.Application([
        # insert your handlers here
    ])

    content.install(application, 'application/json', 'utf-8')
    content.add_text_content_type(application,
                                  'application/json', 'utf-8',
                                  json.dumps, json.loads)

    return application

The add content type functions will add a attribute to the Application instance that the mix-in uses to manipulate the request and response bodies. The add_transcoder function is similar except that it takes an object that implements transcoding methods instead of simple functions. The transcoders module includes ready-to-use transcoders for a few content types:

from sprockets.mixins.mediatype import content, transcoders
from tornado import web

def make_application():
    application = web.Application([
        # insert your handlers here
    ])

    content.install(application, 'application/json', 'utf-8')
    content.add_transcoder(application, transcoders.JSONTranscoder())

    return application

In either case, the ContentMixin uses the registered content type information to provide transparent content type negotiation for your request handlers.

from sprockets.mixins.mediatype import content
from tornado import web

class SomeHandler(content.ContentMixin, web.RequestHandler):
    def get(self):
        self.send_response({'data': 'value'})

    def post(self):
        body = self.get_request_body()
        # do whatever
        self.send_response({'action': 'performed'})

Based on the settings stored in the Application instance and the HTTP headers, the request and response data will be handled correctly or the appropriate HTTP exceptions will be raised.

sprockets.mixins.mediatype's People

Contributors

amberheilman avatar aremm avatar bkorty avatar cknave avatar dave-shawley avatar djt5019 avatar gmr avatar nvllsvm avatar pianoman19372 avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sprockets.mixins.mediatype's Issues

`get_request_body` should catch `TypeError` in addition to `ValueError`

try:
content_type_header = headers.parse_content_type(content_type)
except ValueError:
raise web.HTTPError(400, 'failed to parse content type %s',
content_type)

If the default content type is unset, then content_type will be None and parse_content_type will raise a TypeError instead of a ValueError. In either case, we should be responding with a "client error".

Deploy pipeline is broken

I added the testing pipeline components but we are still lacking the distirbution/upload portion of the pipeline. This has been broken since travis-ci.org went away on June 15, 2021.

Add typing support

I started an effort to do this a few years ago (see #23) but it fizzled since the typing SIG was still changing things. Now that things have settled done in the part of the ecosystem, I'd like to reboot it. I still like the approach that I took in my original branch:

  • represent expectations using structural sub-typing and typing.Protocol sub-classes explicitly
  • add type definitions for precisely we know how to serialize -- IOW, define a union type like SerializableTypes
  • document the definitions and expected usage
  • pull mypy (maybe pyright?) into the build chain

The one downside is that typing.Protocol was added in 3.8 and we still support 3.7. We can use the typing.extensions package as a backport. For this reason, I would isolate the typing-related classes into a module named sprockets.mixins.mediatype.type_info and use it in conjunction with typing. The goal is to not let the non-3.7 compatibility stuff leak out of the module.

Feel free to steal, adopt, and/or ignore portions of my original branch.

Support context suffixes (RFC6839)

ietfparse 1.5.0 introduced breaking behavior that alters the behavior of this module.

For example:

content.add_transcoder(
    self, transcoders.JSONTranscoder(),
    content_type='application/vnd.some.app+json')
content.add_transcoder(
    self, transcoders.MsgPackTranscoder(),
    content_type='application/vnd.some.app+msgpack')

With ietfparse < 1.5, this module will see each content type + suffix as a distinct content type.

With ietfparse >= 1.5, this module's usage of ietfparse will result in the suffix being stripped before registering the transcoder.

Enforce code formatting

Either yapf or black ... in any case:

  • line length is 79 chars
  • single-quotes are preferred over double quotes except in docstrings
  • CI pipeline fails if there are formatting violations
  • tox.ini is updated with a "lint" target that checks style
  • expectations are documented in docs/contributing.rst

My vote would be for yapf since it has fewer dependencies and generally creates code that my eyes like.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.