The web framework
Project description
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.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
star_resty-0.0.20.tar.gz
(13.5 kB
view details)
File details
Details for the file star_resty-0.0.20.tar.gz
.
File metadata
- Download URL: star_resty-0.0.20.tar.gz
- Upload date:
- Size: 13.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.7.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | c22dc8b1d6f60da3b419fd6d4e942e3121337ee14d27073936dcf3d03eab28b1 |
|
MD5 | 3aa7f485a3585371eed82da7b4040368 |
|
BLAKE2b-256 | ff02a6c129e60ef4d18bf043edbe2b59690268ee8b4788adf7032b4c7e0e5b3a |