Beispiel #1
0
 def post(self):
     parser = RequestParser()
     parser.add_argument('name', type=str, required=True)
     args = parser.parse_args()
     server = get_instance()
     args['user_auth'] = request.headers['Authorization']
     server.join_room(**args)
Beispiel #2
0
    def post(self):
        """Adds in a new youtube video for processing."""
        parser = RequestParser()
        parser.add_argument('url', required=True)
        args = parser.parse_args()

        logging.info('Enqueing {url:s}', args)
        # parse youtube url in the form of http://youtube.com/watch?v=<VIDEO_ID>
        # parse the extracted query to get the first available 'v' param
        parsed = parse.urlparse(args['url'])
        video_id = parse.parse_qs(parsed.query).get('v')[0]
        logging.debug('Found video_id {0}', video_id)
        if not video_id:
            msg = "Could not extract video_id (found '{0}') from {1}".format(
                video_id, args['url'])
            logging.warn(msg)
            return abort(400, message=msg)

        res = chain(
            tasks.captions.youtube_captions_from_video.s(video_id),
            tasks.captions.annotate_events_in_captions.s(video_id),
            tasks.captions.event_dates_from_timeml_annotated_captions.s(),
            tasks.wikitext.wikipedia_events_from_dates.s(),
            tasks.wikitext.event_entities_from_wikitext.s(),
            tasks.wikitext.match_event_via_entities.s(),
            tasks.wikitext.resolve_match_link_topics.s(),
            # tasks.requests.send_url_payload(app.config['WIKITEXT_PAYLOAD_DEST_URL']),
        ).apply_async()

        return {
            'url': args['url'],
            'video_id': video_id,
            'task_id': res.id
        }
Beispiel #3
0
 def post(self, name):
     user_auth = request.headers['Authorization']
     parser = RequestParser()
     parser.add_argument('message', type=str, required=True)
     message = parser.parse_args()['message']
     server = get_instance()
     server.handle_message(user_auth, name, message)
Beispiel #4
0
    def test_parse_required(self):
        app = Flask(__name__)
        with app.app_context():
            req = Request.from_values("/bubble")

            parser = RequestParser()
            parser.add_argument("foo", required=True, location='values')

            message = ''
            try:
                parser.parse_args(req)
            except exceptions.BadRequest as e:
                message = e.data['message']

            self.assertEquals(message, ({'foo': 'Missing required parameter in '
                                                'the post body or the query '
                                                'string'}))

            parser = RequestParser()
            parser.add_argument("bar", required=True, location=['values', 'cookies'])

            try:
                parser.parse_args(req)
            except exceptions.BadRequest as e:
                message = e.data['message']
            self.assertEquals(message, ({'bar': 'Missing required parameter in '
                                                'the post body or the query '
                                                'string or the request\'s '
                                                'cookies'}))
Beispiel #5
0
    def test_parse_foo_operators_four_hunderd(self):
        app = Flask(__name__)
        with app.app_context():
            parser = RequestParser()
            parser.add_argument("foo", type=int),

            self.assertRaises(exceptions.BadRequest, lambda: parser.parse_args(Request.from_values("/bubble?foo=bar")))
    def test_parse_required(self):
        req = Request.from_values("/bubble")

        parser = RequestParser()
        parser.add_argument("foo", required=True)

        self.assertRaises(exceptions.BadRequest, lambda: parser.parse_args(req))
Beispiel #7
0
 def bad_choice():
     parser = RequestParser()
     parser.add_argument('foo', choices=['one', 'two'])
     req = Mock(['values'])
     req.values = MultiDict([('foo', 'three')])
     parser.parse_args(req)
     abort.assert_called_with(400, message='three is not a valid choice')
Beispiel #8
0
    def test_parse_lte(self):
        req = Request.from_values("/bubble?foo<=bar")
        parser = RequestParser()
        parser.add_argument("foo", operators=["<="])

        args = parser.parse_args(req)
        self.assertEquals(args['foo'], "bar")
Beispiel #9
0
    def test_parse_unicode(self):
        req = Request.from_values("/bubble?foo=barß")
        parser = RequestParser()
        parser.add_argument("foo")

        args = parser.parse_args(req)
        self.assertEquals(args['foo'], u"barß")
Beispiel #10
0
    def test_parse_required(self):
        req = Request.from_values("/bubble")

        parser = RequestParser()
        parser.add_argument("foo", required=True, location='values')

        message = ''
        try:
            parser.parse_args(req)
        except exceptions.BadRequest as e:
            message = e.data['message']

        self.assertEquals(message, (u'Missing required parameter foo in the '
                                    'post body or the query string'))

        parser = RequestParser()
        parser.add_argument("bar", required=True, location=['values', 'cookies'])

        try:
            parser.parse_args(req)
        except exceptions.BadRequest as e:
            message = e.data['message']

        self.assertEquals(message, (u"Missing required parameter bar in the "
                                    "post body or the query string or the "
                                    "request's cookies"))
Beispiel #11
0
    def test_parse_choices(self):
        req = Request.from_values("/bubble?foo=bar")

        parser = RequestParser()
        parser.add_argument("foo", choices=["bat"]),

        self.assertRaises(exceptions.BadRequest, lambda: parser.parse_args(req))
Beispiel #12
0
    def test_parse_choices_sensitive(self):
        req = Request.from_values("/bubble?foo=BAT")

        parser = RequestParser()
        parser.add_argument("foo", choices=["bat"], case_sensitive=True),

        self.assertRaises(exceptions.BadRequest, lambda: parser.parse_args(req))
 def bad_choice():
     parser = RequestParser()
     parser.add_argument("foo", choices=["one", "two"])
     req = Mock(["values"])
     req.values = MultiDict([("foo", "three")])
     parser.parse_args(req)
     abort.assert_called_with(400, message="three is not a valid choice")
Beispiel #14
0
    def test_passing_arguments_object(self):
        req = Request.from_values("/bubble?foo=bar")
        parser = RequestParser()
        parser.add_argument(Argument("foo", type=str))

        args = parser.parse_args(req)
        self.assertEquals(args['foo'], u"bar")
Beispiel #15
0
    def test_parse_ignore(self):
        req = Request.from_values("/bubble?foo=bar")

        parser = RequestParser()
        parser.add_argument("foo", type=int, ignore=True),

        args = parser.parse_args(req)
        self.assertEquals(args['foo'], None)
    def test_parse(self):
        req = Request.from_values("/bubble?foo=bar")

        parser = RequestParser()
        parser.add_argument("foo"),

        args = parser.parse_args(req)
        self.assertEquals(args["foo"], "bar")
Beispiel #17
0
    def test_parse_choices_correct(self):
        req = Request.from_values("/bubble?foo=bat")

        parser = RequestParser()
        parser.add_argument("foo", choices=["bat"]),

        args = parser.parse_args(req)
        self.assertEquals(args['foo'], "bat")
Beispiel #18
0
    def test_parse_callable_default(self):
        req = Request.from_values("/bubble")

        parser = RequestParser()
        parser.add_argument("foo", default=lambda: "bar")

        args = parser.parse_args(req)
        self.assertEquals(args['foo'], "bar")
Beispiel #19
0
    def test_parse_choices_insensitive(self):
        req = Request.from_values("/bubble?foo=BAT")

        parser = RequestParser()
        parser.add_argument("foo", choices=["bat"], case_sensitive=False),

        args = parser.parse_args(req)
        self.assertEquals('bat', args.get('foo'))
    def test_parse_append_ignore(self):
        req = Request.from_values("/bubble?foo=bar")

        parser = RequestParser()
        parser.add_argument("foo", ignore=True, type=int, action="append"),

        args = parser.parse_args(req)
        self.assertEquals(args["foo"], None)
Beispiel #21
0
    def test_parse_gte_lte_eq(self):
        req = Request.from_values("/bubble?foo>=bar&foo<=bat&foo=foo")

        parser = RequestParser()
        parser.add_argument("foo", operators=[">=", "<=", "="], action="append"),

        args = parser.parse_args(req)
        self.assertEquals(args['foo'], ["bar", "bat", "foo"])
Beispiel #22
0
    def test_parse_default_append(self):
        req = Request.from_values("/bubble")
        parser = RequestParser()
        parser.add_argument("foo", default="bar", action="append")

        args = parser.parse_args(req)

        self.assertEquals(args['foo'], "bar")
Beispiel #23
0
    def test_parse_none(self):
        req = Request.from_values("/bubble")

        parser = RequestParser()
        parser.add_argument("foo")

        args = parser.parse_args(req)
        self.assertEquals(args['foo'], None)
Beispiel #24
0
 def test_help(self, abort):
     from werkzeug.datastructures import MultiDict
     parser = RequestParser()
     parser.add_argument('foo', choices=['one', 'two'], help='Bad choice')
     req = Mock(['values'])
     req.values = MultiDict([('foo', 'three')])
     parser.parse_args(req)
     abort.assert_called_with(400, message='Bad choice')
Beispiel #25
0
    def test_parse_append_single(self):
        req = Request.from_values("/bubble?foo=bar")

        parser = RequestParser()
        parser.add_argument("foo", action="append"),

        args = parser.parse_args(req)
        self.assertEquals(args['foo'], ["bar"])
Beispiel #26
0
    def test_parse_append_default(self):
        req = Request.from_values("/bubble?")

        parser = RequestParser()
        parser.add_argument("foo", action="append"),

        args = parser.parse_args(req)
        self.assertEquals(args['foo'], None)
Beispiel #27
0
    def test_parse_dest(self):
        req = Request.from_values("/bubble?foo=bar")

        parser = RequestParser()
        parser.add_argument("foo", dest="bat")

        args = parser.parse_args(req)
        self.assertEquals(args['bat'], "bar")
Beispiel #28
0
    def test_parse_store_missing(self):
        req = Request.from_values("/bubble")

        parser = RequestParser()
        parser.add_argument("foo", store_missing=False)

        args = parser.parse_args(req)
        self.assertFalse('foo' in args)
Beispiel #29
0
    def test_type_callable(self):
        req = Request.from_values("/bubble?foo=1")

        parser = RequestParser()
        parser.add_argument("foo", type=lambda x: x, required=False),

        args = parser.parse_args(req)
        self.assertEquals(args['foo'], "1")
Beispiel #30
0
    def test_parse_default(self):
        req = Request.from_values("/bubble")

        parser = RequestParser()
        parser.add_argument("foo", default="bar", store_missing=True)

        args = parser.parse_args(req)
        self.assertEquals(args['foo'], "bar")
Beispiel #31
0
 def test_parse_eq(self):
     req = Request.from_values("/bubble?foo=bar")
     parser = RequestParser()
     parser.add_argument("foo"),
     args = parser.parse_args(req)
     self.assertEquals(args['foo'], "bar")
Beispiel #32
0
    def test_parse_required(self):
        req = Request.from_values("/bubble")

        parser = RequestParser()
        parser.add_argument("foo", required=True, location='values')

        message = ''
        try:
            parser.parse_args(req)
        except exceptions.BadRequest as e:
            message = e.data['message']

        self.assertEquals(message, (u'Missing required parameter foo in the '
                                    'post body or the query string'))

        parser = RequestParser()
        parser.add_argument("bar",
                            required=True,
                            location=['values', 'cookies'])

        try:
            parser.parse_args(req)
        except exceptions.BadRequest as e:
            message = e.data['message']

        self.assertEquals(message, (u"Missing required parameter bar in the "
                                    "post body or the query string or the "
                                    "request's cookies"))
Beispiel #33
0
 def test_chaining(self):
     parser = RequestParser()
     self.assertTrue(parser is parser.add_argument("foo"))
Beispiel #34
0
    def get(self):
        """
        @@@
        ## 搜索论文
        ### args

        | 参数名 | 是否可选 | 类型 | 备注 |
        |--------|--------|--------|--------|
        |    words    |    false    |    string   |    检索关键词    |
        |    type    |    false    |    string   |    检索类别    |
        |    offset    |    true    |    int   |    偏移量    |

        type可选 title keywords abstract

        ### return
        - #### data
        >  | 字段 | 可能不存在 | 类型 | 备注 |
        |--------|--------|--------|--------|
        |   \   |    false    |    list   |    检索结果    |

        @@@
        """
        parser = RequestParser()
        parser.add_argument("words", type=str, location="args", required=True)
        parser.add_argument("type", type=str, location="args", required=True)
        parser.add_argument("offset",
                            type=int,
                            location="args",
                            required=False)
        req = parser.parse_args()
        words = req.get("words")
        search_type = req.get("type")
        search_db = ""
        offset = req.get("offset")
        if search_type == 'title':
            search_db = "paperT"
        elif search_type == 'keywords':
            search_db = 'paperK'
        elif search_type == 'abstract':
            search_db = 'paperA'
        else:
            return {'success': False, 'message': '检索类型错误'}, 400
        if words == '' or words.isspace():
            return {'success': True, 'data': []}
        paper_ids = querycl.query(search_db,
                                  search_type,
                                  terms=words,
                                  offset=offset,
                                  limit=20)
        papers_ref = []
        for id in paper_ids:
            paper = db.collection('paper').document(id)
            papers_ref.append(paper)
        papers_ref = db.get_all(papers_ref)
        papers = []
        for paper in papers_ref:
            if paper != None:
                p_id = paper.id
                paper = paper.to_dict()
                paper['id'] = p_id
                get_venue(paper)
                get_authors(paper['authors'])
                papers.append(paper)
        return {'success': True, 'data': papers}
Beispiel #35
0
from flask_restful.reqparse import RequestParser

post_user_profile_parser = RequestParser()
post_user_profile_parser.add_argument('email', required=True)
post_user_profile_parser.add_argument('password', required=True)
post_user_profile_parser.add_argument('full_name', required=True)
post_user_profile_parser.add_argument('phone_number', required=True)
post_user_profile_parser.add_argument('role_id', required=True)
post_user_profile_parser.add_argument('company_id', required=True)

get_user_profile_parser = RequestParser()
get_user_profile_parser.add_argument('email', store_missing=False)
get_user_profile_parser.add_argument('password', store_missing=False)
get_user_profile_parser.add_argument('full_name', store_missing=False)
get_user_profile_parser.add_argument('phone_number', store_missing=False)
get_user_profile_parser.add_argument('role_id', store_missing=False)
get_user_profile_parser.add_argument('company_id', store_missing=False)
Beispiel #36
0
class Code:
    SUCCESS_CODE = 0
    SYSTEM_ERRCODE = 11
    PARAMS_ERRCODE = 21

    msg = {
        SUCCESS_CODE: "success",
        SYSTEM_ERRCODE: "system error",
        PARAMS_ERRCODE: "empty or wrong params"
    }
    
def make_result(data="entrytest", code=Code.SUCCESS_CODE):
    return jsonify({"error_code": code,  "error_message": Code.msg[code],"reference":data})

#获取请求参数以及对参数合法性做校验
parser = RequestParser()
parser.add_argument("a", type=int, location="args", required=True)
parser.add_argument("b", type=str, location="args", required=True)

#使用get方法
class Test(Resource):
    def get(self):
        req = parser.parse_args(strict=True)
        a = req.get("a")
        b = req.get("b")
        return make_result(data="NO."+str(a)+" is "+b)
    
#获取参数   
api.add_resource(Test, "/shopee/test")

#参数错误码
Beispiel #37
0
 def test_parse_eq_other(self):
     parser = RequestParser()
     parser.add_argument("foo"),
     args = parser.parse_args(
         Request.from_values("/bubble?foo=bar&foo=bat"))
     self.assertEquals(args['foo'], "bar")
Beispiel #38
0
 def get(self, id=None):
     parser = RequestParser(trim=True)
     parser.add_argument('amount_lower', type=int)
     parser.add_argument('amount_upper', type=int)
     parser.add_argument('begin_time', type=int)
     parser.add_argument('end_time', type=int)
     parser.add_argument('begin_audit_time', type=int)
     parser.add_argument('end_audit_time', type=int)
     parser.add_argument('qr_code', type=str)
     parser.add_argument('state', type=int)
     parser.add_argument('page', type=int, default=DEFAULT_PAGE)
     parser.add_argument('page_size', type=int, default=DEFAULT_PAGE_SIZE)
     args = parser.parse_args(strict=True)
     critern = set()
     if id is not None:
         critern.add(BankTradeDao.id == id)
     if args['amount_lower'] is not None:
         critern.add(BankTradeDao.amount >= args['amount_lower'])
     if args['amount_upper'] is not None:
         critern.add(BankTradeDao.amount <= args['amount_upper'])
     if args['begin_time'] is not None:
         critern.add(BankTradeDao.pay_time >= args['pay_time'])
     if args['end_time'] is not None:
         critern.add(BankTradeDao.pay_time <= args['pay_time'])
     if args['qr_code'] is not None:
         critern.add(BankTradeDao.qr_code == args['qr_code'])
     if args['state'] is not None:
         critern.add(BankTradeDao.state == args['state'])
     if args['begin_audit_time'] is not None:
         critern.add(BankTradeDao.audit_time >= args['begin_audit_time'])
     if args['end_audit_time'] is not None:
         critern.add(BankTradeDao.audit_time <= args['end_audit_time'])
     query = db.session.query(BankTradeDao).order_by(
         desc(BankTradeDao.action_time))
     pagination = paginate(query, critern, args['page'], args['page_size'])
     return make_response_from_pagination(pagination)
Beispiel #39
0
    validity_end = ArrowDateTime(attribute="not_after")
    replaced_by = fields.Nested(CertificateNestedOutputSchema,
                                many=True,
                                attribute="replaced")
    endpoints = fields.Nested(EndpointNestedOutputSchema,
                              many=True,
                              missing=[])


class CertificateRevokeSchema(LemurInputSchema):
    comments = fields.String()
    crl_reason = fields.String(validate=validate.OneOf(CRLReason.__members__),
                               missing="unspecified")


certificates_list_request_parser = RequestParser()
certificates_list_request_parser.add_argument("short",
                                              type=inputs.boolean,
                                              default=False,
                                              location="args")


def certificates_list_output_schema_factory():
    args = certificates_list_request_parser.parse_args()
    if args["short"]:
        return certificates_short_output_schema
    else:
        return certificates_output_schema


certificate_input_schema = CertificateInputSchema()
Beispiel #40
0
from itertools import groupby
from operator import attrgetter

from . import dataformat
from compair.core import db, event, abort
from compair.authorization import require, allow, is_user_access_restricted
from compair.models import Answer, Assignment, Course, User, Comparison, Criterion, \
    AnswerScore, UserCourse, SystemRole, CourseRole, AnswerComment, AnswerCommentType, \
    File, Group

from .util import new_restful_api, get_model_changes, pagination_parser

answers_api = Blueprint('answers_api', __name__)
api = new_restful_api(answers_api)

new_answer_parser = RequestParser()
new_answer_parser.add_argument('user_id', default=None)
new_answer_parser.add_argument('group_id', default=None)
new_answer_parser.add_argument('comparable', type=bool, default=True)
new_answer_parser.add_argument('content', default=None)
new_answer_parser.add_argument('file_id', default=None)
new_answer_parser.add_argument('draft', type=bool, default=False)

existing_answer_parser = RequestParser()
existing_answer_parser.add_argument('id', required=True, nullable=False, help="Answer id is required.")
existing_answer_parser.add_argument('user_id', default=None)
existing_answer_parser.add_argument('group_id', default=None)
existing_answer_parser.add_argument('comparable', type=bool, default=True)
existing_answer_parser.add_argument('content', default=None)
existing_answer_parser.add_argument('file_id', default=None)
existing_answer_parser.add_argument('draft', type=bool, default=False)
Beispiel #41
0
from bson import ObjectId
from flask_restful import Resource, Api
from flask_restful.reqparse import RequestParser

from . import api_blueprint, db
from ..util import security
from ._conversions import create_release_result
from ._deletion import delete_release
from common.database.contracts import artist_contract as c
from common.database.codecs import release_from_document

api = Api(api_blueprint, prefix='/release')

_arg_parser_create = RequestParser()\
    .add_argument('artist_id', required=True)\
    .add_argument('name', required=True)\
    .add_argument('date')\
    .add_argument('type')

_arg_parser_get = RequestParser()\
    .add_argument('songs')

_arg_parser_patch = RequestParser()\
    .add_argument('name')\
    .add_argument('date')\
    .add_argument('type')


@api.resource('')
class CreateRelease(Resource):
    method_decorators = [security.jwt_required]
Beispiel #42
0
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from src.respond import resp

parser = RequestParser()
parser.add_argument("a",
                    type=int,
                    location="args",
                    required=True,
                    help='a must be int')
parser.add_argument("b",
                    type=str,
                    location="args",
                    required=True,
                    help='b must be a str')


class NewRes(Resource):
    def get(self):
        req = parser.parse_args(strict=True)
        a = req.get("a")
        b = req.get("b")
        res_data = b + ' : ' + str(a)
        return resp.response(code=resp.SUCCESS, data=res_data)
Beispiel #43
0
 def test_parse_lte_gte_missing(self):
     parser = RequestParser()
     parser.add_argument("foo", operators=["<=", "="])
     args = parser.parse_args(Request.from_values("/bubble?foo<=bar"))
     self.assertEquals(args['foo'], "bar")
Beispiel #44
0
from flask_restful.reqparse import RequestParser

refulationParsers = RequestParser(trim=True)

refulationParsers.add_argument('stop_service', type=int)
refulationParsers.add_argument('exempt', type=int)
refulationParsers.add_argument('notify_times', type=int)
refulationParsers.add_argument('pay_times', type=int)
refulationParsers.add_argument('pay_url_times', type=int)
refulationParsers.add_argument('perday_income', type=float)
refulationParsers.add_argument('repetition_time', type=int)
refulationParsers.add_argument('large_limit_lower', type=float)
refulationParsers.add_argument('large_limit_upper', type=float)
refulationParsers.add_argument('small_limit_lower', type=float)
refulationParsers.add_argument('small_limit_upper', type=float)
refulationParsers.add_argument('agents', type=str)
Beispiel #45
0
    def get(self, article_id):
        """
        获取文章详情
        :param article_id: int 文章id
        """
        # 写入埋点日志
        qs_parser = RequestParser()
        qs_parser.add_argument('Trace',
                               type=inputs.regex(r'^.+$'),
                               required=False,
                               location='headers')
        args = qs_parser.parse_args()

        user_id = g.user_id

        # 查询文章数据
        exist = cache_article.ArticleInfoCache(article_id).exists()
        if not exist:
            abort(404, message='The article does not exist.')

        article = cache_article.ArticleDetailCache(article_id).get()

        # 推荐系统所需埋点
        if args.Trace:
            write_trace_log(args.Trace, channel_id=article['ch_id'])

        article['is_followed'] = False
        article['attitude'] = None
        # 增加用户是否收藏了文章
        article['is_collected'] = False

        if user_id:
            # 非匿名用户添加用户的阅读历史
            try:
                cache_user.UserReadingHistoryStorage(user_id).save(article_id)
            except ConnectionError as e:
                current_app.logger.error(e)

            # 查询关注
            # article['is_followed'] = cache_user.UserFollowingCache(user_id).determine_follows_target(article['aut_id'])
            article['is_followed'] = cache_user.UserRelationshipCache(
                user_id).determine_follows_target(article['aut_id'])

            # 查询登录用户对文章的态度(点赞or不喜欢)
            try:
                # article['attitude'] = cache_article.ArticleUserAttitudeCache(user_id, article_id).get()
                article['attitude'] = cache_user.UserArticleAttitudeCache(
                    user_id).get_article_attitude(article_id)
            except SQLAlchemyError as e:
                current_app.logger.error(e)
                article['attitude'] = -1

            # 增加用户是否收藏了文章
            article['is_collected'] = cache_user.UserArticleCollectionsCache(
                g.user_id).determine_collect_target(article_id)

        # 获取相关文章推荐
        article['recomments'] = []
        try:
            similar_articles = self._feed_similar_articles(article_id)
            for _article_id in similar_articles:
                _article = cache_article.ArticleInfoCache(_article_id).get()
                article['recomments'].append({
                    'art_id': _article['art_id'],
                    'title': _article['title']
                })
        except Exception as e:
            current_app.logger.error(e)

        # 更新阅读数
        cache_statistic.ArticleReadingCountStorage.incr(article_id)
        cache_statistic.UserArticlesReadingCountStorage.incr(article['aut_id'])

        return article
Beispiel #46
0
 def post(self):
     parser = RequestParser()
     parser.add_argument('types', type=int, choices=(-1, 0, 1))
     args = parser.parse_args()
     print(args)
     return {}
Beispiel #47
0
class ModReq(Resource):
    get_parser = RequestParser()
    get_parser.add_argument("id", type=int)
    get_parser.add_argument("server", type=str)
    get_parser.add_argument("status",
                            type=str,
                            choices=["open", "elevated", "claimed", "closed"])
    get_parser.add_argument("username", type=str)

    def validate_get(self, args):
        if not any([
                args.get("username"),
                args.get("status"),
                args.get("server"),
                args.get("id")
        ]):
            return {
                'error': [{
                    "message":
                    "an id, a server, a status, or a username must be provided"
                }]
            }

        if args.get("id") and not ModReqModel.objects(uid=args.get("id")):
            return {'error': [{"message": "invalid id"}]}

        if args.get("server") and Server.verify_fid(args.get("server")):
            return {
                'error': [{
                    "message": "the server field must be a valid fid"
                }]
            }

        if args.get("username") and not validate_username(
                args.get("username")):
            return {'error': [{"message": "invalid username"}]}

    @require_api_key(required_access_tokens=['modreq.get'])
    def get(self):
        args = self.get_parser.parse_args()
        validate_args = self.validate_get(args)
        if validate_args:
            return validate_args, 400

        uid = args.get("id")
        server = args.get("server")
        status = args.get("status")
        username = args.get("username")

        modreqs = get_modreqs(uid, server, status, username)

        return {'modreqs': modreqs}

    post_parser = RequestParser()
    post_parser.add_argument("username", type=str, required=True)
    post_parser.add_argument("request", type=str, required=True)
    post_parser.add_argument("server", type=str, required=True)
    post_parser.add_argument("location", type=str, required=True)

    def validate_post(self, args):
        if args.get("username") and not validate_username(
                args.get("username")):
            return {'error': [{"message": "invalid username"}]}

        if args.get("request") and len(args.get("request")) > 1000:
            return {
                'error': [{
                    "message":
                    "the request must be below 1000 characters long"
                }]
            }

        if args.get("server") and Server.verify_fid(args.get("server")):
            return {
                'error': [{
                    "message": "the server field must be a valid fid"
                }]
            }

        if args.get("location") and len(args.get(
                "location")) > 100:  # need a better way to validate location
            # world,x,y,z,pitch,yaw is what we want
            # x, y, and z are doubles
            # pitch and yaw are floats
            # world should only be world, world_nether, or world_the_end
            return {
                'error': [{
                    "message":
                    "the location must be below 100 characters long"
                }]
            }

    @require_api_key(required_access_tokens=['modreq.add'])
    def post(self):
        args = self.post_parser.parse_args()
        validate_args = self.validate_post(args)
        if validate_args:
            return validate_args, 400

        username = args.get("username")
        request = args.get("request")
        server = args.get("server")
        location = args.get("location")

        modreq = ModReqModel(username=username,
                             request=request,
                             server=server,
                             location=location,
                             status="open").save()

        return {'modreq': construct_modreq_data(modreq)}
Beispiel #48
0
from flask_restful.reqparse import RequestParser

# get 请求为args, post请求为json
parser = RequestParser()
parser.add_argument('id', type=int, location='args', required=True)
Beispiel #49
0
    def test_parse_foo_operators_ignore(self):
        parser = RequestParser()
        parser.add_argument("foo", ignore=True)

        args = parser.parse_args(Request.from_values("/bubble"))
        self.assertEquals(args['foo'], None)
Beispiel #50
0
# -*- coding: utf-8 -*-
from app.api_1_0 import api_1_0
from app import db
from app.models import Wallet, SatXpub
from flask_restful.reqparse import RequestParser
from flask import jsonify, request
from app.tools import get_logger, re_email
import json
from bip32 import constants
import constants as tc_constants
import random

parser = RequestParser()

logger = get_logger(__name__)


@api_1_0.before_request
def create_logging():
    if request.method == 'GET':
        logger.info(request.args)
    elif request.method == 'POST':
        logger.info(request.json)


@api_1_0.route('/create_wallet', methods=['post'])
def create_wallet():
    """
    创建钱包
    :return:
    """
Beispiel #51
0
from flask_restful.reqparse import RequestParser

# post
df_merchant_post = RequestParser(trim=True)
df_merchant_post.add_argument('username', type=str)  #用户名
df_merchant_post.add_argument('level', type=int)  #预设等级
df_merchant_post.add_argument('mobilephone', type=str)  #手机号
df_merchant_post.add_argument('email', type=str)  #邮箱
df_merchant_post.add_argument('name', type=str)  #真实姓名
df_merchant_post.add_argument('remark', type=str)  #备注

# get
df_merchant_get = RequestParser(trim=True)
df_merchant_get.add_argument('page', type=int)
df_merchant_get.add_argument('page_size', type=int)

df_merchant_get.add_argument('mer_code', type=str)

df_merchant_get.add_argument('username', type=str)
df_merchant_get.add_argument('begin_time', type=int)
df_merchant_get.add_argument('end_time', type=int)
df_merchant_get.add_argument('state', type=int)
df_merchant_get.add_argument('level', type=int)

# put
df_merchant_put = RequestParser(trim=True)
df_merchant_put.add_argument('mer_code', type=str, required=True)
df_merchant_put.add_argument('state', type=int)
df_merchant_put.add_argument('level', type=int)
df_merchant_put.add_argument('mobilephone', type=str)
df_merchant_put.add_argument('email', type=str)
class ActivityResource(Resource):
    """
    校园活动即post_type=2的POST, 只有指定用户可以发布推文
    """
    def __init__(self):
        super(ActivityResource, self).__init__()

        # ------------------ GET ------------------
        """
        请求地址: /interaction/api/v2/activity
        请求方法: GET
        参数:
            可选参数:
                type 整型值,
                    0(默认值) 表示结果按照活动开始时间排序返回
                    1 表示结果按照发布时间排序返回
                activity_start_time 时间戳
                    type 为 0 时才有意义
                    表示服务器根据activity_start_time为界限,
                    比如activity_start_time为 2016/8/16 那么返回的活动将会是
                    那些已经开始了但是开始时间晚于或者等于2016/8/16的活动
                    以及未来的并未开始的活动
                page_index 页码
                page_size 每页的结果数
        """
        self.get_parser = RequestParser(trim=True)
        self.get_parser.add_argument("type", type=int, location="args")
        self.get_parser.add_argument("activity_start_time",
                                     type=int,
                                     location="args")
        # 用于分页
        self.get_parser.add_argument("page_index", type=int, location="args")
        # 用于分页
        self.get_parser.add_argument("page_size", type=int, location="args")

        # ------------------ GET ------------------

        # ------------------ POST ------------------
        """
        请求地址: /interaction/api/v2/activity
        请求方法: POST
        参数: 以json方式传递参数
            必须参数:
                source 来源, iOS Android 或者可以是部门
                content 此处作为活动的URL
                uid 发布用户的id, 如果用户无权限发布, 那么会返回 403
                token 用户的token
                post_type 取 2
                activity_start_time 活动起始时间戳
                activity_end_time 活动结束时间戳
            可选参数:
                activity_location 活动地点, 如果未指定, 那么默认为 未指定
                description 活动描述
                photo_list_json 同Post的图片格式
        """
        self.post_parser = RequestParser(trim=True)
        self.post_parser.add_argument("source", location="json")
        self.post_parser.add_argument("content",
                                      required=True,
                                      location="json")
        self.post_parser.add_argument("uid",
                                      type=int,
                                      required=True,
                                      location="json")
        self.post_parser.add_argument("token", required=True, location="json")
        # 这里可以不用管post_type参数, 保留同之前API兼容, 提高复用
        self.post_parser.add_argument("post_type",
                                      type=int,
                                      required=True,
                                      location="json")
        self.post_parser.add_argument("activity_start_time",
                                      type=int,
                                      required=True,
                                      location="json")
        self.post_parser.add_argument("activity_end_time",
                                      type=int,
                                      location="json")

        self.post_parser.add_argument("activity_location",
                                      required=False,
                                      location="json")
        self.post_parser.add_argument("description", location="json")
        self.post_parser.add_argument("photo_list_json", location="json")
        # ------------------ POST ------------------

    def query(self, arg_dict):
        # 分页 http://my.oschina.net/ranvane/blog/196906

        # 读取条件

        # 读取类型
        # 默认值为0
        type_ = arg_dict["type"] or 0

        # 设置时间条件
        now = helpers.timestamp_to_string(int(time.time()))
        start_time = arg_dict["activity_start_time"] or now

        # print(depart_time)

        page_index = arg_dict["page_index"] or 1

        page_size = arg_dict["page_size"] or 10

        print("type: {} index: {} size: {}".format(type_, page_index,
                                                   page_size))

        if type_ == 0:
            # 按照活动开始时间排序
            page_obj = \
                models.Post.query\
                    .filter(models.Post.post_type == models.Post.POST_TYPE_SCHOOL_ACTIVITY)\
                    .filter(models.Post.activity_start_time >= start_time)\
                    .filter(models.Post.visibility == models.VISIBILITY_VISIBLE)\
                    .order_by(models.Post.activity_start_time.asc())\
                    .paginate(page_index, page_size, False)
        else:
            # 按照发布时间排序
            page_obj = \
                models.Post.query\
                    .filter(models.Post.post_type == models.Post.POST_TYPE_SCHOOL_ACTIVITY)\
                    .filter(models.Post.visibility == models.VISIBILITY_VISIBLE)\
                    .order_by(models.Post.id.desc())\
                    .paginate(page_index, page_size, False)

        activities = page_obj.items
        # print([a.activity_start_time  for a in activities],"\n=============")

        return activities

    def get(self):
        args = self.get_parser.parse_args(strict=True)

        activities = self.query(args)

        if len(activities) > 0:
            return marshal(activities, ACTIVITY_STRUCTURE)
        else:
            return {"error": "nothing found"}, 404

    def post(self):
        args = self.post_parser.parse_args(strict=True)
        args["post_type"] = PostResource.Post.POST_TYPE_SCHOOL_ACTIVITY

        # 检查token
        if not common.check_token(args):
            return {"error": "wrong token"}, 401
        del args["token"]

        args["activity_location"] = args["activity_location"] or "未指定"

        # 处理时间
        for key in ("activity_start_time", "activity_end_time"):
            args[key] = helpers.timestamp_to_string(args[key])

        # 检测是否有权限发布
        super_users = models.User.query.with_entities(models.User.id).filter(
            models.User.level >= models.User.LEVEL_CAN_POST_ACTIVITY).all()
        super_ids = [user.id for user in super_users]
        if args["uid"] not in super_ids:
            return {"error": "HAVE NOT THE PRIORITY"}, 403  # 没有权限发布
        # 参数新的数据到数据库
        record_id = common.new_record(db, models.Post, **args)

        if record_id != False:
            return {"id": record_id}, 201  # crated
        else:
            return {"error": "failed"}, 500  # Internal Server Error
Beispiel #53
0
from flask_restful.reqparse import RequestParser


def date_parser(data):
    try:
        data = int(data)
    except (TypeError, ValueError):
        raise TypeError("Date must be Int")
    if data == -1:
        return data
    return int(data / 1000)


table_info = RequestParser()
table_info.add_argument('type', location="args", type=int, required=True)

table_query = RequestParser()
table_query.add_argument('page', location='json', type=int)
table_query.add_argument('count', location='json', type=int)
table_query.add_argument('metric', location='json', type=int, required=True)
table_query.add_argument('period', location='json', type=int, required=True)
table_query.add_argument('start',
                         location='json',
                         type=date_parser,
                         required=True)
table_query.add_argument('end',
                         location='json',
                         type=date_parser,
                         required=True)
table_query.add_argument('sort', location='json', type=int, required=True)
table_query.add_argument('sortType', location='json', type=str, required=True)
class CorrectSkewnessApi(Resource):
    post_parser = RequestParser()

    # The following will define additional Swagger documentation for this API
    post_parser.add_argument(
        FORM_PATH,
        type=str,
        required=True,
        location='json',
        help='The form path provided as part of the request body.')
    post_parser.add_argument(
        OUTPUT_PATH,
        type=str,
        required=False,
        location='json',
        help=
        'The corrected form output path provided as part of the request body.')

    @swagger.doc({
        'tags': ['Skewness'],
        'description': 'Correct Skewness API.',
        'reqparser': {
            'name': 'CorrectSkewness',
            'parser': post_parser
        },
        'responses': {
            '200': {
                'description': 'Echo of the values given',
                'examples': {
                    'application/json': {
                        "formPath": "<value>",
                        "outputPath": "<value>"
                    }
                }
            },
            '500': {
                'description': 'Unhandled error'
            }
        }
    })
    def post(self):
        args = self.post_parser.parse_args()
        form_path = ''
        output_path = ''

        try:
            form_path = args[FORM_PATH]
        except Exception as e:
            logging.error(
                f'Failed to find the form path in the body: {str(e)}')

        try:
            output_path = args[OUTPUT_PATH]
        except Exception as e:
            logging.error(
                f'Failed to find the output path in the body: {str(e)}')

        response = request_processor.create_response_single(
            STORAGE_NAME, STORAGE_KEY, VISION_KEY, VISION_REGION, form_path,
            output_path)

        try:
            response_as_json = json.dumps(response)
            return response_as_json, 200
        except Exception as e:
            logging.error(f'Failed to JSONify the response: {str(e)}')

        return '', 500
Beispiel #55
0
#      Author: Birnadin Erick
#      Copyright © 2021. All rights are reserved by Birnadin Erick.
#      This script can be used without any written acknowledgement from author for personal or commercial purpose.

from datetime import datetime as dt

from flask import abort
from flask_restful import Resource
from flask_restful.reqparse import RequestParser

from utility.helpers import create_id
from utility.mongo_api import mdb_api

clans = mdb_api["BugBounty"]["Clans"]

clan_post_args = RequestParser()
clan_get_args = RequestParser()
clan_patch_args = RequestParser()
clan_del_args = RequestParser()

clan_post_args.add_argument("cname", type=str, help="C_404_cn", required=True)
clan_post_args.add_argument("ls", type=str, help="C_404_l")
clan_post_args.add_argument("hs", type=str, help="C_404_h")
clan_post_args.add_argument("bos", type=str, help="C_404_bo")

clan_get_args.add_argument("c_id", type=int, help="C_404_cid", required=True)

clan_patch_args.add_argument("c_id", type=int, help="C_404_cid", required=True)
clan_patch_args.add_argument("opts", type=str, help="C_404_o", required=True)
clan_patch_args.add_argument("poly", type=int, help="C_404_po", required=True)
clan_patch_args.add_argument("params", type=str, help="C_404_p", required=True)
Beispiel #56
0
 def test_namespace_configurability(self):
     self.assertTrue(isinstance(RequestParser().parse_args(), Namespace))
     self.assertTrue(
         type(RequestParser(namespace_class=dict).parse_args()) is dict)
Beispiel #57
0
    def get(self):
        """
        @@@
        ## 搜索项目
        ### args

        | 参数名 | 是否可选 | 类型 | 备注 |
        |--------|--------|--------|--------|
        |    words    |    false    |    string   |    检索关键词    |
        |    type    |    false    |    string   |    检索类别    |
        |    offset    |    true    |    int   |    偏移量    |

        type可选 title desc abstract

        ### return
        - #### data
        >  | 字段 | 可能不存在 | 类型 | 备注 |
        |--------|--------|--------|--------|
        |   \   |    false    |    list   |    检索结果    |

        @@@
        """
        parser = RequestParser()
        parser.add_argument("words", type=str, location="args", required=True)
        parser.add_argument("type", type=str, location="args", required=True)
        parser.add_argument("offset",
                            type=int,
                            location="args",
                            required=False)
        req = parser.parse_args()
        words = req.get("words")
        search_type = req.get("type")
        search_db = "fund"
        offset = req.get("offset")
        if search_type not in ['title', 'desc', 'abstract']:
            return {'success': False, 'message': '检索类型错误'}, 400
        if words == '' or words.isspace():
            return {'success': True, 'data': []}
        fund_ids = querycl.query(search_db,
                                 search_type,
                                 terms=words,
                                 offset=offset,
                                 limit=20)
        funds_ref = []
        for id in fund_ids:
            fund = db.collection('fund').document(id)
            funds_ref.append(fund)
        funds_ref = db.get_all(funds_ref)
        funds = []
        for fund in funds_ref:
            if fund != None:
                id = fund.id
                fund = fund.to_dict()
                fund['id'] = id
                author = db.collection('author').document(
                    fund['author_id']).get().to_dict()
                author['id'] = fund['author_id']
                fund['author'] = author
                fund.pop('author_id')
                funds.append(fund)
        return {'success': True, 'data': funds}
    def __init__(self):
        super(ActivityResource, self).__init__()

        # ------------------ GET ------------------
        """
        请求地址: /interaction/api/v2/activity
        请求方法: GET
        参数:
            可选参数:
                type 整型值,
                    0(默认值) 表示结果按照活动开始时间排序返回
                    1 表示结果按照发布时间排序返回
                activity_start_time 时间戳
                    type 为 0 时才有意义
                    表示服务器根据activity_start_time为界限,
                    比如activity_start_time为 2016/8/16 那么返回的活动将会是
                    那些已经开始了但是开始时间晚于或者等于2016/8/16的活动
                    以及未来的并未开始的活动
                page_index 页码
                page_size 每页的结果数
        """
        self.get_parser = RequestParser(trim=True)
        self.get_parser.add_argument("type", type=int, location="args")
        self.get_parser.add_argument("activity_start_time",
                                     type=int,
                                     location="args")
        # 用于分页
        self.get_parser.add_argument("page_index", type=int, location="args")
        # 用于分页
        self.get_parser.add_argument("page_size", type=int, location="args")

        # ------------------ GET ------------------

        # ------------------ POST ------------------
        """
        请求地址: /interaction/api/v2/activity
        请求方法: POST
        参数: 以json方式传递参数
            必须参数:
                source 来源, iOS Android 或者可以是部门
                content 此处作为活动的URL
                uid 发布用户的id, 如果用户无权限发布, 那么会返回 403
                token 用户的token
                post_type 取 2
                activity_start_time 活动起始时间戳
                activity_end_time 活动结束时间戳
            可选参数:
                activity_location 活动地点, 如果未指定, 那么默认为 未指定
                description 活动描述
                photo_list_json 同Post的图片格式
        """
        self.post_parser = RequestParser(trim=True)
        self.post_parser.add_argument("source", location="json")
        self.post_parser.add_argument("content",
                                      required=True,
                                      location="json")
        self.post_parser.add_argument("uid",
                                      type=int,
                                      required=True,
                                      location="json")
        self.post_parser.add_argument("token", required=True, location="json")
        # 这里可以不用管post_type参数, 保留同之前API兼容, 提高复用
        self.post_parser.add_argument("post_type",
                                      type=int,
                                      required=True,
                                      location="json")
        self.post_parser.add_argument("activity_start_time",
                                      type=int,
                                      required=True,
                                      location="json")
        self.post_parser.add_argument("activity_end_time",
                                      type=int,
                                      location="json")

        self.post_parser.add_argument("activity_location",
                                      required=False,
                                      location="json")
        self.post_parser.add_argument("description", location="json")
        self.post_parser.add_argument("photo_list_json", location="json")
Beispiel #59
0
    def get(self, id=None):
        parser = RequestParser(trim=True)
        parser.add_argument('page', type=int, default=DEFAULT_PAGE)
        parser.add_argument('levels', type=int)
        parser.add_argument('status', type=int)
        parser.add_argument('type', type=int)
        parser.add_argument('pageSize', type=int, default=DEFAULT_PAGE_SIZE)
        args = parser.parse_args(strict=True)
        pagination = None
        criterion = set()
        if id is not None:
            criterion.add(SystemBankAccount.id == id)
            criterion.add(SystemBankAccount.isDelete == 0)
        # pagination = paginate(SystemBankAccount.query.filter(SystemBankAccount.id == id ,SystemBankAccount.isDelete == 0), page=args['page'], per_page=args['pageSize'])
        else:
            if args['status'] == 1 or args['status'] == 0:
                criterion.add(SystemBankAccount.status == args['status'])
                criterion.add(SystemBankAccount.isDelete == 0)
            # pagination = paginate(SystemBankAccount.query.filter(SystemBankAccount.status == args['status'],SystemBankAccount.isDelete == 0), page=args['page'], per_page=args['pageSize'])
            elif args['levels']:
                criterion.add(
                    func.find_in_set(args['levels'], SystemBankAccount.levels,
                                     SystemBankAccount.isDelete == 0))
            # criterion.add(func.find_in_set(args['levels']))
            # criterion.add(SystemBankAccount.isDelete == 0)
            # pagination = paginate(SystemBankAccount.query.filter(func.find_in_set(args['levels'], SystemBankAccount.levels,SystemBankAccount.isDelete == 0)))
            else:
                criterion.add(SystemBankAccount.isDelete == 0)
            # pagination = paginate(SystemBankAccount.query.filter(SystemBankAccount.isDelete == 0), page=args['page'], per_page=args['pageSize'])
            if args['type'] is not None:
                criterion.add(SystemBankAccount.type == args['type'])
        # pagination = paginate(SystemBankAccount.query.filter(SystemBankAccount.type == args['type']), page=args['page'], per_page=args['pageSize'])

        pagination = paginate(SystemBankAccount.query.filter(*criterion),
                              page=args['page'],
                              per_page=args['pageSize'])
        return make_response_from_pagination(pagination)
Beispiel #60
0
def base_parser():
    r = RequestParser()
    r.add_argument("plate_id", type=int)
    r.add_argument("model", type=str, required=True)
    r.add_argument("quaternion", type=bool, default=False)
    return r