Exemplo n.º 1
0
from flask import abort
from flask_restful import Resource, fields, marshal_with
from api.models import Agrosemens

class JsonItem(fields.Raw):
    def format(self, value):
        return value

seed_fields = {
    'variety' : fields.String(),
    'category' : fields.String(),
    'href' : fields.String(),
    'taxon' : fields.String(),
    'description' : JsonItem()
}

class SeedApi(Resource):
    @marshal_with(seed_fields)
    def get(self,page=1):
       seeds = Agrosemens.objects.paginate(page,page + 10).items
       if not seeds:
          abort(404)
       return  seeds
Exemplo n.º 2
0
from models.user import User
from models.cable import Cable
from models.device import Device
from models.interface import Interface
from models.equipment import Equipment
from auth.permissions import admin_or_owner_required, admin_required
from .forms.device import CreateOrUpdateForm, SearchForm
from .helper.base_views import *
from .helper.pagination import pagination_marshal_with, build_order_by
from .helper.response_fields import device_base_fields, equipment_base_fields, device_template_fields

bp = Blueprint('device', __name__, url_prefix='/appliance')

device_list_fields = {
    **device_base_fields,
    'parentEquipmentName': fields.String(attribute='parent_equipment.name'),
}

device_fields = {
    **device_base_fields,
    'parentEquipment': fields.Nested(equipment_base_fields, attribute='parent_equipment'),
}


@bp.route('/device/<oid:oid>', methods=['GET'])
@login_required
@base_view(Device, device_fields)
def get_device():
    pass

Exemplo n.º 3
0
# @author: Small_stars
# @mailbox: [email protected]
# @site:
# @software: PyCharm
# @file: views.py
# @time: 2021/3/9 16:51
from flask_restful import Resource, fields, marshal
from flask import request
import json

from .models import User
from ..db import db
from ..utils import authority, custom_status_code

user_fields = {
    'email': fields.String(),
    'username': fields.String(attribute='username'),
    'authority': fields.String(attribute='uauthority'),
}

user_items = {
    'email': User.email,
    'username': User.username,
    'authority': User.uauthority,
}


# user
class GetList(Resource):
    def get(self):
        data = User.query.filter(User.uauthority > authority['guest']).all()
Exemplo n.º 4
0
 def test_attribute(self):
     obj = {"bar": 3}
     field = fields.String(attribute="bar")
     self.assertEquals(field.output("foo", obj), "3")
Exemplo n.º 5
0
#!/usr/bin/env python
# encoding: utf-8
"""
@author: zhanghe
@software: PyCharm
@file: enum_items.py
@time: 2018-08-23 15:55
"""

from __future__ import unicode_literals

from flask_restful import fields

fields_item_enum_items = {
    'id': fields.Integer(attribute='ID'),
    'id_enum': fields.Integer(attribute='idEnum'),
    'code': fields.String(attribute='Code'),
    'name': fields.String(attribute='Name'),
    'is_deleted': fields.Boolean(attribute='IsDeleted'),
}

fields_item_enum_items_cn = {
    '主键': fields.Integer(attribute='ID'),
    '枚举id': fields.Integer(attribute='idEnum'),
    '编码': fields.String(attribute='Code'),
    '名称': fields.String(attribute='Name'),
    '删除': fields.Boolean(attribute='IsDeleted'),
}
Exemplo n.º 6
0
 def test_string_no_value(self):
     field = fields.String()
     self.assertEquals(None, field.output("bar", Foo()))
Exemplo n.º 7
0
 def test_basic_dictionary(self):
     obj = {"foo": 3}
     field = fields.String()
     self.assertEquals(field.output("foo", obj), "3")
Exemplo n.º 8
0
from flask_restful import fields

song_fields = {
    'id': fields.String(attribute='_id'),
    'artist': fields.String,
    'title': fields.String,
    'difficulty': fields.Float,
    'level': fields.Integer,
    'released': fields.String,
}
Exemplo n.º 9
0
    'slo_id': fields.String,
    'slo_description': fields.String,
    'performance_indicators': fields.List(fields.Nested(pi_data_fields))
}

slo_data_extra_fields = {
    'total_assessments': fields.Integer
}

class_data_fields = {
    'crn': fields.String,
    'course_number': fields.String,
    'course_name': fields.String,
    'course_type': fields.String,
    'semester': fields.String,
    'course_year': fields.String(attribute=lambda x: x['course_year'].year), # extract only the Year as a string
    'total_students': fields.Integer,
    'assigned_slos': fields.List(fields.Nested(slo_data_fields)),
    'completion': fields.Boolean
}

# Input: List of AssessmentModel objects, SLO object
# Output: List of PI data in the format specified by pi_data_fields
def generateSummaryData(listOfAssessments, SLOModel):

    summaryData = [] #container
    relevant_assessments = [x for x in listOfAssessments if x.slo_id == SLOModel.slo_id] # Filters assessments to just be the ones for this specific SLO
    relevant_scores = [] #container that will hold all scores

    # For each relevant assessment, add it's scores to the relevant_scores container
    for a in relevant_assessments: relevant_scores = relevant_scores + a.scores
Exemplo n.º 10
0
from models import db
from flask_restful import fields, marshal

user_fields = {
    'email': fields.String,
    'firstName': fields.String(attribute='first_name'),
    'lastName': fields.String(attribute='last_name'),
    'picture': fields.String(attribute='profile_picture_url'),
    'token': fields.String(attribute='user_secret')
}


class User(db.Model):
    __tablename__ = 'users'
    email = db.Column(db.String, primary_key=True)
    google_id = db.Column(db.String)
    first_name = db.Column(db.String)
    last_name = db.Column(db.String)
    user_secret = db.Column(db.String)
    profile_picture_url = db.Column(db.String)
    contacts = db.relationship('UserContact')
    location_history = db.relationship('UserLocation',
                                       order_by='desc(UserLocation.time)')
    tracking_info = db.relationship('TrackingInfo', uselist=False)

    def __init__(self, gid, email, first, last, picture, secret):
        self.google_id = gid
        self.email = email
        self.first_name = first
        self.last_name = last
        self.profile_picture_url = picture
import os
from datetime import datetime
from logging import getLogger
from time import sleep
from flask import request
from flask_restful import Resource, reqparse, fields, marshal_with, marshal
from kafka.errors import NoBrokersAvailable
from mongoengine import Q
import dateutil.parser
from database.data import Notification
import json

notification_fields = {
    'id': fields.String(),
    'user_id': fields.String(),
    'timestamp': fields.DateTime(dt_format='iso8601'),
    'creation_timestamp': fields.DateTime(dt_format='iso8601'),
    'modified_timestamp': fields.DateTime(dt_format='iso8601'),
    'type': fields.String(),
    'data': fields.Raw(),
    'is_active': fields.Boolean(),
    'notes': fields.String()
}

parser = reqparse.RequestParser()
parser.add_argument('id', type=str)
parser.add_argument('user_id', type=str)
parser.add_argument('timestamp', type=lambda x: dateutil.parser.parse(x))
parser.add_argument('creation_timestamp',
                    type=lambda x: dateutil.parser.parse(x))
parser.add_argument('modified_timestamp',
Exemplo n.º 12
0
#!/usr/bin/env python
# encoding: utf-8
"""
@author: zhanghe
@software: PyCharm
@file: sale_order.py
@time: 2018-07-24 16:59
"""

from __future__ import unicode_literals

from flask_restful import fields

fields_item_sale_order = {
    'id': fields.Integer(attribute='ID'),
    'code': fields.String(attribute='code'),
    'customer_id': fields.Integer(attribute='idcustomer'),  # 客户id
    'settle_id': fields.Integer(attribute='idsettlecustomer'),  # 结算客户id
    'address': fields.String(attribute='address'),
    'linkman': fields.String(attribute='linkMan'),
    'amount': fields.Float(attribute='amount'),
    'amount_tax': fields.Float(attribute='taxAmount'),
    'contact_phone': fields.String(attribute='contactPhone'),
    'delivery_mode': fields.Integer(attribute='deliveryMode'),
    'receive_type': fields.Integer(attribute='reciveType'),
    'maker_id': fields.Integer(attribute='makerid'),
    'maker': fields.String(attribute='maker'),
    'create_time': fields.DateTime(dt_format=b'iso8601',
                                   attribute='createdtime'),
    'update_time': fields.DateTime(dt_format=b'iso8601', attribute='updated'),
}
Exemplo n.º 13
0
parse_base.add_argument('action', type=str, required=True, help='请确认请求参数')
parse_base.add_argument('password', type=str, required=True, help='请输入密码')

parse_register = parse_base.copy()
parse_register.add_argument('phone', type=str, required=True, help='请输入手机号码')
parse_register.add_argument('email', type=str, required=True, help='请输入邮箱')

parse_login = parse_base.copy()
parse_login.add_argument("email", type=str, required=True, help='请输入手机号码')
parse_login.add_argument("phone", type=str, required=True, help='请输入手机号码')
parse_login.add_argument("code", type=str, required=True, help='请输入验证码')

boke_user_fields = {
    'u_email': fields.String,
    'u_phone': fields.String,
    'password': fields.String(attribute="_password"),
}

single_boke_user_fields = {
    'status': fields.Integer,
    'msg': fields.String,
    'data': fields.Nested(boke_user_fields)
}


class BokeUsersResource(Resource):
    def get(self):
        phone = request.args.get("phone")
        resp = send_verify_code(phone)
        result = resp.json()
Exemplo n.º 14
0
from flask_restful import fields

mac_fields = {
    'mac_address': fields.String(),
    'user': fields.String(attribute='user.name')
}

user_fields = {
    'name': fields.String,
    'mac_addresses': fields.List(fields.Nested(mac_fields)),
}
user_list_fields = {
    fields.List(fields.Nested(user_fields)),
}

logs_fields = {
    'time': fields.String,
    'mac_address': fields.String,
    'user': fields.String,
    'ip': fields.String,
}
Exemplo n.º 15
0
 def test_string_with_lambda(self):
     field = fields.String(attribute=lambda x: x.hey)
     self.assertEquals("3", field.output("foo", Foo()))
Exemplo n.º 16
0
from flask import request
from flask_restful import fields, marshal_with

from opencve.api.alerts import alert_fields
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


report_list_fields = {
    "id": fields.String(attribute="public_link"),
    "created_at": DatetimeField(),
    "details": fields.Raw(attribute="details"),
}

report_fields = dict(
    report_list_fields, **{"alerts": fields.List(fields.Nested(alert_fields))}
)


class ReportListResource(BaseResource):
    @marshal_with(report_list_fields)
    def get(self):
        user = User.query.filter_by(
            username=request.authorization.get("username")
        ).first()
        return ReportController.list_items({**request.args, "user_id": user.id})
Exemplo n.º 17
0
 def test_string(self):
     field = fields.String()
     self.assertEquals("3", field.output("hey", Foo()))
    'ml_model_name': fields.String,
    'condition_refcode': fields.String,
    'condition_name': fields.String,
    'name': fields.String,
    'description': fields.String,
    'creator': fields.Nested(user_fields),
    'created_at': fields.DateTime,
    'updated_at': fields.DateTime,
    'feature_set_id': fields.Integer,
    'environment': fields.Nested(environment_fields),
    'feature_set': fields.Nested(feature_set_fields)
}

feature_fields = {
    'resource': fields.String,
    'key': fields.String(attribute='parameter_name'),
    'value': fields.String,
    'name': fields.String,
    'resource_val_path': fields.String(attribute='output_value_path')
}


class MLModelListResource(Resource):
    def __init__(self):
        super(MLModelListResource, self).__init__()
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('environment_id', type=int, required=True, help='No environment id provided', location='json')
        self.parser.add_argument('name', type=str, required=False, help='No model name provided', location='json')
        self.parser.add_argument('description', type=str, required=False, location='json')
        self.parser.add_argument('feature_set_id', type=int, required=False, location='json')
        self.parser.add_argument('condition_refcode', type=str, required=False, location='json')
Exemplo n.º 19
0
 def test_string_none(self):
     field = fields.String()
     self.assertEquals(None, field.output("empty", {'empty': None}))
Exemplo n.º 20
0
from RestfulApp.ext import db
from RestfulApp.models import Teacher

req1 = RequestParser()  #  创建RequestParser请求解析器对象
req1.add_argument("name", type=str, required=True, help="必须传递name参数,并且为字符串类型!")
req1.add_argument("age", type=int, help="年龄必须是整数",
                  dest="t_age")  # 前端使用age传参,后端使用t_age接收参数
req1.add_argument("salary",
                  type=float,
                  required=True,
                  help="必须传递salary参数,并且为小数!")

# 老师实例化对象定制输出模板
teacher_instance = {
    "teacher_id": fields.Integer(attribute="id"),
    "teacher_name": fields.String(attribute="name"),
    "teacher_age": fields.Integer(attribute="age"),
    "teacher_salary": fields.Float(attribute="salary"),
}

teacher_output = {
    "code": fields.String,
    "msg": fields.String,
    "teacher": fields.Nested(teacher_instance, attribute="new_teacher")
}


class TeacherResource(Resource):
    @marshal_with(teacher_output)
    def post(self):
        print("111111111111111")
Exemplo n.º 21
0
 def test_no_attribute(self):
     obj = {"bar": 3}
     field = fields.String()
     self.assertEquals(field.output("foo", obj), None)
Exemplo n.º 22
0
table_reader_fields = {
    'reader': fields.Nested(user_fields, attribute='user'),
    'read_count': fields.Integer
}

column_stat_fields = {
    'stat_type': fields.String,
    'stat_val': fields.String,  # Optional
    'start_epoch': fields.Integer,  # Optional
    'end_epoch': fields.Integer,  # Optional
}

column_fields = {
    'name': fields.String,
    'description': fields.String,
    'type': fields.String(attribute='col_type'),
    'sort_order': fields.Integer,
    # Can be an empty list
    'stats': fields.List(fields.Nested(column_stat_fields))
}

watermark_fields = {
    'watermark_type': fields.String,
    'partition_key': fields.String,
    'partition_value': fields.String,
    'create_time': fields.String
}

tag_fields = {'tag_type': fields.String, 'tag_name': fields.String}

table_writer_fields = {
Exemplo n.º 23
0
import json
from flask import jsonify, Blueprint, abort, g, make_response
from flask_restful import Resource, Api, reqparse, inputs, fields, url_for, marshal, marshal_with

import models
from auth import auth

review_fields = {
    'id': fields.Integer,
    'for_course': fields.String,
    'rating': fields.Integer,
    'comment': fields.String(default=''),
    'created_at': fields.DateTime
}


def review_or_404(review_id):
    try:
        review = models.Review.get(models.Review.id == review_id)
    except models.Review.DoesNotExist:
        abort(404, message='Review {} does not exist'.format(review_id))
    else:
        return review


def add_course(review):
    review.for_course = url_for('resources.courses.course',
                                id=review.course.id)
    return review

Exemplo n.º 24
0
from flask_restful import Resource, request, fields, marshal
from app.db import db, LectureModel
from app.resource import message, admin_required

lecture_field = {
    'id': fields.Integer,
    'titulo': fields.String,
    'conteudo': fields.String,
    'ministrante': fields.String(attribute=lambda obj: obj.speaker.nome)
}
remove_lecture_field = {
    'id': fields.Integer,
    'titulo': fields.String,
    'conteudo': fields.String
}
load_title_field = {
    'id': fields.Integer,
    'titulo': fields.String,
    'ministrante': fields.String(attribute=lambda obj: obj.speaker.nome)
}


class LectureAdminResource(Resource):
    @admin_required
    def get(self, lecture_id=None):
        loadtitle = int(request.args.get('loadtitle', 0))
        if int(loadtitle) == 1:
            lectures = LectureModel.query.order_by(LectureModel.id).all()
            lectures = [marshal(l, load_title_field) for l in lectures]
            return {'values': lectures}, 200
        if lecture_id:
Exemplo n.º 25
0
from flask_restful import Resource, fields, marshal_with
from wanghublog.controllers.flask_restful import fields as jf_fields
from wanghublog.models import db, User, Post, Tag
from wanghublog.controllers.flask_restful import parsers
from flask import abort
from datetime import datetime
# String format output of tag
nested_tag_fields = {'id': fields.String(), 'name': fields.String()}

# String format output of post
post_fields = {
    'author': fields.String(attribute=str(lambda x: x.user.username)),
    'title': fields.String(),
    'text': jf_fields.HTMLField(),
    'tags': fields.List(fields.Nested(nested_tag_fields)),
    'publish_date': fields.DateTime(dt_format='iso8601')
}


class PostApi(Resource):
    """Restful API of posts resource."""
    @marshal_with(post_fields)
    def get(self, post_id=None):
        """Can be execute when receive HTTP Method `GET`.
           Will be return the Dict object as post_fields.
        """

        if post_id:
            post = Post.query.filter_by(id=post_id).first()
            if not post:
                abort(404)
Exemplo n.º 26
0
MODEL = Messages
ROUTE = "/messages"
END_POINT = "messages"

#NESTED SCHEMA FIELDS

#OUTPUT SCHEMA
output_fields = {
    'id':
    fields.Integer,
    'receiver_user_id':
    fields.Integer,
    'is_read':
    fields.Boolean,
    'name':
    fields.String(attribute=lambda x: x.user_data.name
                  if x.user_data is not None else '')
}


#API METHODS FOR SINGLE ENTITY
class MessagesResource(Resource):
    def __init__(self):
        self.route = ROUTE + '/<int:id>'
        self.end_point = END_POINT
        pass

    @marshal_with(output_fields)
    def get(self, id):
        entity = session.query(MODEL).filter(MODEL.id == id).first()
        if not entity:
            abort(404, message=ENTITY_NAME + " {} doesn't exist".format(id))
Exemplo n.º 27
0
from ...models.tv import Channel

from ._utils import marshal_nullable_with
from ._utils import DateTimeWithUtc


log = logging.getLogger(__name__)


# output
_channel_fields = {
	'ID': fields.String,
	'name': fields.String,
	'name_short': fields.String,
	'ip_string': fields.String,
	'channel_status': fields.String(attribute='channel_status.status'),

	'meta_teletext_page': fields.String,
	'meta_country_code': fields.String,
	'meta_language_code3': fields.String,
	'meta_timezone': fields.String,
	'meta_video_source': fields.String,
}

_channel_status_fields = {
	'channel_ID': fields.String,
	'status': fields.String,
	'error': fields.String,
	'ts': DateTimeWithUtc,
}
Exemplo n.º 28
0
 def test_string_with_attribute(self):
     field = fields.String(attribute="hey")
     self.assertEquals("3", field.output("foo", Foo()))
Exemplo n.º 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}
import json
from flask import Flask, jsonify

from flask_restful import reqparse, abort, Api, Resource, request, fields, marshal_with

from ..service.action_entity import save_new_action_entity, get_all_action_entitys, get_a_action_entity, update_a_action_entity, delete_a_action_entity

from .. import api

action_entity_fields = {
    'id': fields.Integer,
    'type': fields.String(1024),
    'category': fields.String(1024),
    'name': fields.String(1024),
    'description': fields.String,
    'sn_name': fields.String(1024),
    'sn_description': fields.String,
    'tn_name': fields.String(1024),
    'tn_description': fields.String,
}

action_entity_list_fields = {
    'action_entitys': fields.List(fields.Nested(action_entity_fields))
}


@api.resource('/action_entitys')
class ActionEntityList(Resource):
    @marshal_with(action_entity_fields)
    def get(self):
        """List all registered action_entitys"""