Exemplo n.º 1
0
class CompanySearchApi(Resource):
    paginate_fields = {
        'page': fields.Integer,
        'pages': fields.Integer,
        'total': fields.Integer,
        'has_prev': fields.Boolean,
        'has_next': fields.Boolean
    }

    data_fields = {
        'companies': fields.List(fields.Nested(company_fields)),
        'paginate': fields.Nested(paginate_fields)
    }

    json_fields = {
        'code': fields.Integer,
        'data': fields.Nested(data_fields),
        'msg': fields.String
    }

    @marshal_with(json_fields)
    def post(self):
        # 合作公司列表查询
        args = parser.parse_args()
        params_data = demjson.decode(args.get('data'))
        page_num = params_data.get('pageNum') or 1
        page_size = params_data.get('pageSize')
        _total = Company.query.count()
        _page_num = _total // page_size
        if _total % page_size > 0:
            _page_num += 1
        if int(page_num) > _page_num:
            page_num = _page_num
        filter_list = []
        for key in params_data:
            if key == 'search_value':
                search_value = params_data.get('search_value') or ''
                filter_list.append(Company.name.contains(search_value))
            if key == 'level':
                level = params_data.get('level') if params_data.get(
                    'level') else 0
                filter_list.append(Company.level >= level)
            if key == 'industry_type':
                industry_type = params_data.get(
                    'industry_type') if params_data.get('industry_type') else 0
                if industry_type:
                    filter_list.append(Company.industry_type == industry_type)
        pagination = Company.query.filter(*filter_list).paginate(
            page=page_num, per_page=page_size, error_out=False)
        paginate_data = dict()
        paginate_data['page'] = pagination.page
        paginate_data['pages'] = pagination.pages
        paginate_data['total'] = pagination.total
        paginate_data['has_prev'] = pagination.has_prev
        paginate_data['has_next'] = pagination.has_next
        companies = pagination.items
        json_data = {'companies': companies, 'paginate': paginate_data}
        return handle_data(json_data)

    @staticmethod
    def delete():
        # 删除具体的合作公司
        args = parser.parse_args()
        company_id = args.get('id')
        try:
            company = Company.query.get(company_id)
            db.session.delete(company)
            db.session.query(Records).filter(
                Records.company_id.__eq__(company_id)).delete()
            db.session.commit()
        except Exception as e:
            db.session.rollback()
        return handle_data('success')
Exemplo n.º 2
0
Arquivo: news.py Projeto: q25979/tdb99
news_bp = Blueprint('news_bp', __name__)
news_api = AddResource(Api(news_bp))

news_fields = {
    'id': fields.String,
    'created_at': Datetime2Timestamp,
    'title': fields.String,
    'details': fields.String,
}

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

# 新闻为公告,可以不用户认证。


@news_api.add_resource()
class NewsList(Resource):
    @marshal_with(news_list_fields)
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('page', type=int, default=1, location='args')
        parser.add_argument('per_page', type=int, default=5, location='args')
        parsed_args = parser.parse_args()

        news = News.query
Exemplo n.º 3
0
user_fields = {
    'telephone': fields.String,
    'password': fields.String,
    'name': fields.String,
    'token': fields.String,
    'email': fields.String,
    'icon': IconForm(attribute='icon'),
    'permissions': fields.Integer
}

result_fields = {
    'msg': fields.String,
    'status': fields.Integer,
    'time': fields.String,
    'err': fields.String,
    'data': fields.Nested(user_fields)
}


class Changinfo(Resource):
    @marshal_with(result_fields)
    def post(self):
        responsedata = {'time': str(int(time.time()))}
        print('##############')
        parse = parser.parse_args()
        print('$$$$$$$$$$$$$$$$')
        user = User()
        user.telephone = parse.get('telephone')
        user.name = parse.get('name')
        user.email = parse.get('email')
        # 图片数据
Exemplo n.º 4
0
    'id': fields.Integer,
    'system_name': fields.String,
    'display_value': fields.String,
    'name': fields.String,
    'is_default': fields.Boolean
}

area_data_fields = {
    'id': fields.Integer,
    'name': fields.String,
}
city_data_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'area_id': fields.Integer,
    'area_data': fields.Nested(area_data_fields)
}
client_address_data_fields = {
    'id': fields.Integer,
    'client_id': fields.Integer,
    'address': fields.String,
    'is_default': fields.Boolean,
    'name': fields.String,
    'confirmed': fields.Boolean,
    'tobacco_alcohol_license': fields.Boolean,
    'code': fields.String,
    'city_id': fields.Integer,
    'city_data': fields.Nested(city_data_fields),
    'phone_number': fields.String
}
Exemplo n.º 5
0
class Question(Resource):
    img_list = {'id': rfields.Integer, 'img_url': rfields.String}

    answer_info = {
        'id': rfields.Integer,
        'student_id': rfields.Integer,
        'school_id': rfields.Integer,
        'teacher_id': rfields.Integer,
        'teacher_nickname': rfields.String,
        'teacher_imgurl': rfields.String(default=''),
        'student_nickname': rfields.String,
        'student_imgurl': rfields.String(default=''),
        'ask_id': rfields.Integer,
        'timestamp': rfields.DateTime(dt_format='iso8601'),
        'answer_text': rfields.String,
        'voice_url': rfields.String,
        'voice_duration': rfields.String,
        'imgs': rfields.List(rfields.String)
    }

    ask_info = {
        'code':
        rfields.Integer,
        'ask':
        rfields.Nested({
            'id': rfields.Integer,
            'student_id': rfields.Integer,
            'school_id': rfields.Integer,
            'timestamp': rfields.DateTime(dt_format='iso8601'),
            'ask_text': rfields.String,
            'voice_url': rfields.String,
            'voice_duration': rfields.String,
            'imgs': rfields.List(rfields.String),
            'answers': rfields.Nested(answer_info),
            'be_answered': rfields.Boolean,
            'answer_grate': rfields.Integer
        })
    }

    @marshal_with(ask_info)
    def get(self, id):
        abort_if_ask_doesnt_exist(id)
        ask = Ask.query.get(id)
        if g.student_user.id != ask.student_id:
            abort(401, code=0, message='没有权限')
        ask = imgidsToimgs(ask)
        for answer in ask.answers:
            answer = imgidsToimgs(answer)
            teacher_id = answer.teacher_id
            if teacher_id:
                teacher = Teacher.query.get(teacher_id)
                answer.teacher_nickname = teacher.nickname
                answer.teacher_imgurl = teacher.imgurl
            student_id = answer.student_id
            if student_id:
                student = Student.query.get(student_id)
                answer.student_nickname = student.nickname
                answer.student_imgurl = student.imgurl
        result = {'code': 1, 'ask': ask}
        return result, 200

    def delete(self, id):
        abort_if_ask_doesnt_exist(id)
        ask = Ask.query.get(id)
        if g.student_user.id != ask.student_id:
            abort(401, code=0, message='没有权限')
        db.session.delete(ask)
        db.session.commit()
        return '', 204
Exemplo n.º 6
0
    'shownameen': fields.String,
    'director': fields.String,
    'leadingRole': fields.String,
    'type': fields.String,
    'country': fields.String,
    'language': fields.String,
    'duration': fields.Integer,
    'screeningmodel': fields.String,
    'openday': fields.DateTime,
    'backgroundpicture': fields.String,
}

multi_movie_fields = {
    'status': fields.Integer,
    'msg': fields.String,
    'data': fields.List(fields.Nested(movie_fields))
}


class MoviesResource(Resource):
    @marshal_with(multi_movie_fields)
    def get(self):

        movies = Movie.query.all()

        data = {'msg': 'OK', 'status': HTTP_OK, 'data': movies}

        return data

    @login_required
    def post(self):
Exemplo n.º 7
0
                          db.ForeignKey('author_model.id'),
                          nullable=False)


"""
Resource fields for marshalling
"""
post_fields = {
    'title': fields.String,
    'content': fields.String,
    'author_id': fields.Integer
}

author_fields = {
    'name': fields.String,
    'posts': fields.List(fields.Nested(post_fields))
}
"""
Controllers
"""


class Post(Resource):
    @marshal_with(post_fields)
    def get(self, post_id):
        return PostModel.query.filter_by(id=post_id).first()


class PostList(Resource):
    @marshal_with(post_fields)
    def get(self):
from flask_restful import Resource, reqparse, request
from flask_restful import fields, marshal_with, marshal
from .model import Todo
from app import db

todo_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'description': fields.String,
    'user_id': fields.Integer
}

todo_list_fields = {
    'count': fields.Integer,
    'todos': fields.List(fields.Nested(todo_fields)),
}

todo_post_parser = reqparse.RequestParser()
todo_post_parser.add_argument('name', type=str, required=True, location=['json'],
                              help='name parameter is required')
todo_post_parser.add_argument('description', type=str, required=True, location=['json'],
                              help='description parameter is required')
todo_post_parser.add_argument('user_id', type=int, required=True, location=['json'],
                              help='user_id parameter is required')


class TodosResource(Resource):
    def get(self, todo_id=None):
        if todo_id:
            todo = Todo.query.filter_by(id=todo_id).first()
            return marshal(todo, todo_fields)
Exemplo n.º 9
0
}

nested_comment_fields = {
    'id': fields.Integer(),
    'time': fields.Integer(),
    'content': fields.String(),
    'author': fields.String()
}

blog_fields = {
    'id': fields.Integer(),
    'author': fields.String(),
    'title': fields.String(),
    'content': fields.String(),
    'time': fields.Integer(),
    'tags': fields.List(fields.Nested(nested_tag_fields)),
    # 'comments': fields.List(fields.Nested(nested_comment_fields))
}

blog_title_fields = {
    'id': fields.Integer(),
    'author': fields.String(),
    'title': fields.String(),
    'time': fields.Integer(),
    'tag': fields.String(),
}

tag_blog_fields = {
    'id': fields.Integer(),
    'author': fields.String(),
    'title': fields.String(),
Exemplo n.º 10
0
            'B':[{},{},{}],
        }
    }
'''

########################## 方式一 ##########################
city_fields = {
    "id": fields.Integer,
    "parentId": fields.Integer,
    "regionName": fields.String,
    "cityCode": fields.Integer,
    "pinYin": fields.String
}

letter_fields = {
    'A': fields.List(fields.Nested(city_fields)),
    'B': fields.List(fields.Nested(city_fields)),
    'C': fields.List(fields.Nested(city_fields)),
    'D': fields.List(fields.Nested(city_fields)),
}

result_fields = {
    'status': fields.Integer(default=200),
    'msg': fields.String(default='区域数据获取成功'),
    'date': fields.String(default=str(time.time())),
    'data': fields.Nested(letter_fields),
    'num': fields.Integer
}

# class CityResource(Resource):
#     @marshal_with(result_fields)
Exemplo n.º 11
0
playlist_update_args.add_argument("owner_id",
                                  type=int,
                                  help="owner of the playlist")
playlist_update_args.add_argument("is_private", type=bool, help="is private")

video_fields = {
    'id': fields.Integer,
    'url': fields.String,
}

playlist_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'owner_id': fields.Integer,
    'is_private': fields.Boolean,
    'videos': fields.List(fields.Nested(video_fields))
}

video_put_args = reqparse.RequestParser()
video_put_args.add_argument("url",
                            type=str,
                            help="Url of the video",
                            required=True)

video_update_args = reqparse.RequestParser()
video_update_args.add_argument("url", type=str, help="name of the playlist")


@auth.verify_password
def verify_password(username, password):
    if User.query.filter_by(login=username).first() and \
Exemplo n.º 12
0
#!/usr/bin/env python
# encoding: utf-8
"""
    File name: book_type.py
    Function Des: ...
    ~~~~~~~~~~
    
    author: Nadeem <*****@*****.**>
    
"""
from flask_restful import fields

book_type_fields = {
    'id': fields.String,
    'name': fields.String,
}

# for get /types
book_types_fields = {
    'books_types': fields.List(fields.Nested(book_type_fields))
}
Exemplo n.º 13
0
from App.apis.admin.utils import login_required
from App.apis.api_constant import HTTP_OK
from App.models.cinema_admin.cinema_user_model import CinemaUser

cinema_user_fields = {
    "id": fields.Integer,
    "username": fields.String,
    "phone": fields.String,
    "password": fields.String(attribute="_password"),
    "is_verify": fields.Boolean
}

single_cinema_user_fields = {
    "status": fields.Integer,
    "msg": fields.String,
    "data": fields.Nested(cinema_user_fields)
}

multi_cinema_user_fields = {
    "status": fields.Integer,
    "msg": fields.String,
    "data": fields.List(fields.Nested(cinema_user_fields))
}


class AdminCinemaUsersResource(Resource):
    @login_required
    def get(self):
        cinema_users = CinemaUser.query.all()
        data = {
            "msg": "ok",
Exemplo n.º 14
0
class AddOneCompany(Resource):
    data = {
        'code': fields.Integer,
        'data': fields.Nested(company_fields),
        'msg': fields.String
    }

    @marshal_with(data)
    def get(self):
        # 获取单个的合作公司信息
        args = parser.parse_args()
        company_id = args.get('id')
        company = Company.query.get(company_id)
        return handle_data(company)

    @staticmethod
    def post():
        # 新增单个的合作公司
        args = parser.parse_args()
        company = demjson.decode(args.get('data'))
        json_params_data = get_params(company)
        records = company.get('records')
        current_company = create_company(json_params_data)
        db.session.add(current_company)
        db.session.flush()
        for record in records:
            current_record = Records(company_id=current_company.id,
                                     content=record.get('content'))
            db.session.add(current_record)
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
        return handle_data('添加成功!')

    @staticmethod
    def put():
        # 修改单个合作公司的信息
        args = parser.parse_args()
        data = args.get('data')
        company = demjson.decode(data)
        name = company.get('name')
        industry_type = company.get('industry_type')
        info = company.get('info')
        register_capital = company.get('register_capital')
        contact_person = company.get('contact_person')
        contacts = company.get('contacts')
        contacts1 = company.get('contacts1')
        level = company.get('level')
        credentials = company.get('credentials')
        recent_situation = company.get('recent_situation')
        url = company.get('url')
        company_id = company.get('id')
        current_company = Company.query.get(company_id)
        current_company.name = name
        current_company.industry_type = industry_type
        current_company.info = info
        current_company.register_capital = register_capital
        current_company.contact_person = contact_person
        current_company.contacts = contacts
        current_company.contacts1 = contacts1
        current_company.level = level
        current_company.recent_situation = recent_situation
        current_company.url = url
        current_company.credentials = credentials
        try:
            db.session.add(current_company)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
        return handle_data('修改成功!')
Exemplo n.º 15
0
from App.apis.viewer.seat_utils import get_avaliable_seats
from App.models.cinema.hall_model import Hall
from App.models.cinema.paidang_model import PaiDang
from App.models.viewer.seat_order_model import SeatOrder, SEAT_ORDER_STATUS_PAYED, SEAT_ORDER_STATUS_NOT_PAY

hall_fields = {
    "h_number": fields.String,
    "h_type": fields.Integer,
    "h_seats": fields.String,
    "h_cinema": fields.Integer
}

single_hall_fields = {
    "msg": fields.String,
    "status": fields.Integer,
    "data": fields.Nested(hall_fields)
}


class SeatResource(Resource):

    @login_required
    def get(self, pk):
        """
            pk  排挡的id
        """
        paidang = PaiDang.query.get(pk)

        if not paidang:
            abort(400, msg="排挡不存在")
Exemplo n.º 16
0
Arquivo: app.py Projeto: jioter/hw
        return value.upper()


# Nested structure.
nested_family_structure = {
    "father": fields.String,
    "mother": fields.String
}

# Custom structure.
structure_fish = {
    "name": Upper,
    "parameters": {"size": fields.List(fields.String),
                   "weight": fields.Integer
                   },
    "family": fields.Nested(nested_family_structure)
}


def decorator(f):
    @wraps(f)
    def decoration(*args, **kwargs):
        print("Hello!")
        return f(*args, **kwargs)
    return decoration


class Fish(Resource):
    def __init__(self, name, size, weight):
        self.name = name
        self.size = size
Exemplo n.º 17
0
from flask_restful import fields, marshal_with
from .. import model
from flask import request
from ..ext import db
from sqlalchemy import text
# from .auth import check_access_permission, check_auth_token

K_ENTITY_TYPE_ID = 'entity_type_id'
K_ENTITY_TYPE_NAME = 'entity_type_name'
K_ENTITY_TYPE_DESCRIPTION = 'description'
entity_type_fields = {
    K_ENTITY_TYPE_ID: fields.Integer(attribute='id'),
    K_ENTITY_TYPE_NAME: fields.String(attribute='entity_type_name'),
    K_ENTITY_TYPE_DESCRIPTION: fields.String(attribute='description')
}
entity_type_list = fields.List(fields.Nested(entity_type_fields))
entity_type_response = {
    'message': fields.String,
    'entity_type_list': entity_type_list
}


class EntityType(Resource):
    @marshal_with(entity_type_response, envelope='resource')
    def get(self):
        # Check if parameters exist, if not, set them None
        try:
            entity_type_id = request.args[K_ENTITY_TYPE_ID]
        except BaseException:
            entity_type_id = None
        try:
Exemplo n.º 18
0
    'pageSize': fields.Integer,
    'current': fields.Integer
}

user_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'username': fields.String,
    'email': fields.String,
    'role_id': fields.Integer,
    'mobile': fields.String,
    'avatar': fields.String,
}

user_list_fields = {
    'pagination': fields.Nested(paginate_fields),
    'list': fields.List(fields.Nested(user_fields)),
}
sortable_fields = ['id', 'name', 'email', 'mobile', 'role_id', 'username']

# parser of post for creating user
user_post_parser = reqparse.RequestParser()
user_post_parser.add_argument('name',
                              type=str,
                              required=True,
                              location=['json'],
                              help='name parameter is required')
user_post_parser.add_argument('username',
                              type=str,
                              required=True,
                              location=['json'],
Exemplo n.º 19
0
class ResponseAPI(ResponseMixin, restful.Resource):

    answer_fields = {
        'id': fields.Integer,
        'question_id': fields.Integer,
        'value': fields.String
    }

    response_fields = {
        'id': fields.Integer,
        'application_form_id': fields.Integer,
        'user_id': fields.Integer,
        'is_submitted': fields.Boolean,
        'submitted_timestamp': fields.DateTime(dt_format='iso8601'),
        'is_withdrawn': fields.Boolean,
        'withdrawn_timestamp': fields.DateTime(dt_format='iso8601'),
        'started_timestamp': fields.DateTime(dt_format='iso8601'),
        'answers': fields.List(fields.Nested(answer_fields)),
        'language': fields.String
    }

    @auth_required
    @marshal_with(response_fields)
    def get(self):
        args = self.get_req_parser.parse_args()
        event_id = args['event_id']
        current_user_id = g.current_user['id']

        event = event_repository.get_by_id(event_id)
        if not event:
            return errors.EVENT_NOT_FOUND

        if not event.has_application_form():
            return errors.FORM_NOT_FOUND

        form = event.get_application_form()
        responses = response_repository.get_all_for_user_application(
            current_user_id, form.id)
        return responses

    @auth_required
    @marshal_with(response_fields)
    def post(self):
        args = self.post_req_parser.parse_args()
        user_id = g.current_user['id']
        is_submitted = args['is_submitted']
        application_form_id = args['application_form_id']
        language = args['language']
        if len(language) != 2:
            language = 'en'  # Fallback to English if language doesn't look like an ISO 639-1 code

        application_form = application_form_repository.get_by_id(
            application_form_id)
        if application_form is None:
            return errors.FORM_NOT_FOUND_BY_ID

        user = user_repository.get_by_id(user_id)
        responses = response_repository.get_all_for_user_application(
            user_id, application_form_id)

        if not application_form.nominations and len(responses) > 0:
            return errors.RESPONSE_ALREADY_SUBMITTED

        response = Response(application_form_id, user_id, language)
        if is_submitted:
            response.submit()

        response_repository.save(response)

        answers = []
        for answer_args in args['answers']:
            answer = Answer(response.id, answer_args['question_id'],
                            answer_args['value'])
            answers.append(answer)
        response_repository.save_answers(answers)

        try:
            if response.is_submitted:
                LOGGER.info(
                    'Sending confirmation email for response with ID : {id}'.
                    format(id=response.id))
                user = user_repository.get_by_id(user_id)
                response = response_repository.get_by_id_and_user_id(
                    response.id, user_id)
                self.send_confirmation(user, response)
        except:
            LOGGER.warn(
                'Failed to send confirmation email for response with ID : {id}, but the response was submitted succesfully'
                .format(id=response.id))
        finally:
            return response, 201

    @auth_required
    @marshal_with(response_fields)
    def put(self):
        args = self.put_req_parser.parse_args()
        user_id = g.current_user['id']
        is_submitted = args['is_submitted']
        language = args['language']

        response = response_repository.get_by_id(args['id'])
        if not response:
            return errors.RESPONSE_NOT_FOUND
        if response.user_id != user_id:
            return errors.UNAUTHORIZED
        if response.application_form_id != args['application_form_id']:
            return errors.UPDATE_CONFLICT

        response.is_submitted = is_submitted
        response.language = language
        if is_submitted:
            response.submit()
        response_repository.save(response)

        answers = []
        for answer_args in args['answers']:
            answer = response_repository.get_answer_by_question_id_and_response_id(
                answer_args['question_id'], response.id)
            if answer:
                answer.update(answer_args['value'])
            else:
                answer = Answer(response.id, answer_args['question_id'],
                                answer_args['value'])
            answers.append(answer)
        response_repository.save_answers(answers)

        try:
            if response.is_submitted:
                LOGGER.info(
                    'Sending confirmation email for response with ID : {id}'.
                    format(id=response.id))
                user = user_repository.get_by_id(user_id)
                response = response_repository.get_by_id_and_user_id(
                    response.id, user_id)
                self.send_confirmation(user, response)
        except:
            LOGGER.warn(
                'Failed to send confirmation email for response with ID : {id}, but the response was submitted succesfully'
                .format(id=response.id))
        finally:
            return response, 200

    @auth_required
    def delete(self):
        args = self.del_req_parser.parse_args()
        current_user_id = g.current_user['id']

        response = response_repository.get_by_id(args['id'])
        if not response:
            return errors.RESPONSE_NOT_FOUND

        if response.user_id != current_user_id:
            return errors.UNAUTHORIZED

        response.withdraw()
        response_repository.save(response)

        try:
            user = user_repository.get_by_id(current_user_id)
            event = response.application_form.event
            organisation = event.organisation

            emailer.email_user(
                'withdrawal',
                template_parameters=dict(organisation_name=organisation.name),
                event=event,
                user=user)

        except:
            LOGGER.error(
                'Failed to send withdrawal confirmation email for response with ID : {id}, but the response was withdrawn succesfully'
                .format(id=args['id']))

        return {}, 204

    def send_confirmation(self, user, response):
        try:
            answers = response.answers
            if not answers:
                LOGGER.warn(
                    'Found no answers associated with response with id {response_id}'
                    .format(response_id=response.id))

            application_form = response.application_form
            if application_form is None:
                LOGGER.warn(
                    'Found no application form with id {form_id}'.format(
                        form_id=response.application_form_id))

            event = application_form.event
            if event is None:
                LOGGER.warn('Found no event id {event_id}'.format(
                    form_id=application_form.event_id))
        except:
            LOGGER.error(
                'Could not connect to the database to retrieve response confirmation email data on response with ID : {response_id}'
                .format(response_id=response.id))

        try:
            question_answer_summary = strings.build_response_email_body(
                answers, user.user_primaryLanguage)

            if event.has_specific_translation(user.user_primaryLanguage):
                event_description = event.get_description(
                    user.user_primaryLanguage)
            else:
                event_description = event.get_description('en')

            emailer.email_user(
                'confirmation-response',
                template_parameters=dict(
                    event_description=event_description,
                    question_answer_summary=question_answer_summary,
                ),
                event=event,
                user=user)

        except Exception as e:
            LOGGER.error(
                'Could not send confirmation email for response with id : {response_id} due to: {e}'
                .format(response_id=response.id, e=e))
Exemplo n.º 20
0
user_detail_fields = {
    'email': fields.String,
    'first_name': fields.String,  # Optional
    'last_name': fields.String,  # Optional
    'full_name': fields.String,  # Optional
    'is_active': fields.Boolean,  # Optional
    'github_username': fields.String,  # Optional
    'slack_id': fields.String,  # Optional
    'team_name': fields.String,  # Optional
    'employee_type': fields.String,  # Optional
    'manager_fullname': fields.String,  # Optional
}

table_list_fields = {
    'table': fields.List(fields.Nested(popular_table_fields))
}


LOGGER = logging.getLogger(__name__)


class UserDetailAPI(BaseAPI):
    """
    User detail API for people resources
    """

    def __init__(self) -> None:
        self.client = get_proxy_client()
        super().__init__(UserSchema, 'user', self.client)
Exemplo n.º 21
0
    'id': fields.Integer,
    'name': fields.String,
}

user_fields = {
    'id': fields.Integer,
    'email': fields.String,
    'username': fields.String,
    'chinese_name': fields.String,
    'cellphone': fields.String,
    'position': fields.String,
    'location': fields.String,
    'member_since': fields.String,
    'last_seen': fields.String,
    'actived': fields.Integer,
    'roles': fields.List(fields.Nested(role_fields)),
}

single_user_fields = {
    'id': fields.Integer,
    'email': fields.String,
    'username': fields.String,
    'chinese_name': fields.String,
    'cellphone': fields.String,
    'position': fields.String,
    'location': fields.String,
    'member_since': fields.String,
    'last_seen': fields.String,
    'can_add_server': fields.Boolean,
    'can_add_view': fields.Boolean,
    'can_add_zone': fields.Boolean,
Exemplo n.º 22
0
from sfo_server.decorate import access_log_decorate, login_required, permission_required

config = Config()

ring_fields_map = {
    "status":
    fields.Integer,
    "message":
    fields.String,
    "data":
    fields.List(
        fields.Nested({
            "guid": fields.String,
            "cluster_name": fields.String,
            "ring_name": fields.String,
            "part_power": fields.String,
            "replicas": fields.String,
            "min_part_hours": fields.String,
            "add_time": fields.String,
        }))
}


def get_ring_info(cluster_name, ring_name):
    status = ''
    message = ''
    data = ''
    resp = {"status": status, "data": data, "message": message}
    rm = RingManager(cluster_name)
    try:
        content = rm.ring_info(ring_name)
Exemplo n.º 23
0
from flask import request
from flask_restful import Resource, fields, marshal_with, marshal, abort, reqparse

from App.models import Goods

goods_fields = {
    "id": fields.Integer,
    "name": fields.String(attribute='g_name'),
    "g_price": fields.Float,
    'uri': fields.Url('single_goods', absolute=True)
}

single_goods_fields = {
    "data": fields.Nested(goods_fields),
    "status": fields.Integer,
    "msg": fields.String,
}

multi_goods_fields = {
    "status": fields.Integer,
    "msg": fields.String,
    "data": fields.List(fields.Nested(goods_fields)),
    "desc": fields.String(default='success'),
    "number": fields.Integer
}

parser = reqparse.RequestParser()
parser.add_argument("g_name",
                    type=str,
                    required=True,
                    help="please input g_name")
Exemplo n.º 24
0
    'name': fields.Raw,
    'default': fields.Raw,
    'hostnames': fields.List(fields.String),
}

key_fields = {'id': fields.Raw, 'app_name': fields.Raw, 'token': fields.Raw, 'valid_until': FieldDate}

equipment_provider_fields = {
    'id': fields.Raw,
    'klass': fields.Raw,
    'args': fields.Raw,
    'created_at': FieldDate,
    'updated_at': FieldDate,
    'discarded': fields.Raw,
}
equipment_provider_list_fields = {'equipments_providers': fields.List(fields.Nested(equipment_provider_fields))}

streetnetwork_backend_fields = {
    'id': fields.Raw,
    'klass': fields.Raw,
    'args': fields.Raw,
    'created_at': FieldDate,
    'updated_at': FieldDate,
    'discarded': fields.Raw,
}
streetnetwork_backend_list_fields = {
    'streetnetwork_backends': fields.List(fields.Nested(streetnetwork_backend_fields))
}

# Create a url to streetnetwork_backends to access the conf directly
class FieldUrlStreetNetworkBackend(fields.Raw):
Exemplo n.º 25
0
class Questions(Resource):
    ask_args = {
        'school_id': fields.Int(required=True),
        'ask_text': fields.Str(missing=None),
        'voice_url': fields.Str(missing=None),
        'voice_duration': fields.Int(missing=0),
        'img_ids': fields.Str(missing=None)
    }

    ask_list_args = {
        'school_id': fields.Int(required=True),
        'page': fields.Int(missing=1),
        'per_page': fields.Int(missing=10),
        'answered': fields.Int(validate=validate.OneOf([0, 1, 2]), missing=0)
    }

    answer_info = {
        'code': rfields.Integer,
        'id': rfields.Integer,
        'student_id': rfields.Integer,
        'school_id': rfields.Integer,
        'teacher_id': rfields.Integer,
        'ask_id': rfields.Integer,
        'timestamp': rfields.DateTime(dt_format='iso8601'),
        'ask_text': rfields.String,
        'voice_url': rfields.String,
        'voice_duration': rfields.String,
        'imgs': rfields.List(rfields.String)
    }

    ask_info = {
        'code':
        rfields.Integer,
        'ask':
        rfields.Nested({
            'id': rfields.Integer,
            'student_id': rfields.Integer,
            'school_id': rfields.Integer,
            'timestamp': rfields.DateTime(dt_format='iso8601'),
            'ask_text': rfields.String,
            'voice_url': rfields.String,
            'voice_duration': rfields.String,
            'imgs': rfields.List(rfields.String),
            'answers': rfields.Nested(answer_info),
            'be_answered': rfields.Boolean,
            'answer_grate': rfields.Integer
        })
    }

    ask_list_info = {
        'code':
        rfields.Integer,
        'asks':
        rfields.Nested({
            'id': rfields.Integer,
            'student_id': rfields.Integer,
            'school_id': rfields.Integer,
            'timestamp': rfields.DateTime(dt_format='iso8601'),
            'ask_text': rfields.String,
            'voice_url': rfields.String,
            'voice_duration': rfields.String,
            'imgs': rfields.List(rfields.String),
            'be_answered': rfields.Boolean,
            'answer_grate': rfields.Integer
        }),
        'prev':
        rfields.String(default=''),
        'next':
        rfields.String(default=''),
        'count':
        rfields.Integer
    }

    @marshal_with(ask_info)
    @use_args(ask_args)
    def post(self, args):
        s_id = args['school_id']
        abort_if_school_doesnt_exist(s_id)
        if g.student_user.is_school_joined(s_id) is False:
            abort(403, code=0, message='不是这个学校/机构的学生')
        if g.student_user.can_ask(s_id) is False:
            abort(403, code=0, message='你的提问次数已经用完了')
        imgs = []
        img_ids = args['img_ids']
        if img_ids:
            img_list = img_ids.rsplit(',')
            for i in img_list:
                img = Topicimage.query.get(i)
                if img is None:
                    abort(401, message='图片不存在')
                imgs.append(img.img_url)
        if not (args['ask_text'] or args['voice_url'] or img_ids):
            abort(400, code=0, message='没有提问任何问题')
        ask = Ask(school_id=s_id,
                  student_id=g.student_user.id,
                  ask_text=args['ask_text'],
                  voice_url=args['voice_url'],
                  voice_duration=args['voice_duration'],
                  img_ids=img_ids)
        db.session.add(ask)
        db.session.commit()
        ask.imgs = imgs
        member_info = SchoolStudent.query.filter_by(
            school_id=s_id, student_id=g.student_user.id).first()
        if member_info.vip_times > 0:
            member_info.vip_times -= 1
        else:
            member_info.nomal_times -= 1
        db.session.add(member_info)
        db.session.commit()
        result = {'code': 1, 'ask': ask}
        return result, 200

    @marshal_with(ask_list_info)
    @use_args(ask_list_args)
    def get(self, args):
        s_id = args['school_id']
        page = args['page']
        per_page = args['per_page']
        answered = args['answered']
        abort_if_school_doesnt_exist(s_id)
        if g.student_user.is_school_joined(s_id) is False:
            abort(403, code=0, message='不是这个学校/机构的学生')
        # 全部
        if answered == 0:
            pagination = Ask.query.filter_by(
                school_id=s_id, student_id=g.student_user.id).order_by(
                    Ask.id.desc()).paginate(page=page,
                                            per_page=per_page,
                                            error_out=True)
        # 已回答
        if answered == 1:
            pagination = Ask.query.filter_by(school_id=s_id,
                                             student_id=g.student_user.id,
                                             be_answered=True).order_by(
                                                 Ask.id.desc()).paginate(
                                                     page=page,
                                                     per_page=per_page,
                                                     error_out=True)
        # 未回答
        if answered == 2:
            pagination = Ask.query.filter_by(school_id=s_id,
                                             student_id=g.student_user.id,
                                             be_answered=False).order_by(
                                                 Ask.id.desc()).paginate(
                                                     page=page,
                                                     per_page=per_page,
                                                     error_out=True)
        asks = pagination.items
        prev = None
        if pagination.has_prev:
            prev = url_for('student_api.asks',
                           s_id=s_id,
                           page=page - 1,
                           per_page=per_page)
        next = None
        if pagination.has_next:
            next = url_for('student_api.asks',
                           s_id=s_id,
                           page=page + 1,
                           per_page=per_page)

        for ask in asks:
            ask = imgidsToimgs(ask)
            '''
            imgs = []
            img_ids = ask.img_ids
            if img_ids:
                img_list = img_ids.rsplit(',')
                for i in img_list:
                    img = Topicimage.query.get(i)
                    imgs.append(img.img_url)
            ask.imgs = imgs
            '''

        result = {
            'code': 1,
            'asks': asks,
            'prev': prev,
            'next': next,
            'count': pagination.total
        }
        return result, 200
Exemplo n.º 26
0
from search_service.proxy import get_proxy_client

tag_fields = {"tag_name": fields.String}

table_fields = {
    "name": fields.String,
    "key": fields.String,
    # description can be empty, if no description is present in DB
    "description": fields.String,
    "cluster": fields.String,
    "database": fields.String,
    "schema": fields.String,
    "column_names": fields.List(fields.String),
    # tags can be empty list
    "tags": fields.List(fields.Nested(tag_fields)),
    # badges can be an empty list
    "badges": fields.List(fields.Nested(tag_fields)),
    # last etl timestamp as epoch
    "last_updated_timestamp": fields.Integer,
    "display_name": fields.String,
    "schema_description": fields.String
}

search_table_results = {
    "total_results": fields.Integer,
    "results": fields.Nested(table_fields, default=[])
}

TABLE_INDEX = 'table_search_index'
Exemplo n.º 27
0
from flask_restful import reqparse, abort, Api, Resource, request, fields, marshal_with

from ..service.task import save_new_task, get_all_tasks, get_a_task, update_a_task, delete_a_task

from .. import api

task_fields = {
    'id': fields.Integer,
    'description': fields.String,
    'state_id': fields.Integer,
    'owner_id': fields.Integer,
    'created_date': fields.DateTime,
    'updated_date': fields.DateTime,
}

task_list_fields = {'tasks': fields.List(fields.Nested(task_fields))}


@api.resource('/tasks')
class TaskList(Resource):
    @marshal_with(task_fields)
    def get(self):
        """List all registered tasks"""
        return get_all_tasks()

    def post(self):
        """Creates a new Task """
        data = request.get_json()
        return save_new_task(data=data)

Exemplo n.º 28
0
from flask_restful import fields

from shemas import response_schema

__all__ = [
    "project_type_list_schema",
    "short_project_type_schema",
    "ext_project_type_schema",
    "base_project_type_schema"
]

base_project_type_schema = dict(
    id=fields.Integer,
    title=fields.String,
)

project_type_list_schema = dict(
    response_schema,
    data=fields.List(fields.Nested(base_project_type_schema))
)

short_project_type_schema = dict(
    response_schema,
    data=fields.List(fields.Nested(base_project_type_schema))
)

ext_project_type_schema = dict(
    response_schema,
    data=fields.List(fields.Nested(base_project_type_schema))
)
Exemplo n.º 29
0
    '''
    resp = make_response(json.dumps(data), code)
    resp.headers.extend(headers or {})
    return resp


TAG_FIELDS = {
    "id": fields.Integer,
    "name": fields.String,
}

FEED_FIELDS = {
    "id": fields.Integer,
    "url": fields.String,
    "flag": fields.Integer,
    "tags": fields.List(fields.Nested(TAG_FIELDS)),
    "tags2": fields.List(fields.Nested(TAG_FIELDS)),
}


class FeedList(Resource):
    '''
    this is Task list resource
    '''

    #decorators = [auth.login_required]

    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument("url",
                                   type=unicode,
Exemplo n.º 30
0
            return str(value)


record_fields = {
    'id': fields.Integer,
    'content': StringUndefinedNone,
    'company_id': fields.Integer
}

company_fields = {
    'id': fields.Integer,
    'name': StringUndefinedNone,
    'info': StringUndefinedNone,
    'register_capital': StringUndefinedNone,
    'industry_type': fields.Integer,
    'records': fields.Nested(record_fields),
    'contact_person': StringUndefinedNone,
    'contacts': StringUndefinedNone,
    'contacts1': StringUndefinedNone,
    'recent_situation': StringUndefinedNone,
    'url': StringUndefinedNone,
    'level': StringUndefinedNone,
    'credentials': StringUndefinedNone
}


def get_params(company):
    name = company.get('name')
    industry_type = company.get('industry_type')
    info = company.get('info')
    register_capital = company.get('register_capital')