def app(): sanic_app = Sanic(__name__) api = Api(sanic_app) class TestResource(Resource): @marshal_with_field(fields.List(fields.Integer)) async def get(self, request): return ['1', 2, 3.0], 200, {} @marshal_with_field(fields.List(fields.Integer)) async def delete(self, request): return ['1', 2, 3.0] @marshal_with(resource_fields) async def post(self, request): data = { 'name': 'bot', 'line1': 'fake street', 'line2': 'fake block', 'city': 1, 'country': 'China', 'first_names': ['Emile', 'Raoul'], 'date_updated': datetime(2019, 1, 1), 'date_created': datetime(2018, 1, 1), 'id': '01', 'boolean': False, 'float': 1, 'arbitrary': 634271127864378216478362784632784678324.23432, 'fixed': 23432, 'none_int': None } return data @marshal_with(resource_fields) async def patch(self, request): data = { 'name': 'bot', 'line1': 'fake street', 'line2': 'fake block', 'city': 1, 'country': 'China', 'first_names': ['Emile', 'Raoul'], 'date_updated': datetime(2019, 1, 1), 'date_created': datetime(2018, 1, 1), 'id': '01', 'boolean': False, 'float': 1, 'arbitrary': 634271127864378216478362784632784678324.23432, 'fixed': 23432, 'none_int': None } return data, 200, {} api.add_resource(TestResource, '/') yield sanic_app
def app(): sanic_app = Sanic(__name__) api = Api(sanic_app) def login_require(func): @wraps(func) async def wrapper(request, *args, **kwargs): response = await func(request, *args, **kwargs) return response return wrapper class TestApi(Resource): method_decorators = {'get': login_require} async def get(self, request): return '' api.add_resource(TestApi, '/') yield sanic_app
def app(): sanic_app = Sanic(__name__) api = Api(sanic_app) class TestResource(Resource): async def get(self, request): return {'response': 'get'} async def post(self, request): return {'response': 'post'} async def put(self, request): return {'response': 'put'} async def delete(self, request): return {'response': 'delete'} async def patch(self, request): return {'response': 'patch'} class TestResponse(Resource): async def get(self, request): return json({'response': 'get'}) api.add_resource(TestResponse, '/response') api.add_resource(TestResource, '/') yield sanic_app
def app(): sanic_app = Sanic(__name__) api = Api(sanic_app) class SimpleParserResource(Resource): async def post(self, request): args = simple_parser.parse_args(request) return {'args': args.args, 'form': args.form} async def patch(self, request): args = simple_parser.parse_args(request) return {'json': args.json} class NoLocation(Resource): async def post(self, request): args = no_location_parser.parse_args(request) assert args.key return {"key": args.key}, 200, {} class Convert(Resource): async def get(self, request): args = convert_parser.parse_args(request) assert isinstance(args.key, int) assert not args.key1 assert args.key2 == 'VALUE' assert args.default_key == 'default_value' return '', 200 async def post(self, request): parser = RequestParser() parser.add_argument('key', required=True) parser.parse_args(request) return '', class ParserChoices(Resource): async def get(self, request): choices = ('one', 'two') parser = RequestParser() parser.add_argument('foo', choices=choices, help="bad choice: {error_msg}") args = parser.parse_args(request) assert args.foo in choices return '' class StrictParse(Resource): async def get(self, request): parser = RequestParser() parser.add_argument('key') parser.parse_args(request, True) return '' class TrimParse(Resource): async def get(self, request): parser = RequestParser(trim=True) parser.add_argument('key') args = parser.parse_args(request) assert args.key == 'value' return '' class NullParse(Resource): async def post(self, request): parser = RequestParser() parser.add_argument('key', nullable=False, location='json') parser.parse_args(request) return '' async def put(self, request): parser = RequestParser() parser.add_argument('key', nullable=True, location='json') parser.parse_args(request) return '' api.add_resource(NullParse, '/null') api.add_resource(TrimParse, '/trim') api.add_resource(StrictParse, '/strict') api.add_resource(ParserChoices, '/choices') api.add_resource(Convert, '/convert') api.add_resource(NoLocation, '/no_location') api.add_resource(SimpleParserResource, '/') yield sanic_app
from sanic_restful import Api from sanic.blueprints import Blueprint from . import healthcheck health_bp = Blueprint(__name__, url_prefix='/health') health_api = Api(health_bp) health_api.add_resource(healthcheck.HealthStatusResource, '/status')
from sanic import Sanic from sanic.request import Request from sanic.response import json from sanic_jwt import initialize from sanic_restful import Api from src.auth import authenticate from src.definitions import ApiError, BadRequestError from src.resources import PolyDataResource, PolyDataResourceList app = Sanic("Polyrize Interview Server") api = Api(app) initialize(app, authenticate=authenticate, url_prefix="/api/auth") def build_error_response(message, status_code, error_code, **kwargs): return json({ "error": error_code, "message": message, **kwargs }, status=status_code) # Handle exceptions @app.exception(Exception) def handle_error(request: Request, e): if isinstance(e, ApiError): return build_error_response(message=e.message, status_code=e.status_code, error_code=e.error_code)
import base64 # Set global defines API_KEY = os.getenv("API_KEY") BOT_TOKEN = os.getenv("BOT_TOKEN") CHAT_ID = os.getenv("CHAT_ID") CHAT_USER_NAME = os.getenv("CHAT_USER_NAME") DEBUG = bool(os.environ.get('DEBUG', '')) ENCRYPTION_KEY = os.getenv("ENCRYPTION_KEY") PORT = int(os.environ.get("PORT", 8000)) WEB_CONCURRENCY = int(os.environ.get('WEB_CONCURRENCY', 1)) # setup sanic api engine sanic = Sanic("__Sanic__") sanic_errors = {'TypeError': {'status': 404, 'message': 'not found'}} api = Api(sanic, errors=sanic_errors) parser = reqparse.RequestParser() parser.add_argument('signature', location='form') parser.add_argument('title', location='form') parser.add_argument('text', location='form') class SanicApiHandler(Resource): async def post(self, request): args = parser.parse_args(request) # validate signature if 'signature' in args: signature = self.decrypt_data(args['signature']).decode("utf-8") if signature == API_KEY: if 'title' in args and 'text' in args:
@app.middleware('response') async def cors_headers(request, response): """ Add CORS headers to all responses, including errors. """ response.headers['Access-Control-Allow-Origin'] = request.headers.get('Origin', '*') response.headers['Access-Control-Allow-Credentials'] = 'true' response.headers['Access-Control-Allow-Methods'] = 'POST, PUT, PATCH, DELETE, OPTIONS, GET' response.headers['Access-Control-Allow-Headers'] = "X-Requested-With,X-Prototype-Version," \ "Content-Type,Cache-Control,Pragma,Origin,Cookie" response.headers['Access-Control-Max-Age'] = '3600' class TodoResource(ApiEndpoint): # method_decorators = [auth.auth_required] endpoint = 'todos/<todo_id>' async def get(self, request, todo_id): return {'id': todo_id} async def post(self, request, todo_id): return {'id': todo_id}, 201 api = Api(app, [TodoResource], '/v0.9/') if __name__ == "__main__": app.run(host="0.0.0.0", port=8000, debug=True)
# @Project : tql-App. # @File : SanicApp # @Time : 2019-11-26 13:40 # @Author : yuanjie # @Email : [email protected] # @Software : PyCharm # @Description : from sanic import Sanic from sanic.exceptions import NotFound, Unauthorized from sanic.log import error_logger from sanic_restful import reqparse, Api, Resource app = Sanic(__name__) errors = {'TypeError': {'status': 404, 'message': 'not found'}} api = Api(app, errors=errors) TODOS = { 'todo1': { 'task': 'build an API' }, 'todo2': { 'task': '?????' }, 'todo3': { 'task': 'profit!' }, } def abort_if_todo_doesnt_exist(todo_id):
def init_app(): app = Sanic(__name__) api = Api(app) api.add_resource(SignUp, '/signup') api.add_resource(SignIn, '/signin') api.add_resource(RefreshToken, '/refreshtoken') api.add_resource(Api1, '/api1') api.add_resource(Api2, '/api2') api.add_resource(Api3, '/api3') api.add_resource(Api4, '/api4') api.add_resource(Api5, '/api5') return app
from sanic import Sanic from sanic.response import HTTPResponse from sanic_restful import Api, Resource def output_xml(app, data, code, headers=None): """Makes a Flask response with a XML encoded body""" resp = HTTPResponse(dumps({'response': data}), status=code, headers=headers) resp.headers.extend(headers or {}) return resp app = Sanic(__name__) api = Api(app, default_mediatype='application/xml') api.representations['application/xml'] = output_xml class Hello(Resource): """ # you need requests >>> from requests import get >>> get('http://localhost:5000/me').content # default_mediatype '<?xml version="1.0" ?><response><hello>me</hello></response>' >>> get('http://localhost:5000/me', headers={"accept":"application/json"}).content '{"hello": "me"}' >>> get('http://localhost:5000/me', headers={"accept":"application/xml"}).content '<?xml version="1.0" ?><response><hello>me</hello></response>' """ async def get(self, request, entry):
from sanic import Blueprint from sanic_restful import Api from .test import * api_blueprint = Blueprint(__name__, url_prefix='/api') api = Api(api_blueprint) api.add_resource(AboutNow, '/test/<id>')
from sanic_restful import Api from sanic.blueprints import Blueprint from . import planet planet_bp = Blueprint(__name__, url_prefix='/planets') planet_api = Api(planet_bp) planet_api.add_resource(planet.PlanetsResource, '') planet_api.add_resource(planet.PlanetResource, '/<planet_id:string>')
>>> from requests import put, get >>> put('http://localhost:5000/todo1', data={'data': 'Remember the milk'}).json {u'todo1': u'Remember the milk'} >>> get('http://localhost:5000/todo1').json {u'todo1': u'Remember the milk'} >>> put('http://localhost:5000/todo2', data={'data': 'Change my breakpads'}).json {u'todo2': u'Change my breakpads'} >>> get('http://localhost:5000/todo2').json {u'todo2': u'Change my breakpads'} """ method_decorators = {'get': decorator} async def get(self, request, todo_id): return {todo_id: TODOS[todo_id]} async def put(self, request, todo_id): TODOS[todo_id] = request.form.get('data') return {todo_id: TODOS[todo_id]} app = Sanic(__name__) bp = Blueprint(__name__, url_prefix='/') api = Api(bp) api.add_resource(TodoSimple, '/<todo_id:string>') app.register_blueprint(bp) if __name__ == '__main__': app.run(debug=True)