GithubHelp home page GithubHelp logo

lazy-labs / star_resty Goto Github PK

View Code? Open in Web Editor NEW
6.0 4.0 0.0 76 KB

Python rest framework

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

Python 96.82% HTML 3.18%
starlette apispec marshmallow python3 web rest-api asyncio

star_resty's Introduction

Star resty

Object-oriented rest framework based on starlette, marshmallow and apispec.

Requirements

  • [Python] 3.7+
  • [Starlette] 0.12.0+
  • [Marshmallow] 3.0.0rc8+
  • [APISpec] 2.0.2+
  • [python-multipart] 0.0.5+

Installation

$ pip install star_resty

Example

from marshmallow import Schema, fields, ValidationError, post_load
from starlette.applications import Starlette
from starlette.datastructures import UploadFile
from starlette.responses import JSONResponse
from apispec.ext.marshmallow import MarshmallowPlugin
from apispec import APISpec

from dataclasses import dataclass
from datetime import datetime

from star_resty import Method, Operation, endpoint, json_schema, json_payload, upload, query, setup_spec, form_payload
from typing import Optional

class EchoInput(Schema):
    a = fields.Int()


# Json Payload (by schema)
class JsonPayloadSchema(Schema):
    a = fields.Int(required=True)
    s = fields.String()

ma_plugin = MarshmallowPlugin()

# Json Payload (by dataclass)
@dataclass
class Payload:
    a: int
    s: Optional[str] = None

class JsonPayloadDataclass(Schema):
    a=fields.Int(required=True)
    s=fields.Str()

    @post_load
    def create_payload(self, data, **kwargs):
        return Payload(**data)


# Form Payload
class FormPayload(Schema):
    id = fields.Int(required=True)
    file_dt = fields.DateTime()


app = Starlette(debug=True)

@app.exception_handler(ValidationError)
def register_error(request, e: ValidationError):
    return JSONResponse(e.normalized_messages(), status_code=400)


@app.route('/echo')
@endpoint
class Echo(Method):
    meta = Operation(tag='default',
                     description='echo')
    response_schema = EchoInput
    async def execute(self, query_params: query(EchoInput)):
        self.status_code = 201  # Configurable Respone Http Status Code
        return query_params


@app.route('/post/schema', methods=['POST'])
@endpoint
class PostSchema(Method):
    meta = Operation(tag='default', description='post json (by schema)')

    async def execute(self, item: json_payload(JsonPayloadSchema)):
        return {'a': item.get('a') * 2, 's': item.get('s')}


@app.route('/post/dataclass', methods=['POST'])
@endpoint
class PostDataclass(Method):
    meta = Operation(tag='default', description='post json (by dataclass)')

    async def execute(self, item: json_schema(JsonPayloadDataclass, Payload)):
        return {'a': item.a * 3, 's': item.s}

@app.route('/form', methods=['POST'])
@endpoint
class PostForm(Method):
    meta = Operation(tag='default', description='post form')

    async def execute(self, form_data: form_payload(FormPayload),
                            files_reqired: upload('selfie', 'doc', required=True),
                            files_optional: upload('file1', 'file2', 'file3')):
        files = {}
        for file in files_reqired + files_optional:
            body = await file.read()
            files[file.filename] = f"{body.hex()[:10]}..."
        id = form_data.get('id')
        return {'message': f"files received (id: {id})", "files": files}


if __name__ == '__main__':
    import uvicorn

    setup_spec(app, title='Example')
    uvicorn.run(app, port=8080)

Open http://localhost:8080/apidocs to view generated openapi schema.

star_resty's People

Contributors

slv0 avatar wvolkov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

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.