Exemple #1
0
class Mall(object):

    resource_fields = {
        'mall_id': fields.Integer(),
        'name': fields.String(),
        'address': fields.Raw(),
        'contact': fields.String(),
        'country': fields.String(),
        'district': fields.String(),
        'city': fields.String(),
        'location': fields.Raw()
    }
    required = ['name']
Exemple #2
0
 def get_serializable_entries(self, entries):
     endpoint = format_endpoint(GetEntry, self.dict_id)
     marshaled_entries = []
     for entry in entries:
         entry.content['entry_id'] = entry.content['id']
         entry_fields = {
             'content': fields.Raw(default=entry.content['content']),
             'id': fields.String(),
             'name': fields.String(),
             'references': fields.Raw(default=entry.content['references']),
             'url': fields.Url(endpoint=endpoint, absolute=True),
         }
         marshaled_entries.append(marshal(entry.content, entry_fields))
     return marshaled_entries
Exemple #3
0
 def test_nested_raw_field(self):
     foo = Mock()
     bar = Mock()
     bar.value = 3
     foo.bar = bar
     field = fields.Raw()
     self.assertEquals(field.output("bar.value", foo), 3)
Exemple #4
0
class ModelResult(object):
    """The result of a call to /model"""
    resource_fields = {
        'modelInfo': fields.Raw()
    }

    def __init__(self, model_info):
        self.modelInfo = model_info
        logger.debug(f'Created response: {self.__dict__}')
Exemple #5
0
class RequestDonations(object):
    """docstring for User"""

    resource_fields = {
        'donation_id': fields.Integer(),
        'blood_type': fields.String(),
        'notes': fields.String(),
        'request_date': fields.Integer(),
        'requisite_number': fields.Integer(),
        'user': fields.Raw(),
    }

    required = []
class IncidentEvents(Resource):
    @marshal_with({
        "id": fields.String,
        "action": fields.String(default=None),
        "reference_id": fields.Integer(default=None),
        "linked_event": fields.String,
        "description": fields.String,
        "intiator": fields.String,
        "incident_id": fields.Integer,
        "affected_attribute": fields.String,
        "created_date": fields.Integer,
        "approved_date": fields.Integer(default=None),
        "data": fields.Raw(default=None)
    })
    def get(self, incident_id):
        """get all events of an incident in the chronological order"""
        print(get_incident_events(incident_id)[0].__dict__)

        return get_trail_events(incident_id)
Exemple #7
0
# -*- coding: utf-8 -*-

from __future__ import absolute_import, unicode_literals

from flask_restful import fields

from utils.response import MESSAGE

resource_fields = {
    "code": fields.Integer,
    "message": fields.String,
    "data": fields.Raw(default=None)
}


class APIResponse(object):

    def __init__(self, code=0, message="success", data=None):
        if not message:
            message = MESSAGE.get(code)
        self.code = code
        self.message = message
        self.data = data

    def to_json(self):
        return {
            "code": self.code,
            "message": self.message,
            "data": self.data
        }
Exemple #8
0
 def test_raw_field(self):
     obj = Mock()
     obj.foo = 3
     field = fields.Raw()
     self.assertEquals(field.output("foo", obj), 3)
Exemple #9
0
    Checker,
    WhiteListMask,
    BlackListMask,
    SubsetComparator,
    RetrocompatibilityMask,
    StopScheduleIDGenerator,
    PerfectComparator,
)
import re
"""
The default behaviour for journeys is to check only a subset journey

the mask create a new dict filtering only the wanted elt
"""
fare = {
    "total": fields.Raw(attribute="total.value"),
    "currency": fields.Raw(attribute="total.currency"),
}

distances = {
    "bike": fields.Raw,
    "car": fields.Raw,
    "walking": fields.Raw,
    "taxi": fields.Raw,
}

durations = {
    "bike": fields.Raw,
    "car": fields.Raw,
    "total": fields.Raw,
    "walking": fields.Raw,
Exemple #10
0
import datetime
import logging
import threading
import time

from flask_restful import fields

from core.handler import CSVLogger, AsyncHandler
from core.interface import RecordingDeviceStatus, DATETIME_FORMAT, API_PREFIX

logger = logging.getLogger('analyser.devicecontroller')

deviceFields = {
    'deviceId': fields.String,
    'lastUpdateTime': fields.DateTime,
    'state': fields.Raw(attribute='payload')
}


class Device(object):
    """
    the analyser view of a device which includes the payload sent by the device along with information for our own
    housekeeping.
    """

    def __init__(self, maxAgeSeconds):
        self.deviceId = None
        self.payload = None
        self.lastUpdateTime = None
        self.dataHandler = None
        self.maxAgeSeconds = maxAgeSeconds
Exemple #11
0
test_resource_fields = {
    'id': fields.Raw,
    'name': fields.String,
    }

teststructure_resource_fields = {
    'test': fields.Nested(test_resource_fields),
    'structure': fields.Nested(structure_resource_fields),
    }

testresult_resource_fields = {
    'id': fields.String,
    'test': fields.Nested(test_resource_fields),
    'method': fields.Nested(method_resource_fields),
    'ctime': fields.String,
    'data': fields.Raw(attribute='result_data'),
    }


class ParameterError(Exception):
    pass


class TaskResource(Resource):
    @marshal_with(task_resource_fields)
    def get(self, id):
        return (Task.query
                .options(joinedload("method"))
                .options(joinedload("structure"))
                .get_or_404(id))
Exemple #12
0
admin_member_match_sell_order_fields = {
    'created_timestamp':
    fields.Integer,
    'updated_timestamp':
    fields.Integer,
    'buy_number':
    fields.String,
    'current_price':
    fields.String,
    'payment_amount':
    fields.String,
    'payment':
    fields.Nested(admin_member_payment_fields),
    'proof_img':
    fields.Raw(
        attribute=lambda x: None if x is None else json.loads(x.proof_img)),
    'buy_user':
    fields.Nested(admin_member_user_fields)
}

admin_member_sell_order_detail_fields = {
    'id':
    fields.Integer,
    'created_timestamp':
    fields.Integer,
    'updated_timestamp':
    fields.Integer,
    'number':
    fields.String,
    'amount':
    fields.String,
Exemple #13
0
def dump_geo(data):
    if data is None:
        return None
    p = wkb.loads(data, hex=True)
    return geometry.mapping(p)


resource_fields = {
    'properties': {
        'seq': fields.Integer,
        'street': fields.String,
        'distance': fields.Float,  # feet
        'travel_time': fields.Float,
        # 'feature_type': fields.String,
    },
    'geometry': fields.Raw(attribute=lambda x: dump_geo(x.geom))
}


class GeoRouter(Resource):
    @marshal_with(resource_fields, envelope='features')
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('orig', type=str, trim=True, required=True)
        parser.add_argument('dest', type=str, trim=True, required=True)
        parser.add_argument('mode', type=str, trim=True, required=True)
        args = parser.parse_args()
        if args['mode'] == 'drive':
            route_result = db.engine.execute(
                "SELECT * FROM getdrivingroute({},{})".format(
                    args['orig'], args['dest']))
Exemple #14
0
instance_status = {
    "data_version": fields.Integer(),
    "end_production_date": fields.String(),
    "is_connected_to_rabbitmq": fields.Boolean(),
    "last_load_at": fields.String(),
    "last_rt_data_loaded": fields.String(),
    "last_load_status": fields.Boolean(),
    "kraken_version": fields.String(attribute="navitia_version"),
    "nb_threads": fields.Integer(),
    "publication_date": fields.String(),
    "start_production_date": fields.String(),
    "status": fields.String(),
    "is_open_data": fields.Boolean(),
    "is_open_service": fields.Boolean(),
    "is_realtime_loaded": fields.Boolean(),
    "realtime_proxies": fields.Raw(),
    "dataset_created_at": fields.String(),
    "autocomplete": fields.Raw(),
    "street_networks": fields.Raw(),
    "ridesharing_services": fields.Raw(),
}

instance_parameters = {
    'scenario': fields.Raw(attribute='_scenario_name'),
    'journey_order': fields.Raw,
    '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,
    'max_car_no_park_duration_to_pt': fields.Raw,
    'max_nb_transfers': fields.Raw,
Exemple #15
0
from flask import request
from flask_restful import fields, marshal_with

from opencve.api.base import BaseResource
from opencve.api.cves import cves_fields
from opencve.api.fields import DatetimeField
from opencve.controllers.alerts import AlertController
from opencve.controllers.reports import ReportController
from opencve.models.users import User

alert_fields = {
    "id": fields.String(attribute="id"),
    "created_at": DatetimeField(),
    "cve": fields.String(attribute="cve.cve_id"),
    "details": fields.Raw(attribute="details"),
}

event_fields = {
    "cve": fields.String(attribute="cve.cve_id"),
    "type": fields.String(attribute="type.code"),
    "details": fields.Raw(attribute="details"),
}


class AlertListResource(BaseResource):
    @marshal_with(alert_fields)
    def get(self, link):
        report = ReportController.get({"public_link": link})
        return AlertController.list_items({"report_id": report.id})

Exemple #16
0
cves_fields = {
    "id": fields.String(attribute="cve_id"),
    "summary": fields.String(attribute="summary"),
    "created_at": DatetimeField(),
    "updated_at": DatetimeField(),
}

cve_fields = dict(
    cves_fields, **{
        "cvss": {
            "v2": fields.Float(attribute="cvss2"),
            "v3": fields.Float(attribute="cvss3"),
        },
        "vendors": CveVendorsField(attribute="json"),
        "cwes": fields.Raw(),
        "raw_nvd_data": fields.Raw(attribute="json"),
    })


class CveListResource(BaseResource):
    @marshal_with(cves_fields)
    def get(self):
        return CveController.list_items(request.args)


class CveResource(BaseResource):
    @marshal_with(cve_fields)
    def get(self, id):
        return CveController.get({"cve_id": id})
Exemple #17
0
        'id': form.id,
        'event_id': form.event_id,
        'is_open': form.is_open,
        'nominations': form.nominations,
        'sections': section_fields
    }
    return form_fields


question_detail_fields = {
    'id':
    fields.Integer,
    'type':
    fields.String,
    'description':
    fields.Raw(attribute=lambda q: q.description_translations),
    'headline':
    fields.Raw(attribute=lambda q: q.headline_translations),
    'order':
    fields.Integer,
    'options':
    fields.Raw(attribute=lambda q: q.options_translations),
    'placeholder':
    fields.Raw(attribute=lambda q: q.placeholder_translations),
    'validation_regex':
    fields.Raw(attribute=lambda q: q.validation_regex_translations),
    'validation_text':
    fields.Raw(attribute=lambda q: q.validation_text_translations),
    'is_required':
    fields.Boolean,
    'depends_on_question_id':
Exemple #18
0
    'uid': fields.String,
    'name': fields.String,
    'email': fields.String
}


def cal_community_balance(x):
    balance = x.community_balance + x.community_today_balance
    return '{0:.8f}'.format(decimal.Decimal(balance))


member_assets_fields = {
    'id': fields.String,
    'user': fields.Nested(member_assets_user_fields),
    'total_balance': DecimalToString,
    'community_balance': fields.Raw(attribute=lambda x: cal_community_balance(x)),
    'transaction_balance': DecimalToString,
    'grand_total_balance': DecimalToString,
    'community_frozen_balance': DecimalToString
}


@assets_api.add_resource('/query')
class MemberAssetsQueryApi(Resource):
    decorators = [member_login_required]

    @marshal_with(member_assets_fields)
    def get(self):
        assets = Assets.get_assets(g.current_user.id)
        return assets
Exemple #19
0
    'paperswithcode': fields.String(attribute='link')
}

paper_list_item_fields = {
    'id':
    fields.String,
    'title':
    fields.String,
    'authors':
    fields.Nested({'name': fields.String}),
    'timePublished':
    fields.DateTime(dt_format='rfc822', attribute="publication_date"),
    'abstract':
    fields.String(attribute="abstract"),
    'groups':
    fields.Raw(attribute='collection_ids', default=[]),
    'twitter_score':
    fields.Integer,
    'num_stars':
    fields.Integer,
    'code':
    fields.Nested(paper_with_code_fields,
                  attribute='paper_with_code',
                  allow_null=True),
    'comments_count':
    fields.Integer
}

metadata_fields = {
    'id':
    fields.String,
Exemple #20
0
review_question_detail_fields = {
    'id':
    fields.Integer,
    'question_id':
    fields.Integer,
    'type':
    fields.String,
    'is_required':
    fields.Boolean,
    'order':
    fields.Integer,
    'weight':
    fields.Float,
    'headline':
    fields.Raw(attribute=lambda s: s.headline_translations),
    'description':
    fields.Raw(attribute=lambda s: s.description_translations),
    'placeholder':
    fields.Raw(attribute=lambda s: s.placeholder_translations),
    'options':
    fields.Raw(attribute=lambda s: s.options_translations),
    'validation_regex':
    fields.Raw(attribute=lambda s: s.validation_regex_translations),
    'validation_text':
    fields.Raw(attribute=lambda s: s.validation_text_translations)
}

review_section_detail_fields = {
    'id':
    fields.Integer,
Exemple #21
0
        'is_offer_open': event.is_offer_open,
        'is_offer_opening': event.is_offer_opening,
        'is_registration_open': event.is_registration_open,
        'is_registration_opening': event.is_registration_opening,
        'is_event_open': event.is_event_open,
        'is_event_opening': event.is_event_opening,
        'travel_grant': event.travel_grant,
        "miniconf_url": event.miniconf_url
    }


event_fields = {
    'id':
    fields.Integer,
    'name':
    fields.Raw(attribute=lambda event: event.get_all_name_translations()
               if isinstance(event, Event) else {}),
    'description':
    fields.Raw(attribute=lambda event: event.get_all_description_translations(
    ) if isinstance(event, Event) else {}),
    'key':
    fields.String,
    'start_date':
    fields.DateTime(dt_format='iso8601'),
    'end_date':
    fields.DateTime(dt_format='iso8601'),
    'email_from':
    fields.String,
    'organisation_name':
    fields.String(attribute='organisation.name'),
    'organisation_id':
    fields.String(attribute='organisation.id'),
Exemple #22
0
    "id": fields.Integer,
    "created_at": fields.DateTime,
    "expires_at": fields.DateTime,
    "owned_by_ip": fields.String,
    "cancelled_at": fields.DateTime,
    "cancelled_by_ip": fields.String
}

entry_full = {
    "id": fields.Integer,
    "logbook": fields.Nested(logbook),
    "title": fields.String,
    "created_at": fields.DateTime,
    "last_changed_at": fields.DateTime,
    "authors": fields.List(fields.Nested(authors)),
    "attributes": fields.Raw(attribute="converted_attributes"),
    "attachments": fields.List(fields.Nested(attachment)),
    "priority": fields.Integer,
    "metadata": fields.Raw,
    "content": fields.String,
    "content_type": fields.String,
    "follows": EntryId,
    "n_followups": NumberOf(attribute="followups"),
    "followups": fields.List(Followup),
    "revision_n": fields.Integer,
    "lock": fields.Nested(entry_lock, allow_null=True),
    "next": EntryId,
    "previous": EntryId,
}

entry = {
Exemple #23
0
    'today_have_transaction':
    fields.Integer,
    'team_qualified_cnt':
    fields.Integer,
    'is_community_node':
    fields.Integer,
    'node_profit':
    fields.String,
    'assets':
    fields.Nested({
        'id':
        fields.String,
        'total_balance':
        DecimalToString,
        'community_balance':
        fields.Raw(attribute=lambda x: cal_community_balance(x)),
        'transaction_balance':
        DecimalToString,
    })
}

admin_member_list_fields = {
    'total_pages': fields.Integer,
    'page': fields.Integer,
    'per_page': fields.Integer,
    'total_count': fields.Integer,
    'objects': fields.List(fields.Nested(admin_member_fields))
}


@member_api.add_resource()
Exemple #24
0
import os
from flask_restful import marshal
from flask_restful import fields
from flask import Blueprint, jsonify
from flask_login import login_required, current_user
from models.task import Task

task_status_storage = {}
bp = Blueprint('task', __name__, url_prefix='/task')

task_fields = {
    'name': fields.String(),
    'status': fields.String(),
    'params': fields.Raw(),
    'result': fields.Raw(),
    'createdAt': fields.DateTime(attribute='created_at', dt_format='iso8601'),
}


@bp.route('/result/<oid:task_id>', methods=['GET'])
@login_required
def get_task_result(task_id):
    try:
        task = Task.objects.get(id=task_id)
    except Task.DoesNotExist:
        return jsonify(ok=False, msg='任务不存在'), 404
    if task.create_user.id != current_user.id:
        return jsonify(ok=False, msg='不是任务创建者,拒绝访问'), 403
    result = task_status_storage.get(str(task_id))
    return result if result is not None else task.result
Exemple #25
0
        return papers + authors


papers_fields = {
    'id':
    fields.String,
    'title':
    fields.String,
    'authors':
    fields.Nested({'name': fields.String}),
    'time_published':
    fields.DateTime(dt_format='rfc822', attribute="publication_date"),
    'abstract':
    fields.String(attribute="abstract"),
    'groups':
    fields.Raw(attribute='collection_ids', default=[]),
    'twitter_score':
    fields.Integer,
    'num_stars':
    fields.Integer,
    'code':
    fields.Nested(paper_with_code_fields,
                  attribute='paper_with_code',
                  allow_null=True),
    'comments_count':
    fields.Integer
}

papers_list_fields = {
    'papers': fields.Nested(papers_fields),
    'count': fields.Integer,
Exemple #26
0
parser.add_argument('name')
parser.add_argument('emails_for_notifications')
parser.add_argument('run_on_schedule')
parser.add_argument('schedules', type=list, location='json')
parser.add_argument('params', type=list, location='json')

schedule_fields = {
    'id': fields.Integer,
    'pipeline_id': fields.Integer,
    'cron': fields.String,
}
param_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'type': fields.String,
    'value': fields.Raw(attribute='api_value'),
    'label': fields.String
}
pipeline_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'emails_for_notifications': fields.String,
    'status': fields.String(attribute='state'),
    'updated_at': fields.String,
    'run_on_schedule': fields.Boolean,
    'schedules': fields.List(fields.Nested(schedule_fields)),
    'params': fields.List(fields.Nested(param_fields)),
    'message': fields.String,
    'has_jobs': fields.Boolean,
}
Exemple #27
0
billing_plan_fields_full = {
    'id': fields.Raw,
    'name': fields.Raw,
    'max_request_count': fields.Raw,
    'max_object_count': fields.Raw,
    'default': fields.Raw,
    'end_point': fields.Nested(end_point_fields)
}

user_fields = {
    'id': fields.Raw,
    'login': fields.Raw,
    'email': fields.Raw,
    'block_until': FieldDate,
    'type': fields.Raw(),
    'end_point': fields.Nested(end_point_fields),
    'billing_plan': fields.Nested(billing_plan_fields),
    'has_shape': HasShape,
    'shape': Shape,
    'default_coord': fields.Raw,
}

user_fields_full = {
    'id':
    fields.Raw,
    'login':
    fields.Raw,
    'email':
    fields.Raw,
    'block_until':
Exemple #28
0
    if order.match_order is None:
        return None
    else:
        price = order.match_order.payment_amount_usdt
        return '{0:.8f}'.format(price)


member_match_sell_order_fields = {
    'created_timestamp':
    fields.Integer,
    'updated_timestamp':
    fields.Integer,
    'payment':
    fields.Nested(member_payment_fields),
    'proof_img':
    fields.Raw(
        attribute=lambda x: None if x is None else json.loads(x.proof_img)),
    'buy_user':
    fields.Nested(member_user_fields)
}

member_sell_order_detail_fields = {
    'id':
    fields.Integer,
    'created_timestamp':
    fields.Integer,
    'updated_timestamp':
    fields.Integer,
    'number':
    fields.String,
    'amount':
    fields.String,
Exemple #29
0
class DepositionType(object):
    """Deposition type.

    A base class for the deposition types to ensure certain
    properties are defined on each type.

    A deposition type is just a BibWorkflow with a couple of extra methods.

    To customize rendering behavior of the workflow for a given deposition type
    you can override the render_error(), render_step() and render_completed()
    methods.
    """

    workflow = []
    """ Workflow definition """

    name = ""
    """ Display name for this deposition type """

    name_plural = ""
    """ Plural version of display name for this deposition type """

    enabled = False
    """ Determines if type is enabled - TODO: REMOVE"""

    default = False
    """
    Determines if type is the default - warnings are issed if conflicts exsists
    TODO: remove
    """

    deletable = False
    """
    Determine if a deposition is deletable after submission.
    """

    editable = False
    """
    Determine if a deposition is editable after submission.
    """

    stopable = False
    """
    Determine if a deposition workflow can be stopped (i.e. discard changes).
    """

    group = None
    """ Name of group to include this type in. """

    api = False
    """
    Determines if API is enabled for this type (requires workflow to be
    compatible with the API).
    """

    draft_definitions = {'_default': None}
    """
    Dictionary of all drafts for this deposition type
    """

    marshal_file_fields = dict(
        checksum=fields.String,
        filename=fields.String(attribute='name'),
        id=fields.String(attribute='uuid'),
        filesize=fields.String(attribute='size'),
    )
    """ REST API structure of a file """

    marshal_draft_fields = dict(
        metadata=fields.Raw(attribute='values'),
        completed=fields.Boolean,
        id=fields.String,
    )
    """ REST API structure of a draft """

    marshal_deposition_fields = dict(
        id=fields.Integer,
        title=fields.String,
        created=UTCISODateTime,
        modified=UTCISODateTime,
        owner=fields.Integer(attribute='user_id'),
        state=fields.String,
        submitted=fields.Boolean,
        files=fields.Nested(marshal_file_fields),
        drafts=fields.Nested(marshal_draft_fields, attribute='drafts_list'),
    )
    """ REST API structure of a deposition """
    @classmethod
    def default_draft_id(cls, deposition):
        """Default draft id."""
        return '_default'

    @classmethod
    def render_error(cls, dummy_deposition):
        """
        Render a page when deposition had an workflow error.

        Method can be overwritten by subclasses to provide custom
        user interface.
        """
        flash('%(name)s deposition has returned error.' % {'name': cls.name},
              'error')
        return redirect(url_for('.index'))

    @classmethod
    def render_step(self, deposition):
        """
        Render a page for a given deposition step.

        Method can be overwritten by subclasses to provide custom
        user interface.
        """
        ctx = deposition.get_render_context()
        if ctx:
            return render_template(**ctx)
        else:
            return render_template(
                'deposit/error.html',
                **dict(
                    depostion=deposition,
                    deposition_type=(None if deposition.type.is_default() else
                                     deposition.type.get_identifier()),
                    uuid=deposition.id,
                    my_depositions=Deposition.get_depositions(
                        current_user, type=deposition.type),
                ))

    @classmethod
    def render_completed(cls, dummy_deposition):
        """Render page when deposition was successfully completed.

        (i.e workflow just finished successfully).

        Method can be overwritten by subclasses to provide custom
        user interface.
        """
        flash('%(name)s was successfully finished.' % {'name': cls.name},
              'success')
        return redirect(url_for('.index'))

    @classmethod
    def render_final(cls, deposition):
        """Render page when deposition was *already* successfully completed.

        (i.e a finished workflow is being executed a second time).

        This allows you render e.g. a preview of the record. The distinction
        between render_completed and render_final is primarily useful for the
        REST API (see api_final and api_completed)

        Method can be overwritten by subclasses to provide custom
        user interface.
        """
        return cls.render_completed(deposition)

    @classmethod
    def api_completed(cls, deposition):
        """Workflow just finished processing.

        Workflow just finished processing so return an 202 Accepted, since
        usually further background processing may happen.
        """
        return deposition.marshal(), 202

    @classmethod
    def api_final(cls, deposition):
        """Workflow already finished.

        And the user tries to re-execute the workflow, so send a 400 Bad
        Request back.
        """
        return dict(
            message="Deposition workflow already completed",
            status=400,
        ), 400

    @classmethod
    def api_step(cls, deposition):
        """Workflow was halted during processing.

        The workflow task that halted processing is expected to provide a
        response to send back to the client.

        The default response code is 500 Internal Server Error. A workflow task
        is expected to use Deposition.set_render_context() with a dictionary
        which is returned to the client. Set the key 'status', to change the
        status code, e.g.::

            d.set_render_context(dict(status=400, message="Bad request"))

        If no response is provided by the workflow task, it is regarded as
        an internal server error.
        """
        ctx = deposition.get_render_context()
        if ctx:
            return ctx.get('response', {}), ctx.get('status', 500)
        return cls.api_error(deposition)

    @classmethod
    def api_error(cls, deposition):
        """Api error."""
        return dict(message='Internal Server Error', status=500), 500

    @classmethod
    def api_action(cls, deposition, action_id):
        """Api action."""
        if action_id == 'run':
            return deposition.run_workflow(headless=True)
        elif action_id == 'reinitialize':
            deposition.reinitialize_workflow()
            return deposition.run_workflow(headless=True)
        elif action_id == 'stop':
            deposition.stop_workflow()
            return deposition.run_workflow(headless=True)
        raise InvalidApiAction(action_id)

    @classmethod
    def api_metadata_schema(cls, draft_id):
        """Get the input validation schema for this draft_id.

        Allows you to override API defaults.
        """
        from wtforms.fields.core import FieldList, FormField

        if draft_id in cls.draft_definitions:
            schema = dict()
            formclass = cls.draft_definitions[draft_id]
            for fname, fclass in formclass()._fields.items():

                if isinstance(fclass, FieldList):
                    schema[fname] = dict(type='list')
                elif isinstance(fclass, FormField):
                    schema[fname] = dict(type='dict')
                else:
                    schema[fname] = dict(type='any')
            return dict(type='dict', schema=schema)
        return None

    @classmethod
    def marshal_deposition(cls, obj):
        """Generate a JSON representation for REST API of a Deposition."""
        return marshal(obj, cls.marshal_deposition_fields)

    @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 marshal_file(cls, obj):
        """Generate a JSON representation for REST API of a DepositionFile."""
        return marshal(obj, cls.marshal_file_fields)

    @classmethod
    def authorize(cls, deposition, action):
        """Authorize."""
        if action == 'create':
            return True  # Any authenticated user
        elif action == 'delete':
            if deposition.has_sip():
                return deposition.type.deletable
            return True
        elif action == 'reinitialize':
            return deposition.type.editable
        elif action == 'stop':
            return deposition.type.stopable
        elif action in ['add_file', 'remove_file', 'sort_files']:
            # Don't allow to add/remove/sort files after first submission
            return not deposition.has_sip()
        elif action in [
                'add_draft',
        ]:
            # Allow adding drafts when inprogress (independent of SIP exists
            # or not).
            return deposition.state == 'inprogress'
        else:
            return not deposition.has_sip()

    @classmethod
    def authorize_draft(cls, deposition, draft, action):
        """Authorize draft."""
        if action == 'update':
            # If deposition allows adding  a draft, then allow editing the
            # draft.
            return cls.authorize(deposition, 'add_draft')
        return cls.authorize(deposition, 'add_draft')

    @classmethod
    def authorize_file(cls, deposition, deposition_file, action):
        """Authorize file."""
        return cls.authorize(deposition, 'add_file')

    @classmethod
    def get_identifier(cls):
        """Get type identifier (identical to workflow name)."""
        return cls.__name__

    @classmethod
    def is_enabled(cls):
        """Check if workflow is enabled."""
        # Wrapping in a method to eventually allow enabling/disabling
        # via configuration.
        return cls.enabled

    @classmethod
    def is_default(cls):
        """Check if workflow is the default."""
        # Wrapping in a method to eventually allow configuration
        # via configuration.
        return cls.default

    @classmethod
    def run_workflow(cls, deposition):
        """Run workflow for the given BibWorkflowObject.

        Usually not invoked directly, but instead indirectly through
        Deposition.run_workflow().
        """
        if deposition.workflow_object.workflow is None or (
                deposition.workflow_object.version == ObjectVersion.INITIAL
                and deposition.workflow_object.workflow.status
                == WorkflowStatus.NEW):
            return deposition.workflow_object.start_workflow(
                workflow_name=cls.get_identifier(),
                id_user=deposition.workflow_object.id_user,
                module_name="webdeposit")
        else:
            return deposition.workflow_object.continue_workflow(
                start_point="restart_task", )

    @classmethod
    def reinitialize_workflow(cls, deposition):
        """Reinitialize workflow."""
        # Only reinitialize if really needed (i.e. you can only
        # reinitialize a fully completed workflow).
        wo = deposition.workflow_object
        if wo.version == ObjectVersion.COMPLETED and \
           wo.workflow.status == WorkflowStatus.COMPLETED:

            wo.version = ObjectVersion.INITIAL
            wo.workflow.status = WorkflowStatus.NEW

            # Clear deposition drafts
            deposition.drafts = {}

    @classmethod
    def stop_workflow(cls, deposition):
        """Stop workflow."""
        # Only stop workflow if really needed
        wo = deposition.workflow_object
        if wo.version != ObjectVersion.COMPLETED and \
           wo.workflow.status != WorkflowStatus.COMPLETED:

            # Only workflows which has been fully completed once before
            # can be stopped
            if deposition.has_sip():
                wo.version = ObjectVersion.COMPLETED
                wo.workflow.status = WorkflowStatus.COMPLETED

                # Clear all drafts
                deposition.drafts = {}

                # Set title - FIXME: find better way to set title
                sip = deposition.get_latest_sip(sealed=True)
                title = sip.metadata.get('title', 'Untitled')
                deposition.title = title

    @classmethod
    def all(cls):
        """Get a dictionary of deposition types."""
        from .registry import deposit_types
        return deposit_types.mapping()

    @classmethod
    def get(cls, identifier):
        """Get."""
        try:
            return cls.all()[identifier]
        except KeyError:
            raise InvalidDepositionType(identifier)

    @classmethod
    def keys(cls):
        """Get a list of deposition type names."""
        return cls.all().keys()

    @classmethod
    def values(cls):
        """Get a list of deposition type names."""
        return cls.all().values()

    @classmethod
    def get_default(cls):
        """Get a list of deposition type names."""
        from .registry import deposit_default_type
        return deposit_default_type.get()

    def __unicode__(self):
        """Return a name for this class."""
        return self.get_identifier()

    @classmethod
    def all_authorized(cls, user_info=None):
        """Get all authorized.

        Return a dict of deposit types that the current user
        is allowed to view.
        """
        user_info = user_info or current_user

        all_types = cls.all()
        auth_types = user_info.get('precached_allowed_deposition_types', set())

        return {key: all_types[key] for key in auth_types if key in all_types}
Exemple #30
0
    "total_result": fields.String,
    "prev": fields.Nested(href_field),
    "next": fields.Nested(href_field),
    "first": fields.Nested(href_field),
    "last": fields.Nested(href_field)
}

meta_fields = {"pagination": fields.Nested(paginate_fields)}

error_fields = {'error': fields.Nested({'message': fields.String})}

base_severity_fields = {
    'id': fields.Raw,
    'color': fields.Raw,
    'priority': fields.Integer(default=None),
    'effect': fields.Raw()
}

severity_fields = deepcopy(base_severity_fields)
severity_fields['wording'] = fields.Raw
severity_fields['created_at'] = FieldDateTime
severity_fields['updated_at'] = FieldDateTime
severity_fields['self'] = {'href': fields.Url('severity', absolute=True)}
severity_fields['wordings'] = fields.List(fields.Nested(wording_fields))

base_severity_fields['name'] = fields.Raw(attribute='wording')

severities_fields = {
    'severities': fields.List(fields.Nested(severity_fields)),
    'meta': {},
}