async def echo_nested(request): args = {"name": fields.Nested({"first": fields.Str(), "last": fields.Str()})} parsed = await parser.parse(args, request) return json_response(parsed)
class UserSchema(Schema): id = fields.Int(dump_only=True) email = fields.Email() password = fields.Str(load_only=True)
payable = Payable.query.get(id) if payable is None: raise ApiException(message="Not Found", status_code=404, payload={"payable": id}) p = payable.to_dict() p["app"] = payable.app.to_dict() return p @bp.route("/apps/<app_id>/payables", methods=["POST"]) @authorized @use_args({ "display_name": fields.Str(required=True), "display_price": fields.Integer(required=True), "permalink": fields.Str(required=True), }) def create_payable(user, args, app_id): """ Creates a new app for a given user """ app = App.query.get(app_id) if app is None: raise ApiException("App does not exist", 400) payable = Payable( display_name=args["display_name"],
def test_arg_not_required_excluded_in_parsed_output(parser, web_request): web_request.json = {'first': 'Steve'} args = {'first': fields.Str(), 'last': fields.Str()} result = parser.parse(args, web_request) assert result == {'first': 'Steve'}
def test_get_value_multidict(input_dict): field = fields.List(fields.Str()) assert get_value(input_dict, 'foos', field) == ['a', 'b']
class PlayListResponseSchema(Schema): id = fields.Str() title = fields.Str() entries = fields.Nested(PlayListEntitySchema, many=True)
class ProgressEpisodeSchema(Schema): id = fields.Int() title = fields.Str() image_url = fields.URL() status = fields.Str()
from flask import * from flask_socketio import emit from webargs import fields from webargs.flaskparser import use_args, FlaskParser from . import main from .routes_frontend import get_recipes from .routes_frontend import get_graph_data from .. import * arg_parser = FlaskParser() # Register: /API/pico/register?uid={UID} # Response: '#{0}#\r\n' where {0} : T = Registered, F = Not Registered register_args = { 'uid': fields.Str(required=True), #32 character alpha-numeric serial number } @main.route('/API/pico/register') @use_args(register_args, location='querystring') def process_register(args): return '#T#\r\n' # Change State: /API/pico/picoChangeState?picoUID={UID}&state={STATE} # Response: '\r\n' change_state_args = { 'picoUID': fields.Str(required=True), #32 character alpha-numeric serial number 'state': fields.Int(
from webargs import fields, validate from webargs.flaskparser import use_args, use_kwargs, parser from src.services import MovieSuggestService from .anonymous_base_controller import AnonymousBaseController from src.controllers.common.http_exceptions import HTTPNotFoundException, HTTPServerInternalException from src.controllers.common.http_exceptions import HTTPInvalidContentFormatException, HTTPInvalidFileFormatException, HTTPDataEmptyException from src.exceptions import WebapiException from src.exceptions import ErrorCode from .schemas import MovieResponseSchema from marshmallow import EXCLUDE from flask import Response movie_args = {"title": fields.Str(required=True)} @parser.error_handler def handle_request_parsing_error(error, req, schema, *, error_status_code, error_headers): raise HTTPInvalidFileFormatException() class MovieSuggestController(AnonymousBaseController): def __init__(self): super().__init__() @use_args(movie_args) def post(self, args): try:
from __future__ import unicode_literals from marshmallow_enum import EnumField from webargs import fields from indico.legacy.common.cache import GenericCache from indico.modules.rb.models.reservations import RepeatFrequency _cache = GenericCache('Rooms') search_room_args = { 'capacity': fields.Int(), 'equipment': fields.List(fields.Str()), 'features': fields.List(fields.Str(), data_key='feature'), 'favorite': fields.Bool(), 'mine': fields.Bool(), 'text': fields.Str(), 'division': fields.Str(), 'start_dt': fields.DateTime(), 'end_dt': fields.DateTime(), 'repeat_frequency': EnumField(RepeatFrequency), 'repeat_interval': fields.Int(missing=0), 'building': fields.Str(), 'sw_lat': fields.Float(validate=lambda x: -90 <= x <= 90), 'sw_lng': fields.Float(validate=lambda x: -180 <= x <= 180), 'ne_lat': fields.Float(validate=lambda x: -90 <= x <= 90), 'ne_lng': fields.Float(validate=lambda x: -180 <= x <= 180) }
from guard.ip import ratelimit from . import validators, utils api = Blueprint('accounts.username', __name__) db = app.db @ratelimit(limit=10, interval=300, key_prefix='register') @api.route('/register.api', methods=['post']) # @anonymous_user_required @use_args( { 'username': fields.Str(required=True, validate=[ validate.Length(min=6, max=30), validate.Regexp('^[a-zA-Z][a-zA-Z0-9_\-]+'), validators.username_exists ]), 'password': fields.Str(required=True, validate=validate.Length(min=8, max=32)), }, locations=('form', 'json')) def register(args): if app.config.get('ACCOUNT_USERNAME_DISABLE_REGISTER', True): abort(422, errors={'global': '网站禁止使用用户名方式注册'}) return jsonify(utils.register(args['username'], args['password'])), 201 @ratelimit(limit=5, interval=300, key_prefix='login:username') @api.route('/login.api', methods=['post'])
async def echo_nested_many(request): args = { "users": fields.Nested({"id": fields.Int(), "name": fields.Str()}, many=True) } parsed = await parser.parse(args, request) return json_response(parsed)
async def echo_multiple_args(request): args = {"first": fields.Str(), "last": fields.Str()} parsed = await parser.parse(args, request) return json_response(parsed)
class HelloSchema(ma.Schema): name = fields.Str(missing="World", validate=lambda n: len(n) >= 3)
class EpisodeListSchema(Schema): id = fields.Int(required=True) title = fields.Str(required=True) created_at = fields.DateTime(required=True) image_url = fields.URL() status = fields.Str(required=True)
class Userland(RouteCog): @staticmethod def dict_all(models): return [m.to_dict() for m in models] @route("/api/v1/login", methods=["POST"]) @json @use_kwargs({ "username": fields.Str(required=True), "password": fields.Str(required=True) }, locations=("json",)) async def login(self, username: str, password: str): user = await User.get_any(True, username=username, email=username).first() if not user: abort(400, "Invalid username or email") if Authenticator.hash_password(password) != user.password: abort(400, "Invalid password") if not user.email_verified: abort(401, "Email needs to be verified") token = jwt_service.make_login_token(user.id, user.last_pass_reset) return jsonify(token=token) @route("/api/v1/verify", methods=["GET"]) @json @use_kwargs({ "token": fields.Str(required=True) }, locations=("query",)) async def verify_email(self, token): parsed_token = await jwt_service.verify_email_token(token, True) if parsed_token is False: abort(400, "Invalid token") user = await User.get(parsed_token["id"]) if user.email_verified: return jsonify("Email already verified") await user.update(email_verified=True).apply() return jsonify("Email verified") @route("/api/v1/search", methods=["GET"]) @json @use_kwargs({ "q": fields.Str(required=True) }, locations=("query",)) async def search(self, q: str): like = f"%{q}%" mods = await Mod.query.where(or_( Mod.title.match(q), Mod.tagline.match(q), Mod.description.match(q), Mod.title.ilike(like), Mod.tagline.ilike(like), Mod.description.ilike(like) )).limit(5).gino.all() users = await User.query.where(or_( User.username.match(q), User.username.ilike(like) )).limit(5).gino.all() return jsonify(mods=self.dict_all(mods), users=self.dict_all(users))
class PlayListEntitySchema(Schema): id = fields.Str() title = fields.Str() description = fields.Str() thumbnail_url = fields.URL() url = fields.URL()
class EchoWithParamHandler(tornado.web.RequestHandler): ARGS = {"name": fields.Str()} @use_args(ARGS) def get(self, id, args): self.write(args)
class ProgressPodcastSchema(Schema): id = fields.Int() name = fields.Str() image_url = fields.URL()
class AlwaysFailHandler(tornado.web.RequestHandler): ARGS = {"name": fields.Str(validate=always_fail)} @use_args(ARGS) def post(self, args): self.write(args)
from webservices import docs from webservices import sorting from webservices import decoders from webservices import exceptions use_kwargs = functools.partial(use_kwargs_original, locations=('query', )) class Resource(six.with_metaclass(MethodResourceMeta, restful.Resource)): pass API_KEY_ARG = fields.Str( required=True, missing='DEMO_KEY', description=docs.API_KEY_DESCRIPTION, ) if os.getenv('PRODUCTION'): Resource = use_kwargs({'api_key': API_KEY_ARG})(Resource) def check_cap(kwargs, cap): if cap: if not kwargs.get('per_page') or kwargs['per_page'] > cap: raise exceptions.ApiError( 'Parameter "per_page" must be between 1 and {}'.format(cap), status_code=422, )
def test_arg_allow_none(parser, web_request): web_request.json = {"first": "Steve", "last": None} args = {"first": fields.Str(), "last": fields.Str(allow_none=True)} result = parser.parse(args, web_request) assert result == {"first": "Steve", "last": None}
def test_arg_allow_none(parser, web_request): web_request.json = {'first': 'Steve', 'last': None} args = {'first': fields.Str(), 'last': fields.Str(allow_none=True)} result = parser.parse(args, web_request) assert result == {'first': 'Steve', 'last': None}
def test_get_value_multidict(input_dict): field = fields.List(fields.Str()) assert get_value(input_dict, "foos", field) == ["a", "b"]
def test_list_allowed_missing(web_request, parser): args = {'name': fields.List(fields.Str())} web_request.json = {'fakedata': True} result = parser.parse(args, web_request) assert result == {}
class PodcastCreateUpdateSchema(Schema): name = fields.Str(required=True, validate=validate.Length(min=1, max=256)) description = fields.Str() download_automatically = fields.Bool(default=True)
class Athlete(object): post_request_args = { "name": fields.Str(required=True), "email": fields.Str(required=True), "phone": fields.Int(required=True), "gender": fields.Str(required=True), "birthday": fields.Str(required=True) } def __init__(self, conn, database_service): self.conn, self.database_service, self.resource_name = conn, database_service, self.__class__.__name__ def on_delete(self, req, resp, id): try: q = " ".join([ "DELETE", "FROM", self.resource_name.lower(), "WHERE", self.resource_name.lower() + "_id = %s" ]) q_resp = self.database_service.run_delete_query(self.conn, q, [id]) if not q_resp['status']: output = { "status": True, "message": q_resp['message'], "data": None } else: output = { "status": True, "message": self.resource_name + " was deleted successfully!", "data": None } resp.status = falcon.HTTP_200 resp.body = output except Exception as error: output = {"status": False, "message": str(error), "data": None} resp.status = falcon.HTTP_500 resp.body = output def on_get(self, req, resp, id): try: cur = self.conn.cursor() q = " ".join([ "SELECT", "*", "FROM", self.resource_name.lower(), "wHERE", self.resource_name.lower() + "_id = %s" ]) q_resp = self.database_service.run_get_query(cur, q, [id]) if not q_resp['status']: output = { "status": True, "message": q_resp['message'], "data": None } else: output = { "status": True, "message": None, 'data': self.database_service.set_columns(q_resp['data'], cur) } resp.status = falcon.HTTP_200 resp.body = output except Exception as error: output = {"status": False, "message": str(error), "data": None} resp.status = falcon.HTTP_500 resp.body = output def on_get_collection(self, req, resp): try: cur = self.conn.cursor() q = " ".join(["SELECT * FROM", self.resource_name.lower()]) q_resp = self.database_service.run_get_query(cur, q, []) if not q_resp['status']: output = { "status": True, "message": q_resp['message'], "data": None } else: output = { "status": True, "message": None, 'data': self.database_service.set_columns(q_resp['data'], cur) } resp.status = falcon.HTTP_200 resp.body = output except Exception as error: output = {"status": False, "message": str(error), "data": None} resp.status = falcon.HTTP_500 resp.body = output def on_put(self, req, resp, id): try: cur = self.conn.cursor() get_q = " ".join([ "SELECT name,email,phone,gender,birthday FROM", self.resource_name.lower(), "wHERE", self.resource_name.lower() + "_id = %s" ]) get_resp = self.database_service.run_get_query(cur, get_q, [id]) record = list( self.database_service.set_columns(get_resp['data'], cur))[0] request = req.media for index in record.keys(): if index in request.keys(): record[index] = request[index] record['id'] = id update_q = " ".join([ "UPDATE", self.resource_name.lower(), "SET name=%s, email=%s, phone=%s, gender=%s, birthday=%s WHERE", self.resource_name.lower() + "_id=%s RETURNING ", self.resource_name.lower() + "_id;" ]) update_resp = self.database_service.run_upsert_query( self.conn, update_q, record.values()) if not update_resp['status']: output = { "status": True, "message": update_resp['message'], "data": None } else: response_data = { "id": update_resp['data'], "name": record['name'], "email": record['email'], "phone": record['phone'], "gender": record['gender'], "birthday": record['birthday'] } output = { "status": True, "message": self.resource_name + " is updated successfully!", "data": response_data } resp.status = falcon.HTTP_201 resp.body = output except Exception as error: output = {"status": False, "message": str(error), "data": None} resp.status = falcon.HTTP_500 resp.body = output @use_args(post_request_args) def on_post_collection(self, req, resp, args): try: q = " ".join([ "INSERT INTO", self.resource_name.lower(), "(name,email,phone,gender,birthday) VALUES (%s,%s,%s,%s,%s) RETURNING", self.resource_name.lower() + "_id;" ]) params = { 'name': args['name'], 'email': args['email'], 'phone': args['phone'], 'gender': args['gender'], 'birthday': args['birthday'] } q_resp = self.database_service.run_upsert_query( self.conn, q, params.values()) if not q_resp['status']: output = { "status": True, "message": q_resp['message'], "data": None } else: response_data = { "id": q_resp['data'], "name": args['name'], "email": args['email'], "phone": args['phone'], "gender": args['gender'], "birthday": args['birthday'] } output = { "status": True, "message": self.resource_name + " is added successfully!", "data": response_data } resp.status = falcon.HTTP_201 resp.body = output except Exception as error: output = {"status": False, "message": str(error), "data": None} resp.status = falcon.HTTP_500 resp.body = output
class EpisodeUpdateSchema(Schema): title = fields.Str(validate=validate.Length(max=256)) description = fields.Str() author = fields.Str(validate=validate.Length(max=256))
from server import model from server.database import db from server.response import respond, success from server.library.model import query from server.middleware import authorize from server.api.question import URL_PARAMS from server.exc import InvalidRequest, Unauthorized Note = Blueprint("note", __name__) @Note.route("/course/<course>/paper/<year>/<period>/q/<question>/note", methods=["POST"]) @use_kwargs(URL_PARAMS, locations=("view_args", )) @use_kwargs({ "link": fields.Str(required=True), "description": fields.Str(required=True), }) @authorize def create_link_note(course, year, period, question, link, description): question = model.Question.get_by_path(db.session, course, year, period, map(int, question.split("."))) note = model.NoteLink(link=link, description=description, user=g.user, question=question) db.session.add(note) db.session.commit() db.session.refresh(note) return respond({"question": question, "note": note})
import asyncio import aiohttp from aiohttp.web import json_response import marshmallow as ma from webargs import fields from webargs.aiohttpparser import parser, use_args, use_kwargs from webargs.core import json hello_args = {"name": fields.Str(missing="World", validate=lambda n: len(n) >= 3)} hello_multiple = {"name": fields.List(fields.Str())} class HelloSchema(ma.Schema): name = fields.Str(missing="World", validate=lambda n: len(n) >= 3) hello_many_schema = HelloSchema(many=True) # variant which ignores unknown fields hello_exclude_schema = HelloSchema(unknown=ma.EXCLUDE) ##### Handlers ##### async def echo(request): parsed = await parser.parse(hello_args, request, location="query") return json_response(parsed)