Example #1
0
 class ListSchema(Schema):
     foos = fields.List(fields.Str())
Example #2
0
import json
from django.http import HttpResponse
from django.views.generic import View

import marshmallow as ma
from webargs import fields, ValidationError
from webargs.djangoparser import parser, use_args, use_kwargs
from webargs.core import MARSHMALLOW_VERSION_INFO

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)


strict_kwargs = {'strict': True} if MARSHMALLOW_VERSION_INFO[0] < 3 else {}
hello_many_schema = HelloSchema(many=True, **strict_kwargs)


def json_response(data, **kwargs):
    return HttpResponse(json.dumps(data),
                        content_type='application/json',
                        **kwargs)


def echo(request):
    try:
Example #3
0
from webargs import fields, validate
from webargs.flaskparser import use_args


from optimizers import standard as optimize_standard, OptimizeError
from lineups import LineupError

app = Flask(__name__)
cors = CORS(app)

version_types = [ '0.2-lin-reg-dfn-min', '0.2-lin-reg-rg-min', '0.1-dfn', '0.1-rg']

optimize_args = {
    "date":    fields.Date(required=True),
    "site":    fields.String(require=True, validate=validate.OneOf(["fd"])),
    "exclude": fields.List(fields.Int(), missing=[]),
    "include": fields.List(fields.Int(), missing=[]),
    "version": fields.String(require=True, validate=validate.OneOf(version_types)),
}


# Return validation errors as JSON
@app.errorhandler(422)
@app.errorhandler(400)
def handle_error(err):
    headers = err.data.get("headers", None)
    messages = err.data.get("messages", ["Invalid request."])
    if headers:
        return jsonify({"errors": messages}), err.code, headers
    else:
        return jsonify({"errors": messages}), err.code
Example #4
0
    return {
        'per_page':
        per_page,
        'last_index':
        field(
            missing=None,
            description=description
            or 'Index of last result from previous page',
        ),
    }


names = {
    'q':
    fields.List(fields.Str,
                required=True,
                description='Name (candidate or committee) to search for'),
}

query = {
    'q':
    fields.Str(required=False,
               description='Text to search legal documents for.'),
    'from_hit':
    fields.Int(required=False,
               description='Get results starting from this index.'),
    'hits_returned':
    fields.Int(required=False,
               description='Number of results to return (max 10).'),
    'type':
    fields.Str(required=False,
Example #5
0
class TransactionInputEndpoint(Resource):
    """
    Class implementing transaction input API
    """
    args_transaction = {'transaction_ids': fields.List(fields.Integer())}

    @use_kwargs(args_transaction)
    def get(self, transaction_ids):
        """
        Method for GET request
        :param transaction_ids:
        """
        try:
            transaction_ids = list(set(list(transaction_ids)))
            request = {"transaction_ids": transaction_ids}
            response = {}
            # Validate User Input
            validations_result = validate_transaction_ids(transaction_ids)
            if validations_result is not None and len(validations_result) > 0:
                response = {
                    "ResponseCode":
                    ResponseCodes.InvalidRequestParameter.value,
                    "ResponseDesc": ResponseCodes.InvalidRequestParameter.name,
                    "ValidationErrors": validations_result
                }
            else:
                transaction_inputs_dict = {}
                for transaction_id in sorted(transaction_ids):
                    transaction_inputs = db_session.query(
                        TransactionInput).filter(
                            TransactionInput.transaction_id ==
                            transaction_id).all()
                    previous_output_ids = []
                    trans_input_list = []
                    total_num_of_inputs = 0

                    for transaction_input in transaction_inputs:
                        trans_input_as_dict = serialize_transaction_input(
                            transaction_input)
                        prev_output_id = trans_input_as_dict[
                            "PreviousTransactionOutputId"]

                        if prev_output_id is not None:
                            prev_out = db_session.query(Output).filter(
                                Output.id == prev_output_id).one()
                            trans_input_as_dict["Value"] = prev_out.value

                            previous_output_ids.append(prev_output_id)
                            prev_addresses = []
                            prev_address = db_session.query(
                                OutputAddress, Address).filter(
                                    OutputAddress.output_id == prev_output_id
                                ).filter(Address.id ==
                                         OutputAddress.address_id).all()
                            for address in prev_address:
                                address_as_dict = serialize_address(
                                    address.Address)
                                prev_addresses.append(address_as_dict)
                            trans_input_as_dict[
                                "InputAddresses"] = prev_addresses

                        trans_input_list.append(trans_input_as_dict)
                        total_num_of_inputs = total_num_of_inputs + 1
                    transaction_inputs_dict[transaction_id] = {
                        "NumberOfInputs": total_num_of_inputs,
                        "TransactionInputs": trans_input_list
                    }

                if total_num_of_inputs > 0:
                    response = {
                        'ResponseCode': ResponseCodes.Success.value,
                        'ResponseDesc': ResponseCodes.Success.name,
                        'TransactionInputData': transaction_inputs_dict
                    }
                else:
                    response = {
                        "ResponseCode": ResponseCodes.NoDataFound.value,
                        "ResponseDesc": ResponseCodes.NoDataFound.name,
                        "ErrorMessage": ResponseDescriptions.NoDataFound.value
                    }
        except Exception as ex:
            response = {
                "ResponseCode": ResponseCodes.InternalError.value,
                "ResponseDesc": ResponseCodes.InternalError.name,
                "ErrorMessage": str(ex)
            }
        finally:
            return response
Example #6
0
import asyncio

import aiohttp
import marshmallow as ma
from aiohttp import web
from aiohttp.web import json_response
from webargs import fields
from webargs.aiohttpparser import parser, use_args, use_kwargs
from webargs.core import MARSHMALLOW_VERSION_INFO, 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)

    if MARSHMALLOW_VERSION_INFO[0] < 3:

        class Meta:
            strict = True


strict_kwargs = {"strict": True} if MARSHMALLOW_VERSION_INFO[0] < 3 else {}
hello_many_schema = HelloSchema(many=True, **strict_kwargs)

# variant which ignores unknown fields
exclude_kwargs = ({
    "strict": True
Example #7
0
    "citizen_id": fields.Int(required=True),
    "town": fields.Str(required=True),
    "street": fields.Str(required=True),
    "building": fields.Str(required=True),
    "apartment": fields.Int(required=True),
    "name": fields.Str(required=True),
    "birth_date": fields.Str(
        validate=partial(check_valid_date, date_format=config['birth_date_format']),
        required=True
    ),
    "gender": fields.Str(
        validate=validate.OneOf(config['valid_genders']),
        required=True
    ),
    "relatives": fields.List(
        fields.Int(),
        required=True
    )
}

recieve_import_data_args = {
    "citizens": fields.List(
        fields.Nested(citizen_info, required=True),
        required=True
    )
}


update_citizen_info_args = {
    "town": fields.Str(),
    "street": fields.Str(),
    "building": fields.Str(),
Example #8
0
from pyramid.config import Configurator
import marshmallow as ma

from webargs import fields, ValidationError
from webargs.pyramidparser import parser, use_args, use_kwargs

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(strict=True, many=True)

def echo(request):
    return parser.parse(hello_args, request)

def echo_query(request):
    return parser.parse(hello_args, request, locations=('query', ))

@use_args(hello_args)
def echo_use_args(request, args):
    return args

@use_args({'value': fields.Int()}, validate=lambda args: args['value'] > 42)
def echo_use_args_validated(request, args):
    return args
Example #9
0
def make_multi_sort_args(default=None, validator=None, default_hide_null=False, default_reverse_nulls=True,
        default_nulls_only=False):
    args = make_sort_args(default, validator, default_hide_null, default_reverse_nulls, default_nulls_only)
    args['sort'] = fields.List(fields.Str, missing=default, validate=validator, required=False, allow_none=True,
        description='Provide a field to sort by. Use - for descending order.',)
    return args
Example #10
0
class AuthorSchema(ma.Schema):
    name = fields.Str(missing="World", validate=lambda n: len(n) >= 3)
    works = fields.List(fields.Str())
Example #11
0
 def test_it_should_parse_multiple_arg_required(self):
     args = {"foo": fields.List(fields.Int(), required=True)}
     request = make_json_request({})
     msg = "Missing data for required field."
     with pytest.raises(tornado.web.HTTPError, match=msg):
         parser.parse(args, request)
Example #12
0
 class CustomSchema(ma.Schema):
     works = fields.List(
         fields.Nested({
             "author": fields.Str(),
             "workname": fields.Str()
         }))
Example #13
0
from webargs import fields

from project.api.models import db, WebsiteDuplicated
from project.api.schemas import OneOf, length_validator
from project.api.exceptions.customs import RecordNotFound


def id_in_db(id):
    if not db.session.query(WebsiteDuplicated).filter_by(id=id).first():
        raise RecordNotFound('无此数据')


delete_args = {
    'ids': fields.List(fields.Int(validate=id_in_db), required=True)
}

restore_args = {
    'ids': fields.List(fields.Int(validate=id_in_db), required=True)
}

query_args = {
    'page': fields.Int(missing=0),
    'size': fields.Int(missing=25, validate=length_validator),
    'order': fields.Nested({
        'field': fields.Str(missing='create_time'),
        'direction': fields.Str(missing='desc', validate=OneOf(['asc', 'desc']))
    }, missing={}),
    'filter': fields.Nested({
        'url': fields.Str(),
        'title': fields.Str(),
        'effective_url': fields.Str()
Example #14
0
def test_int_list_allowed_missing(web_request, parser):
    args = {"name": fields.List(fields.Int())}
    web_request.json = {}
    result = parser.parse(args, web_request)
    assert result == {}
Example #15
0
def test_multiple_arg_required_with_int_conversion(web_request, parser):
    args = {'ids': fields.List(fields.Int(), required=True)}
    web_request.json = {'fakedata': True}
    with pytest.raises(ValidationError) as excinfo:
        parser.parse(args, web_request)
    assert excinfo.value.messages == {'ids': ['Missing data for required field.']}
Example #16
0
query_recycler_schema = {
    'start':
    fields.Int(missing=0),
    'length':
    fields.Int(missing=15, validate=length_validator),
    'order':
    fields.Nested(
        {
            'field':
            fields.Str(missing='create_time'),
            'direction':
            fields.Str(missing='desc', validate=OneOf(['asc', 'desc']))
        },
        missing={}),
    'fields':
    fields.List(fields.Str()),
    'filter':
    fields.Nested(
        {
            'url': fields.Str(missing=""),
            'title': fields.Str(missing=""),
            'domain': fields.Str(missing=""),
            'host_dept': fields.Str(missing="")
        },
        missing={})
}

delete_website_recycler_args = {
    'website_recycler_ids':
    fields.List(fields.Int(validate=website_id_in_db), required=True)
}
Example #17
0
def test_type_conversion_with_multiple_required(web_request, parser):
    web_request.json = {}
    args = {'ids': fields.List(fields.Int(), required=True)}
    with pytest.raises(ValidationError) as excinfo:
        parser.parse(args, web_request)
    assert 'Missing data for required field.' in str(excinfo)
Example #18
0
def test_parse_required_list(parser, web_request):
    web_request.json = {'bar': []}
    args = {'foo': fields.List(fields.Field(), required=True)}
    with pytest.raises(ValidationError) as excinfo:
        parser.parse(args, web_request)
    assert excinfo.value.messages['foo'][0] == 'Missing data for required field.'
Example #19
0
from . import messages
from . import util
from .download_file_and_redirect import download_file_and_redirect
from .git_progress import Progress
from .pull_from_remote import pull_from_remote
from .config import Config

thread_pool = ThreadPoolExecutor(max_workers=4)

url_args = {
    'file_url': fields.Str(),
    'domain': fields.Str(),
    'account': fields.Str(),
    'repo': fields.Str(),
    'branch': fields.Str(),
    'path': fields.List(fields.Str()),
    'notebook_path': fields.Str(),
}


class LandingHandler(IPythonHandler):
    """
    Landing page containing option to download.

    Option 1
    --------

        ?file_url=public_file_url

    Example: ?file_url=http://localhost:8000/README.md
Example #20
0
def test_parse_list_allow_none(parser, web_request):
    web_request.json = {'foo': None}
    args = {'foo': fields.List(fields.Field(allow_none=True), allow_none=True)}
    assert parser.parse(args, web_request) == {'foo': None}
Example #21
0
@app.route("/orders/<int:order_id>", methods=["GET"])
@marshal_with(OrderSchema())
def route_order_get_by_id(order_id):
    order = Order.query.filter(Order.id == order_id).first()
    if not order:
        return abort(400,
                     "The order with id: {0} does not exists".format(order_id))
    return order


@app.route("/orders", methods=["POST"])
@marshal_with(OrderSchema())
@use_kwargs({
    "buyer_id": fields.Int(),
    "seller_id": fields.Int(),
    "line_items": fields.List(fields.Dict()),
})
def route_order_create(buyer_id, seller_id, line_items):
    order = Order(buyer_id=buyer_id, seller_id=seller_id, line_items=[])
    total = 0
    for li in line_items:
        product = Product.query.filter(Product.id == li['product_id']).first()
        total += li['quantity'] * product.price
        item = LineItem(product=product,
                        order=order,
                        quantity=li['quantity'],
                        unit_price=li['quantity'] * product.price)
        order.line_items.append(item)
    order.total = total
    db.session.add(order)
    db.session.commit()
Example #22
0
def test_parse_list_dont_allow_none(parser, web_request):
    web_request.json = {'foo': None}
    args = {'foo': fields.List(fields.Field(), allow_none=False)}
    with pytest.raises(ValidationError) as excinfo:
        parser.parse(args, web_request)
    assert excinfo.value.messages['foo'][0] == 'Field may not be null.'
Example #23
0
    'bounds': fields.Nested({
        'north_east': fields.Nested({'lat': fields.Float(), 'lng': fields.Float()}, required=True),
        'south_west': fields.Nested({'lat': fields.Float(), 'lng': fields.Float()}, required=True)
    }, required=True)
}

_create_args = {
    **_base_args,
    'name': fields.String(required=True)
}

_update_args = {
    'areas': fields.List(
        fields.Nested({
            **_base_args,
            'id': fields.Int(required=True),
            'name': fields.String()
        }, required=True)
    )
}


class RHMapAreas(RHRoomBookingAdminBase):
    @use_args(_create_args)
    def _process_POST(self, args):
        create_area(**args)
        return map_areas_schema.jsonify(MapArea.query)

    @use_kwargs(_update_args)
    def _process_PATCH(self, areas):
        for area in areas:
Example #24
0
def test_parse_missing_list(parser, web_request):
    web_request.json = {}
    args = {'things': fields.List(fields.Field())}
    assert parser.parse(args, web_request) == {}
Example #25
0
from indico.modules.rb.models.rooms import Room
from indico.modules.rb_new.schemas import aspects_schema, map_rooms_schema, room_details_schema, rooms_schema
from indico.modules.rb_new.util import (
    get_buildings, get_equipment_types, get_existing_room_occurrences,
    get_rooms_availability, get_suggestions, group_by_occurrence_date,
    has_managed_rooms, search_for_rooms, serialize_occurrences)
from indico.modules.users.models.users import User
from indico.util.date_time import iterdays
from indico.util.i18n import _
from indico.web.util import jsonify_data

NUM_SUGGESTIONS = 5

search_room_args = {
    'capacity': fields.Int(),
    'equipment': fields.List(fields.Str()),
    'favorite': fields.Bool(),
    'mine': fields.Bool(),
    'text': fields.Str(),
    'start_dt': fields.DateTime(),
    'end_dt': fields.DateTime(),
    'repeat_frequency': EnumField(RepeatFrequency),
    'repeat_interval': fields.Int(missing=0),
    'building': fields.Str(),
    'floor': 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)
}
Example #26
0
def test_get_value_multidict(input_dict):
    field = fields.List(fields.Str())
    assert get_value(input_dict, 'foos', field) == ['a', 'b']
Example #27
0
blueprint = Blueprint("inspirehep_curation", __name__, url_prefix="/curation")
parser = FlaskParser()


@parser.error_handler
def handle_error(error, req, schema, error_status_code, error_headers):
    message = f"Incorrect input type for fields: {''.join(error.field_names)}"
    abort(400, message)


@blueprint.route("/literature/<int:pid_value>/keywords", methods=["PUT"])
@login_required_with_roles([Roles.cataloger.value])
@parser.use_args(
    {
        "_desy_bookkeeping": fields.Dict(required=False),
        "keywords": fields.List(fields.String, required=False),
        "energy_ranges": fields.List(fields.String, required=False),
    },
    locations=("json",),
)
def add_keywords(args, pid_value):
    keywords = args.get("keywords")
    desy_bookkeeping = args.get("_desy_bookkeeping")
    energy_ranges = args.get("energy_ranges")
    if not any([keywords, desy_bookkeeping, energy_ranges]):
        return (
            jsonify(
                success=False,
                message="None of required fields was passed",
            ),
            400,
Example #28
0
def test_int_list_allowed_missing(web_request, parser):
    args = {'name': fields.List(fields.Int())}
    web_request.json = {'fakedata': True}
    result = parser.parse(args, web_request)
    assert result == {}
Example #29
0
 def test_it_should_parse_multiple_arg_required(self):
     args = {'foo': fields.List(fields.Int(), required=True)}
     request = make_json_request({})
     with pytest.raises(tornado.web.HTTPError) as excinfo:
         parser.parse(args, request)
     assert 'Missing data for required field.' in str(excinfo)
Example #30
0
def test_parse_empty_list(parser, web_request):
    web_request.json = {"things": []}
    args = {"things": fields.List(fields.Field())}
    assert parser.parse(args, web_request) == {"things": []}