class InstituteList(AuthorizedResource):
    institute_obj = {
        'id': fields.Integer,
        'name': fields.String,
        'email': fields.String,
        'username': fields.String,
        'location': fields.String,
        'mobile_no': fields.String,
        'logo_url': fields.String,
        'joined_at': fields.DateTime,
        'last_activity': fields.DateTime,
        'type': fields.Integer
    }

    get_response = {
        'error': fields.Boolean(default=False),
        'institutes': fields.List(fields.Nested(institute_obj)),
        'total': fields.Integer
    }

    post_response = {
        'error': fields.Boolean(default=False),
        'institute': fields.Nested(institute_obj)
    }

    @marshal_with(get_response)
    def get(self, *args, **kwargs):
        parser = reqparse.RequestParser()
        parser.add_argument('page', type=int, default=1)
        parser.add_argument('limit',
                            type=int,
                            default=app.config['INSTITUTE_LIST_LIMIT'])
        args = parser.parse_args()
        institutes, total = Institute.get_list(args['page'], args['limit'])
        return {'institutes': institutes, 'total': total}

    @marshal_with(post_response)
    def post(self, *args, **kwargs):
        parser = reqparse.RequestParser()
        parser.add_argument('name', type=str, required=True)
        parser.add_argument('email', type=str, required=True)
        parser.add_argument('password', type=str, required=True)
        parser.add_argument('location', type=str, required=True)
        parser.add_argument('username', type=str, required=True)
        parser.add_argument('mobile_no', type=str, required=True)
        parser.add_argument('logo', type=str)
        args = parser.parse_args()

        if args['logo'] is not None:
            s3 = S3()
            mimetype, image_data = parse_base64_string(args['logo'])
            mimetype_parts = mimetype.split('/')
            if len(mimetype_parts) > 1 and mimetype_parts[-1] in app.config[
                    'ACCEPTED_IMAGE_EXTENSIONS']:
                # if mimetype has an extension and the extension is in the accepted list then proceed with the upload
                content_type = mimetype_parts[-1]
                url = s3.upload(image_data, content_type)
            else:
                raise UnAcceptableFileType
        else:
            url = None

        institute = Institute.create(name=args['name'],
                                     email=args['email'],
                                     password=md5(
                                         args['password']).hexdigest(),
                                     username=args['username'],
                                     location=args['location'],
                                     mobile_no=args['mobile_no'],
                                     logo_url=url)

        return {'institute': institute}
Ejemplo n.º 2
0
region_fields = {
    "id": fields.String(attribute="region_id"),
    "start_production_date": fields.String,
    "end_production_date": fields.String,
    "last_load_at": FieldDateTime(),
    "name": fields.String,
    "status": fields.String,
    "shape": fields.String,
    "error": NonNullNested({
        "code": fields.String,
        "value": fields.String
    })
}
regions_fields = OrderedDict([("regions",
                               fields.List(fields.Nested(region_fields)))])

collections = collections_to_resource_type.keys()


class Coverage(StatedResource):
    @clean_links()
    @add_coverage_link()
    @add_collection_links(collections)
    @marshal_with(regions_fields)
    def get(self, region=None, lon=None, lat=None):
        resp = i_manager.regions(region, lon, lat)
        if resp.has_key("regions"):
            resp["regions"] = sorted(
                resp["regions"],
                cmp=lambda reg1, reg2: cmp(reg1.get('name'), reg2.get('name')))
Ejemplo n.º 3
0
        self._register_interpreted_parameters(args)
        return i_manager.dispatch(args,
                                  self.endpoint,
                                  instance_name=self.region)


date_time = {
    "date_time": SplitDateTime(date='date', time='time'),
    "additional_informations": additional_informations(),
    "links": stop_time_properties_links()
}

row = {
    "stop_point": PbField(stop_point),
    "date_times": fields.List(fields.Nested(date_time))
}

header = {
    "display_informations":
    PbField(display_informations_vj, attribute='pt_display_informations'),
    "additional_informations":
    NonNullList(PbEnum(response_pb2.SectionAdditionalInformationType)),
    "links":
    UrisToLinks()
}
table_field = {
    "rows": fields.List(fields.Nested(row)),
    "headers": fields.List(fields.Nested(header))
}
Ejemplo n.º 4
0
#
# Stay tuned using
# twitter @navitia
# IRC #navitia on freenode
# https://groups.google.com/d/forum/navitia
# www.navitia.io

from __future__ import absolute_import, print_function, unicode_literals, division
from flask.ext.restful import Resource, fields, marshal_with
from jormungandr import i_manager
from jormungandr.interfaces.v1.serializer.api import GeoStatusSerializer
from jormungandr.interfaces.v1.decorators import get_serializer
from jormungandr.interfaces.v1.StatedResource import StatedResource

geo_status = {
        'geo_status': fields.Nested({'street_network_sources': fields.List(fields.String),
            'nb_admins': fields.Raw,
            'nb_admins_from_cities': fields.Raw,
            'nb_ways': fields.Raw,
            'nb_addresses': fields.Raw,
            'nb_pois': fields.Raw,
            'poi_sources': fields.List(fields.String),
        })
}


class GeoStatus(StatedResource):
    def __init__(self, *args, **kwargs):
        super(GeoStatus, self).__init__(output_type_serializer=GeoStatusSerializer, *args, **kwargs)

    @get_serializer(serpy=GeoStatusSerializer, marshall=geo_status)
Ejemplo n.º 5
0
    'max_duration_criteria': fields.Raw,
    'max_duration_fallback_mode': fields.Raw,
    'max_duration': fields.Raw,
    'walking_transfer_penalty': fields.Raw,
    'night_bus_filter_max_factor': fields.Raw,
    'night_bus_filter_base_factor': fields.Raw,
    'priority': fields.Raw,
    'bss_provider': fields.Boolean,
    'successive_physical_mode_to_limit_id': fields.Raw,
    'max_additional_connections': fields.Raw
}

instance_status_with_parameters = deepcopy(instance_status)
instance_status_with_parameters['parameters'] = fields.Nested(
    instance_parameters, allow_null=True)
instance_status_with_parameters['realtime_contributors'] = fields.List(
    fields.String(), attribute='rt_contributors')

instance_traveler_types = {
    'traveler_type': fields.String,
    'walking_speed': fields.Raw,
    'bike_speed': fields.Raw,
    'bss_speed': fields.Raw,
    'car_speed': fields.Raw,
    'wheelchair': fields.Boolean(),
    'max_walking_duration_to_pt': fields.Raw,
    'max_bike_duration_to_pt': fields.Raw,
    'max_bss_duration_to_pt': fields.Raw,
    'max_car_duration_to_pt': fields.Raw,
    'first_section_mode': fields.List(fields.String),
    'last_section_mode': fields.List(fields.String),
    'is_from_db': fields.Boolean(),
Ejemplo n.º 6
0
from flask import jsonify, Blueprint, abort
from flask.ext.restful import (Resource, Api, reqparse, inputs, fields,
                               marshal, marshal_with, url_for)

import models

course_fields = {
    'id': fields.Integer,
    'title': fields.String,
    'url': fields.String,
    'reviews': fields.List(fields.String),
    'created_at': fields.DateTime
}


def course_or_404(course_id):
    try:
        course = models.Course.get(models.Course.id == course_id)
    except models.Course.DoesNotExist:
        abort(404)
    else:
        return course


def add_reviews(course):
    course.reviews = [
        url_for('resources.reviews.review', id=review.id)
        for review in course.review_set
    ]
    return course
Ejemplo n.º 7
0
    def post(self):
        args = self.reqparse.parse_args()
        node = {
            'node_id': nodes[-1]['node_id'] + 1,
            'node': args['node'],
            'centrality': args['centrality']
        }
        nodes.append(node)
        return {'node': marshal(node, node_fields)}, 201


# --------- EDGES -----------------

edge_fields = {
    'name': fields.List(fields.String),
    # 'v1': fields.String,
    # 'v2': fields.String
}


# EdgeAPI
# shows a single edge with and lets you delete a edge
class EdgeAPI(Resource):
    def get(self, edge_id):
        abort_if_edge_doesnt_exist(edge_id)
        return edges[edge_id]

    def delete(self, edge_id):
        abort_if_edge_doesnt_exist(edge_id)
        del edges[edge_id]
Ejemplo n.º 8
0
    'name': fields.String,
    'status': fields.String,
    'ip': fields.String,
}

instance_fields = {
    'id': fields.String,
    'name': fields.String,
    'path': fields.String,
    'archive_url': fields.String,
    'git_reference': fields.String,
    'status': fields.Nested(status_fields),
    'environment': fields.String,
    'project': fields.Nested(project_wo_instance_fields),
    'host': fields.Nested(host_fields),
    'jeto_infos': fields.List(fields.String),
}


class InstancesApi(Resource):
    backend = None

    def __init__(self):
        self.backend = VagrantBackend()

    def get(self):
        instances = self.backend.get_all_instances()

        return {
            'instances': map(lambda t: marshal(t, instance_fields), instances),
        }
Ejemplo n.º 9
0
_reqparse = reqparse.RequestParser()

#
# customise by spec.
#

field_inputs_wrap['orderBy']['type'] = validate.str_in_list(
    default='name', argument=['name', 'type', 'description'])
field_inputs['srcIpAddrs'] = {
    # type attribute for marshal
    'type': {
        fields.List(
            fields.Nested({
                'id': {
                    'type': fields.Integer()
                },
                'name': {
                    'type': fields.String(attribute='name')
                }
            }))
    },
    # validate attribute for reqparse
    'validator': {
        fields.List(
            fields.Nested({
                'id': {
                    'type': validate.natural(default=1),
                    'required': True
                },
                'name': {
                    'type': validate.str_range(argument={
Ejemplo n.º 10
0
from .auth import abort_if_no_admin_auth

nested_role_fields = {
    'movie_id': fields.Integer(),
    'role_name': fields.String()
}

actor_fields = {
    'id': fields.Integer(),
    'first_name': fields.String(),
    'last_name': fields.String(),
    'birthday': fields.DateTime(dt_format='iso8601'),
    'deathday': fields.DateTime(dt_format='iso8601'),
    'hometown': fields.String(),
    'bio': fields.String(),
    'roles': fields.List(fields.Nested(nested_role_fields)),
}


class ActorAPI(Resource):
    @marshal_with(actor_fields)
    def get(self, actor_id=None):
        if actor_id:
            return Actor.query.get_or_404(actor_id)
        else:
            return Actor.query.all()

    def post(self, actor_id=None):
        if actor_id:
            abort(400)
        else:
Ejemplo n.º 11
0
collections = list(collections_to_resource_type.keys())

coverage_marshall_fields = [("regions",
                             fields.List(
                                 NonNullNested({
                                     "id":
                                     fields.String(attribute="region_id"),
                                     "start_production_date":
                                     fields.String,
                                     "end_production_date":
                                     fields.String,
                                     "last_load_at":
                                     FieldDateTime(),
                                     "name":
                                     fields.String,
                                     "status":
                                     fields.String,
                                     "shape":
                                     fields.String,
                                     "error":
                                     NonNullNested({
                                         "code": fields.String,
                                         "value": fields.String
                                     }),
                                     "dataset_created_at":
                                     fields.String(),
                                 })))]


class Coverage(StatedResource):
    def __init__(self, quota=True, *args, **kwargs):
Ejemplo n.º 12
0
import requests as req
from flask import request, json

from flask.ext.restful import Resource, fields, marshal
from flask.ext.login import current_user
from jeto.models.auditlog import auditlog
from jeto import app

htpassword_list_fields = {
    'slug': fields.String,
    'users': fields.List(fields.String),
}


class HtpasswordService(object):
    def _get_url(self):
        return 'http://' + app.config.get('HTPASSWORD_API_URL') + ':' +\
            app.config.get('HTPASSWORD_API_PORT')

    def _get_headers(self):
        return {
            "Content-Type": "application/json",
        }


class HtpasswordApi(Resource, HtpasswordService):
    def get(self):
        r = req.get(self._get_url())
        items = r.json()['lists']

        return {
Ejemplo n.º 13
0
class upload(DepositionType):
    """
    Zenodo deposition workflow
    """
    workflow = [
        p.IF_ELSE(
            has_submission,
            # Existing deposition
            [
                # Load initial record
                load_record(draft_id='_edit', post_process=process_draft),
                # Render the form and wait until it is completed
                render_form(draft_id='_edit'),
            ],
            # New deposition
            [
                # Load pre-filled data from cache
                prefill_draft(draft_id='_default'),
                # Render the form and wait until it is completed
                render_form(draft_id='_default'),
                # Test if all files are available for API
                api_validate_files(),
            ]),
        # Create the submission information package by merging data
        # from all drafts - i.e. generate the recjson.
        prepare_sip(),
        p.IF_ELSE(
            has_submission,
            [
                # Process SIP recjson
                process_sip_metadata(process_recjson_edit),
                # Merge SIP metadata into record and generate MARC
                merge_record(
                    draft_id='_edit',
                    post_process_load=process_draft,
                    process_export=process_recjson_edit,
                    merge_func=merge,
                ),
                # Set file restrictions
                process_bibdocfile(process=process_files),
            ],
            [
                # Check for reserved recids.
                reserved_recid(),
                # Reserve a new record id
                create_recid(),
                # Register DOI in internal pid store.
                mint_pid(
                    pid_field='doi',
                    pid_store_type='doi',
                    pid_creator=lambda recjson: create_doi(recid=recjson[
                        'recid'])['doi'],
                    existing_pid_checker=check_existing_pid,
                ),
                # Process SIP metadata
                process_sip_metadata(process_recjson_new),
            ]),
        # Generate MARC based on recjson structure
        finalize_record_sip(),
        p.IF_ELSE(
            has_submission,
            [
                # Seal the SIP and write MARCXML file and call bibupload on it
                upload_record_sip(),
                # Schedule background tasks.
                run_tasks(update=True),
            ],
            [
                # Note: after upload_record_sip(), has_submission will return
                # True no matter if it's a new or editing of a deposition.
                upload_record_sip(),
                run_tasks(update=False),
            ]),
    ]
    name = "Upload"
    name_plural = "Uploads"
    editable = True
    stopable = True
    enabled = True
    default = True
    api = True
    draft_definitions = {
        '_default': ZenodoForm,
        '_edit': ZenodoEditForm,
    }

    marshal_metadata_fields = dict(
        access_right=fields.String,
        communities=fields.List(fields.Raw),
        conference_acronym=fields.String,
        conference_dates=fields.String,
        conference_place=fields.String,
        conference_title=fields.String,
        conference_url=fields.String,
        conference_session=fields.String,
        conference_session_part=fields.String,
        creators=fields.Raw(default=[]),
        description=fields.String,
        doi=fields.String(default=''),
        embargo_date=ISODate,
        grants=fields.List(fields.Raw),
        image_type=fields.String(default=''),
        imprint_isbn=fields.String,
        imprint_place=fields.String,
        imprint_publisher=fields.String,
        journal_issue=fields.String,
        journal_pages=fields.String,
        journal_title=fields.String,
        journal_volume=fields.String,
        keywords=fields.Raw(default=[]),
        license=fields.String,
        notes=fields.String(default=''),
        partof_pages=fields.String,
        partof_title=fields.String,
        prereserve_doi=fields.Raw,
        publication_date=ISODate,
        publication_type=fields.String(default=''),
        references=fields.List(fields.String, default=[]),
        related_identifiers=fields.Raw(default=[]),
        thesis_supervisors=fields.Raw(default=[]),
        title=fields.String,
        upload_type=fields.String,
    )

    marshal_metadata_edit_fields = marshal_metadata_fields.copy()
    del marshal_metadata_edit_fields['prereserve_doi']
    #marshal_metadata_edit_fields.update(dict(
    #    recid=fields.Integer,
    #    version_id=UTCISODateTime,
    #))

    marshal_deposition_fields = DepositionType.marshal_deposition_fields.copy()
    del marshal_deposition_fields['drafts']

    marshal_draft_fields = DepositionType.marshal_draft_fields.copy()
    marshal_draft_fields['metadata'] = fields.Nested(marshal_metadata_fields,
                                                     attribute='values')
    del marshal_draft_fields['id']
    del marshal_draft_fields['completed']

    @classmethod
    def default_draft_id(cls, deposition):
        if deposition.has_sip() and '_edit' in deposition.drafts:
            return '_edit'
        return '_default'

    @classmethod
    def marshal_deposition(cls, deposition):
        """
        Generate a JSON representation for REST API of a Deposition
        """
        # Get draft
        if deposition.has_sip() and '_edit' in deposition.drafts:
            draft = deposition.get_draft('_edit')
            metadata_fields = cls.marshal_metadata_edit_fields
        elif deposition.has_sip():
            # FIXME: Not based on latest available data in record.
            sip = deposition.get_latest_sip(sealed=True)
            draft = record_to_draft(Record.create(sip.package,
                                                  master_format='marc'),
                                    post_process=process_draft)
            metadata_fields = cls.marshal_metadata_edit_fields
        else:
            draft = deposition.get_or_create_draft('_default')
            metadata_fields = cls.marshal_metadata_fields

        # Fix known differences in marshalling
        draft.values = filter_empty_elements(draft.values)
        if 'grants' not in draft.values:
            draft.values['grants'] = []

        # Set disabled values to None in output
        for field, flags in draft.flags.items():
            if 'disabled' in flags and field in draft.values:
                del draft.values[field]

        # Marshal deposition
        obj = marshal(deposition, cls.marshal_deposition_fields)
        # Marshal the metadata attribute
        obj['metadata'] = marshal(unicodifier(draft.values), metadata_fields)

        # Add record and DOI information from latest SIP
        for sip in deposition.sips:
            if sip.is_sealed():
                recjson = sip.metadata
                if recjson.get('recid'):
                    obj['record_id'] = fields.Integer().format(
                        recjson.get('recid'))
                    obj['record_url'] = fields.String().format(
                        url_for('record.metadata',
                                recid=recjson.get('recid'),
                                _external=True))
                if recjson.get('doi') and \
                   recjson.get('doi').startswith(cfg['CFG_DATACITE_DOI_PREFIX']
                                                +"/"):
                    obj['doi'] = fields.String().format(recjson.get('doi'))
                    obj['doi_url'] = fields.String().format(
                        "http://dx.doi.org/%s" % obj['doi'])
                break

        return obj

    @classmethod
    def marshal_draft(cls, obj):
        """
        Generate a JSON representation for REST API of a DepositionDraft
        """
        return marshal(obj, cls.marshal_draft_fields)

    @classmethod
    def api_action(cls, deposition, action_id):
        if action_id == 'publish':
            return deposition.run_workflow(headless=True)
        elif action_id == 'edit':
            # Trick: Works in combination with load_record task to provide
            # proper response codes to API clients.
            if deposition.state == 'done' or deposition.drafts:
                deposition.reinitialize_workflow()
            return deposition.run_workflow(headless=True)
        elif action_id == 'discard':
            deposition.stop_workflow()
            deposition.save()
            return deposition.marshal(), 201
        raise InvalidApiAction(action_id)

    @classmethod
    def api_metadata_schema(cls, draft_id):
        schema = super(upload, cls).api_metadata_schema(draft_id)
        if schema and draft_id == '_edit':
            if 'recid' in schema['schema']:
                del schema['schema']['recid']
            if 'modification_date' in schema['schema']:
                del schema['schema']['modification_date']
        return schema

    @classmethod
    def render_completed(cls, d):
        """
        Render page when deposition was successfully completed
        """
        ctx = dict(
            deposition=d,
            deposition_type=(None if d.type.is_default() else
                             d.type.get_identifier()),
            uuid=d.id,
            my_depositions=Deposition.get_depositions(current_user,
                                                      type=d.type),
            sip=d.get_latest_sip(),
            format_record=format_record,
        )

        return render_template('deposit/completed.html', **ctx)
Ejemplo n.º 14
0
    'found': fields.Boolean(),
    'links': FareLinks(attribute="ticket_id")
}

journey = {
    'duration': fields.Integer(),
    'nb_transfers': fields.Integer(),
    'departure_date_time': DateTime(),
    'arrival_date_time': DateTime(),
    'requested_date_time': DateTime(),
    'sections': NonNullList(NonNullNested(section)),
    'from': PbField(place, attribute='origin'),
    'to': PbField(place, attribute='destination'),
    'type': fields.String(),
    'fare': NonNullNested(fare),
    'tags': fields.List(fields.String),
    "status": enum_type(attribute="message_status"),
    "calendars": NonNullList(NonNullNested(calendar)),
}

ticket = {
    "id": fields.String(),
    "name": fields.String(),
    "comment": fields.String(),
    "found": fields.Boolean(),
    "cost": NonNullNested(cost),
    "links": TicketLinks(attribute="section_id")
}
journeys = {
    "journeys": NonNullList(NonNullNested(journey)),
    "error": PbField(error, attribute='error'),
Ejemplo n.º 15
0
project_full_resource_fields.pop('longitude')
project_full_resource_fields.pop('region')
project_full_resource_fields["description"] = fields.String
project_full_resource_fields["motivation"] = fields.String
project_full_resource_fields["goal"] = fields.String
project_full_resource_fields["about"] = fields.String
project_full_resource_fields["currency"] = fields.String
project_full_resource_fields["currency_rate"] = fields.Float
project_full_resource_fields["scope"] = fields.String
project_full_resource_fields["date_created"] = DateTime
project_full_resource_fields["date_published"] = DateTime
project_full_resource_fields["date_updated"] = DateTime
project_full_resource_fields["date_succeeded"] = DateTime
project_full_resource_fields["date_closed"] = DateTime
project_full_resource_fields["date_passed"] = DateTime
project_full_resource_fields["location"] = fields.List(
    fields.Nested(location_resource_fields))
project_full_resource_fields["user"] = fields.Nested(user_resource_fields)
project_full_resource_fields["widget_url"] = fields.String
project_full_resource_fields["image_url_big"] = fields.String
project_full_resource_fields["image_gallery"] = fields.List(
    fields.Nested(project_gallery_resource_fields))
project_full_resource_fields["video_url"] = fields.String
project_full_resource_fields["rewards"] = fields.List(
    fields.Nested(project_reward_resource_fields))
project_full_resource_fields["costs"] = fields.List(
    fields.Nested(project_cost_resource_fields))
project_full_resource_fields["needs"] = fields.List(
    fields.Nested(project_need_resource_fields))

project_full_translate_resource_fields = {
    k: v
Ejemplo n.º 16
0
class GeocodejsonFeature(fields.Raw):
    def format(self, place):
        type_ = place.get('properties', {}).get('geocoding', {}).get('type')

        if type_ not in geocode_feature_func_mapping:
            logging.getLogger(__name__).error(
                'Place not serialized (unknown type): {}'.format(place))
            return None

        return marshal(place, geocode_feature_func_mapping[type_])


geocodejson = {
    "places":
    fields.List(GeocodejsonFeature, attribute='features'),
    "warnings":
    ListLit([fields.Nested(beta_endpoint)]),
    "feed_publishers":
    ListLit([
        fields.Nested(feed_publisher_bano),
        fields.Nested(feed_publisher_osm)
    ])
}


class GeocodeJson(AbstractAutocomplete):
    """
    Autocomplete with an external service returning geocodejson
    (https://github.com/geocoders/geocodejson-spec/)
Ejemplo n.º 17
0
    'committee_name': fields.String,
    'link_date': fields.String,
    'expire_date': fields.String,
    'committee_type': fields.String,
    'committee_type_full': fields.String,
    'committee_designation': fields.String,
    'committee_designation_full': fields.String,
    'election_year': fields.Integer,
}
candidate_fields = {
    'candidate_id': fields.String,
    'candidate_status_full': fields.String,
    'candidate_status': fields.String,
    'district': fields.String,
    'active_through': fields.Integer,
    'election_years': fields.List(fields.Integer),
    'incumbent_challenge_full': fields.String,
    'incumbent_challenge': fields.String,
    'office_full': fields.String,
    'office': fields.String,
    'party_full': fields.String,
    'party': fields.String,
    'state': fields.String,
    'name': fields.String,
}
candidate_detail_fields = {
    'candidate_id': fields.String,
    'candidate_status_full': fields.String,
    'candidate_status': fields.String,
    'district': fields.String,
    'active_through': fields.Integer,
Ejemplo n.º 18
0
    "min_duration": fields.Integer(),
    'from': PbField(place, attribute='origin'),
    "to": PbField(place, attribute="destination"),
    'requested_date_time': DateTime(),
    'min_date_time': DateTime(),
    'max_date_time': DateTime()
}

graphical_isochrones = {
    "isochrones":
    NonNullList(NonNullNested(graphical_isochrone),
                attribute="graphical_isochrones"),
    "error":
    PbField(error, attribute='error'),
    "feed_publishers":
    fields.List(NonNullNested(feed_publisher)),
    "links":
    fields.List(Links()),
    "warnings":
    ListLit([fields.Nested(beta_endpoint)]),
}


class GraphicalIsochrone(JourneyCommon):
    def __init__(self):
        super(GraphicalIsochrone,
              self).__init__(output_type_serializer=None
                             )  #TODO implement and change to a real one
        parser_get = self.parsers["get"]
        parser_get.add_argument("min_duration",
                                type=UnsignedInteger(),
Ejemplo n.º 19
0
        self._register_interpreted_parameters(args)
        return i_manager.dispatch(args,
                                  self.endpoint,
                                  instance_name=self.region)


date_time = {
    "date_time": SplitDateTime(date='date', time='time'),
    "additional_informations": additional_informations(),
    "links": stop_time_properties_links(),
    'data_freshness': enum_type(attribute='realtime_level'),
}

row = {
    "stop_point": PbField(stop_point),
    "date_times": fields.List(fields.Nested(date_time))
}

header = {
    "display_informations":
    PbField(display_informations_vj, attribute='pt_display_informations'),
    "additional_informations":
    NonNullList(PbEnum(response_pb2.SectionAdditionalInformationType)),
    "links":
    UrisToLinks()
}
table_field = {
    "rows": fields.List(fields.Nested(row)),
    "headers": fields.List(fields.Nested(header))
}
Ejemplo n.º 20
0
import six

line_report = {
    "line": PbField(line),
    "pt_objects": NonNullList(NonNullNested(pt_object)),
}

line_reports = {
    "line_reports":
    NonNullList(NonNullNested(line_report)),
    "error":
    PbField(error, attribute='error'),
    "pagination":
    NonNullNested(pagination),
    "disruptions":
    fields.List(NonNullNested(disruption_marshaller), attribute="impacts"),
    "warnings":
    ListLit([fields.Nested(beta_endpoint)]),
}


class LineReports(ResourceUri):
    def __init__(self):
        ResourceUri.__init__(self,
                             output_type_serializer=api.LineReportsSerializer)
        parser_get = self.parsers["get"]
        parser_get.add_argument("depth",
                                type=int,
                                default=1,
                                help="The depth of your object")
        parser_get.add_argument("count",
Ejemplo n.º 21
0
def get_answer_pairings_new():
    ret = {
        'id': fields.Integer,
        'answers': fields.List(fields.Nested(get_posts_for_answers())),
    }
    return ret
class QuestionUploadSetList(AuthorizedResource):

    mock_test_obj = {
        'name': fields.String
    }

    upload_set_obj = {
        'id': fields.Integer,
        'name': fields.String,
        'errors_exist': fields.Boolean,
        'mock_test_id': fields.Integer,
        'mock_test': fields.Nested(mock_test_obj),
        'questions_added': fields.Boolean,
    }

    get_response = {
        'total': fields.Integer,
        'error': fields.Boolean(default=False),
        'upload_sets': fields.List(fields.Nested(upload_set_obj)),
    }

    post_response = {
        'error': fields.Boolean(default=False),
        'upload_set': fields.Nested(upload_set_obj)
    }

    @marshal_with(get_response)
    def get(self, *args, **kwargs):
        
        parser = reqparse.RequestParser()
        parser.add_argument('page', type=int, default=1)
        parser.add_argument('limit', type=int, default=app.config['UPLOAD_SET_LIST_LIMIT'])
        args = parser.parse_args()

        # get a list of all the upload sets in the DB (without the questions)
        upload_set_pag_obj = QuestionUploadSet.query.filter().order_by(QuestionUploadSet.created_at.desc()).paginate(args['page'], args['limit'])
        upload_sets = upload_set_pag_obj.items
        total = upload_set_pag_obj.total

        # return a list of tests
        return {'upload_sets': upload_sets, 'total': total}

    @marshal_with(post_response)
    def post(self, *args, **kwargs):
        
        parse = reqparse.RequestParser()
        parse.add_argument('name', type=str, required=True)
        parse.add_argument('archive_key', type=str, required=True)
        parse.add_argument('mock_test_id', type=str, required=True)
        args = parse.parse_args()

        parse_upload_set_async.delay(args['name'], args['archive_key'], args['mock_test_id'])

        print 'this is done'

        return 'this is good shit'

        #print 'Checking S3 key'

        # check if the s3 key exists
        conn = S3Connection(app.config['S3_ACCESS_KEY'], app.config['S3_SECRET'])
        bucket = conn.get_bucket(app.config['S3_UPLOAD_SET_ARCHIVES_BUCKET'])
        archive_s3 = bucket.get_key(args['archive_key'])
        if not archive_s3:
            raise ArchiveS3KeyDoesNotExist

        #print 'S3 key checked'


        #print 'Checking mock test'

        # check if the mock test is open and has no questions
        mock_test_id = args['mock_test_id']
        mock_test = MockTest.query.get(mock_test_id)
        if not mock_test:
            raise InvalidMockTestId
        if not mock_test.question_ids is None:
            raise QuestionUploadSetMockSetNotEmpty

        #print 'Mock test checked'

        #print 'Getting contents from S3'

        # parse the paper and store it in json
        archive = StringIO()
        archive_s3.get_contents_to_file(archive)

        #print 'Contents from S3 got'
        
        #print 'parsing questions'
        parsed_questions = parse_paper(archive)
        #print 'questions parsed'

        # check the parsed questions for any `overall` errors. if there are then don't proceed
        if parsed_questions['is_overall_error']:
            error_message = '\n'.join([ exc.message for exc in parsed_questions['overall_errors'] ])
            raise OverallQuestionParsingError(error_message)

        # check if any errors exist or not
        errors = False
        try:
            check_if_errors_exist_in_parsed_questions(parsed_questions)
        except Exception as e:
            errors = True

        # store the parsed questions in the DB
        upload_set = QuestionUploadSet.create(
            name=args['name'],
            errors_exist=errors,
            mock_test_id=mock_test.id,
            parsed_questions=ExceptionJSONEncoder().encode(parsed_questions['questions']),
            parsed_comprehensions=ExceptionJSONEncoder().encode(parsed_questions['comprehensions'])
        )

        return {'upload_set': upload_set}
Ejemplo n.º 23
0
client = MongoClient()
print("Connected to MongoDB@localhost")

db = client.eduvideo
video_col = db.video
user_col = db.user
channel_col = db.channel
chunks_col = db.fs.chunks
files_col = db.fs.files

app = Flask(__name__, static_url_path="")
api = Api(app)
CORS(app)

usr_rates = {
    'good': fields.List(fields.String),
    'avg': fields.List(fields.String),
    'poor': fields.List(fields.String)
}

user_fields = {
    'username': fields.String,
    'password': fields.String,
    'usertype': fields.String,
    '_id': fields.String,
    'email': fields.String,
    'history': fields.List(fields.String),
    'rates': fields.Nested(usr_rates),
    'channel_ids': fields.List(fields.String),
    'subscribed_ids': fields.List(fields.String),
    'watch_later_ids': fields.List(fields.String),
Ejemplo n.º 24
0
    'found': fields.Boolean(),
    'links': FareLinks(attribute="ticket_id")
}

journey = {
    'duration': fields.Integer(),
    'nb_transfers': fields.Integer(),
    'departure_date_time': DateTime(),
    'arrival_date_time': DateTime(),
    'requested_date_time': DateTime(),
    'sections': NonNullList(NonNullNested(section)),
    'from': PbField(place, attribute='origin'),
    'to': PbField(place, attribute='destination'),
    'type': fields.String(),
    'fare': NonNullNested(fare),
    'tags': fields.List(fields.String),
    "status": fields.String(attribute="most_serious_disruption_effect"),
    "calendars": NonNullList(NonNullNested(calendar)),
    "co2_emission": NonNullNested({
        'value': fields.Raw,
        'unit': fields.String
    }),
    "durations": Durations(),
    "debug": JourneyDebugInfo()
}

ticket = {
    "id": fields.String(),
    "name": fields.String(),
    "comment": fields.String(),
    "found": fields.Boolean(),
Ejemplo n.º 25
0
    "name": fields.String,
    "address": {
        "id":
        fields.String,
        "coord": {
            "lon": fields.Float(attribute="coord.lon"),
            "lat": fields.Float(attribute="coord.lat"),
        },
        "house_number":
        fields.String,
        "label":
        fields.String(attribute="name"),
        "name":
        fields.String(attribute="street.street_name"),
        "administrative_regions":
        fields.List(fields.Nested(ww_admin),
                    attribute="street.administrative_region")
    }
}

ww_street = {
    "embeded_type": Lit("address"),
    #"id": id,
    "name": fields.String,
    "address": {
        #"id": id,
        #"coord": source["coord"],
        #"house_number": 0,
        "label":
        fields.String(attribute="name"),
        "name":
        fields.String(attribute="street_name"),
Ejemplo n.º 26
0
                  area=PolygonToLatLng(attribute='area'),
                  dimension=fields.String,
                  lot_area=fields.Float,
                  price_per_sq_mtr=fields.Float,
                  amount=fields.Float,
                  or_no=fields.String,
                  date_purchased=fields.DateTime("iso8601"),
                  status=fields.String,
                  remarks=fields.String,
                  date_created=fields.DateTime("iso8601"),
                  date_modified=fields.DateTime("iso8601"))

lot_create_fields = dict(status=fields.String,
                         message=fields.String,
                         lot=fields.Nested(lot_fields, allow_null=False))

ok_response = dict(status=fields.String, message=fields.String)

lot_client_create_fields = dict(
    status=fields.String,
    message=fields.String,
    client=fields.Nested(client_fields),
    lot=fields.Nested(lot_fields),
)

lot_complete_fields = copy(lot_fields)
lot_complete_fields['deceased'] = fields.List(fields.Nested(deceased_fields))
lot_complete_fields['client'] = fields.Nested(client_fields)

# lot_complete_fields['block'] = fields.Nested(block_basic_fields)
Ejemplo n.º 27
0
    'id': fields.Integer,
    'name': fields.String,
    'capacity': fields.Integer,
    'number_players': fields.Integer
}

enrollment_fields = {
    'number_players': fields.Integer,
    'team': fields.Nested(team_fields)
}

user_fields = {
    'id': fields.Integer,
    'username': fields.String,
    'email': fields.String,
    'teams_created': fields.List(fields.Nested(team_fields)),
    'teams': fields.List(fields.Nested(enrollment_fields))
}


class UserAPI(Resource):
    def get(self, id):
        user = User.query.get(id)
        if not user:
            return 'User not found', 404
        return {'user': marshal(user, user_fields)}


class UsersAPI(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
Ejemplo n.º 28
0
from jormungandr.interfaces.v1.fields import DateTime
from jormungandr.interfaces.v1.serializer.api import HeatMapSerializer
from jormungandr.interfaces.v1.decorators import get_serializer

heat_map = {
    "heat_matrix": JsonString(),
    'from': PbField(place, attribute='origin'),
    "to": PbField(place, attribute="destination"),
    'requested_date_time': DateTime()
}


heat_maps = {
    "heat_maps": NonNullList(NonNullNested(heat_map)),
    "error": PbField(error, attribute='error'),
    "links": fields.List(Links()),
    "warnings": ListLit([fields.Nested(beta_endpoint)]),
    "feed_publishers": fields.List(NonNullNested(feed_publisher)),
}


class HeatMap(JourneyCommon):

    def __init__(self):
        super(HeatMap, self).__init__(output_type_serializer=HeatMapSerializer)
        parser_get = self.parsers["get"]
        parser_get.add_argument("resolution", type=UnsignedInteger(), default=500)

    @get_serializer(serpy=HeatMapSerializer, marshall=heat_maps)
    @ManageError()
    def get(self, region=None, uri=None):
Ejemplo n.º 29
0
api = Api(app)
element_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'description': fields.String,
    'status': fields.Integer,
    'controller_id': fields.Integer
    #	'uri': fields.Url('controller')
}
controller_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'description': fields.String,
    'status': fields.Integer,
    'elements': fields.List(fields.Nested(element_fields)),
    'pipeRead': fields.String,
    'pipeWrite': fields.String
}


class ElementAPI(Resource):
    def __init__(self):
        #Will be used to parse our answers
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('name', type=str, location='json')
        self.reqparse.add_argument('description', type=str, location='json')
        self.reqparse.add_argument('status', type=int, location='json')
        self.reqparse.add_argument('controller_id', type=int, location='json')
        super(ElementAPI, self).__init__()
Ejemplo n.º 30
0
comment_fields = {
    'id': fields.Integer,
    'detail': fields.String,
    'create_at': TimeFormat(attribute='createAt'),
    'author': fields.Nested(user_fields)
}

comment_page_fields = {
    'total': fields.Integer,
    'has_prev': fields.Boolean,
    'prev_num': fields.Integer,
    'page': fields.Integer,
    'pages': fields.Integer,
    'has_next': fields.Boolean,
    'next_num': fields.Integer,
    'items': fields.List(fields.Nested(comment_fields))
}

blog_list_fields = {
    'id': fields.Integer,
    'title': fields.String,
    'content': ContentFormat,
    'create_at': DateFormat(attribute='createAt'),  #重命名属性
    'author': AuthorFormat, #格式化属性
    'ccount': fields.Integer
}

blog_fields = {
    'id': fields.Integer,
    'title': fields.String,
    'content': fields.String,