Python flask.ext.restful.reqparse.RequestParser() Examples

The following are 23 code examples of flask.ext.restful.reqparse.RequestParser(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.ext.restful.reqparse , or try the search function .
Example #1
Source File: api.py    From Flask-PostgreSQL-API-Seed with MIT License 6 votes vote down vote up
def post(self):
        req_parser = reqparse.RequestParser()
        req_parser.add_argument('code', type=str, required=True)
        req_parser.add_argument('password', type=str, required=True)
        args = req_parser.parse_args()

        password_reset = db.session.query(PasswordReset
                            ).filter(PasswordReset.code==args['code']
                            ).filter(PasswordReset.date>datetime.now()).first()

        if not password_reset:
            return CODE_NOT_VALID

        password_reset.user.set_password(args['password'])
        db.session.delete(password_reset)
        db.session.commit()

        return {}, 200 
Example #2
Source File: srv.py    From sync-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
def ns_all():
    """ Return all namespaces """
    # We do this outside the blueprint to support the case of an empty
    # public_id.  However, this means the before_request isn't run, so we need
    # to make our own session
    with global_session_scope() as db_session:
        parser = reqparse.RequestParser(argument_class=ValidatableArgument)
        parser.add_argument('limit', default=DEFAULT_LIMIT, type=limit,
                            location='args')
        parser.add_argument('offset', default=0, type=int, location='args')
        parser.add_argument('email_address', type=bounded_str, location='args')
        args = strict_parse_args(parser, request.args)

        query = db_session.query(Namespace)
        if args['email_address']:
            query = query.join(Account)
            query = query.filter_by(email_address=args['email_address'])

        query = query.limit(args['limit'])
        if args['offset']:
            query = query.offset(args['offset'])

        namespaces = query.all()
        encoder = APIEncoder()
        return encoder.jsonify(namespaces) 
Example #3
Source File: word2vec-api.py    From word2vec-flask-api with MIT License 6 votes vote down vote up
def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('positive', type=str, required=False, help="Positive words.", action='append')
        parser.add_argument('negative', type=str, required=False, help="Negative words.", action='append')
        parser.add_argument('topn', type=int, required=False, help="Number of results.")
        args = parser.parse_args()
        pos = filter_words(args.get('positive', []))
        neg = filter_words(args.get('negative', []))
        t = args.get('topn', 10)
        pos = [] if pos == None else pos
        neg = [] if neg == None else neg
        t = 10 if t == None else t
        print "positive: " + str(pos) + " negative: " + str(neg) + " topn: " + str(t)
        try:
            res = model.most_similar_cosmul(positive=pos,negative=neg,topn=t)
            return res
        except Exception, e:
            print e
            print res 
Example #4
Source File: rest_api.py    From dash with MIT License 6 votes vote down vote up
def post(self):
        """
        Handle setting the architechture settings.
        """
        parser = reqparse.RequestParser()
        parser.add_argument('filter_bytes', type=str, required=True,
                            location='json')
        
        args = parser.parse_args()
        ASSEMBLY_STORE.filter_bytes = binascii.unhexlify(args.filter_bytes)
        
        ASSEMBLY_STORE.ClearErrors()
        
        for row in ASSEMBLY_STORE.GetRowsIterator():
            ASSEMBLER.CheckOpcodeBytes(row, ASSEMBLY_STORE)
            
        return jsonify(success="1") 
Example #5
Source File: client_es.py    From poem with MIT License 6 votes vote down vote up
def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('topic')
        parser.add_argument('id')

        args = parser.parse_args()
        topic = args['topic']
        index = 'default'
        if "id" in args:
            index = args['id']

        times, poems, rhyme_words, table_html = get_rhyme_interactive(
            topic, index)
        d = {}
        d['rhyme_words'] = rhyme_words

        json_str = json.dumps(d, ensure_ascii=False)
        r = make_response(json_str)
        sm.clear_status(index)

        return r 
Example #6
Source File: client_es.py    From poem with MIT License 6 votes vote down vote up
def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('topic')
        parser.add_argument('result')
        parser.add_argument('poem1')
        parser.add_argument('poem2')
        parser.add_argument('config_file')

        args = parser.parse_args()
        d = args
        d['time'] = datetime.now().isoformat()
        json_str = json.dumps(d, ensure_ascii=False)
        json_str.replace('\n', "\\n")
        f = open(os.path.join(root_dir, 'py/compare_result_es.txt'), 'a')
        f.write(json_str + "\n")
        f.close()

        r = make_response("Done")

        return r 
Example #7
Source File: client_es.py    From poem with MIT License 5 votes vote down vote up
def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('words')
        parser.add_argument('id')

        args = parser.parse_args()
        words_json = args['words']
        index = 'default'
        if "id" in args:
            index = args['id']

        r = make_response("Got It")
        sm.clear_status(index)

        return r 
Example #8
Source File: ns_api.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def start():
    g.api_version = request.headers.get('Api-Version', API_VERSIONS[0])

    if g.api_version not in API_VERSIONS:
        g.api_version = API_VERSIONS[0]

    if g.api_version == API_VERSIONS[0]:
        g.api_features = APIFeatures(optimistic_updates=True)
    else:
        g.api_features = APIFeatures(optimistic_updates=False)

    request.environ['log_context'] = {
        'endpoint': request.endpoint,
        'api_version': g.api_version,
        'namespace_id': g.namespace_id,
    }

    engine = engine_manager.get_for_id(g.namespace_id)
    g.db_session = new_session(engine)
    g.namespace = Namespace.get(g.namespace_id, g.db_session)

    if not g.namespace:
        # The only way this can occur is if there used to be an account that
        # was deleted, but the API access cache entry has not been expired yet.
        raise AccountDoesNotExistError()

    request.environ['log_context']['account_id'] = g.namespace.account_id
    if hasattr(g, 'application_id'):
        request.environ['log_context']['application_id'] = g.application_id

    is_n1 = request.environ.get('IS_N1', False)
    g.encoder = APIEncoder(g.namespace.public_id, is_n1=is_n1)

    g.parser = reqparse.RequestParser(argument_class=ValidatableArgument)
    g.parser.add_argument('limit', default=DEFAULT_LIMIT, type=limit,
                          location='args')
    g.parser.add_argument('offset', default=0, type=offset, location='args') 
Example #9
Source File: word2vec-api.py    From word2vec-flask-api with MIT License 5 votes vote down vote up
def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('word', type=str, required=True, help="word to query.")
        args = parser.parse_args()
        try:
            res = model[args['word']]
            res = base64.b64encode(res)
            return res
        except Exception, e:
            print e
            return 
Example #10
Source File: word2vec-api.py    From word2vec-flask-api with MIT License 5 votes vote down vote up
def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('w1', type=str, required=True, help="Word 1 cannot be blank!")
        parser.add_argument('w2', type=str, required=True, help="Word 2 cannot be blank!")
        args = parser.parse_args()
        return model.similarity(args['w1'], args['w2']) 
Example #11
Source File: word2vec-api.py    From word2vec-flask-api with MIT License 5 votes vote down vote up
def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('ws1', type=str, required=True, help="Word set 1 cannot be blank!", action='append')
        parser.add_argument('ws2', type=str, required=True, help="Word set 2 cannot be blank!", action='append')
        args = parser.parse_args()
        return model.n_similarity(filter_words(args['ws1']),filter_words(args['ws2'])) 
Example #12
Source File: dist.py    From CuckooSploit with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        RestResource.__init__(self, *args, **kwargs)

        self._parser = reqparse.RequestParser()
        self._parser.add_argument("package", type=str)
        self._parser.add_argument("timeout", type=int)
        self._parser.add_argument("priority", type=int, default=1)
        self._parser.add_argument("options", type=str)
        self._parser.add_argument("machine", type=str)
        self._parser.add_argument("platform", type=str, default="windows")
        self._parser.add_argument("tags", type=str)
        self._parser.add_argument("custom", type=str)
        self._parser.add_argument("memory", type=str)
        self._parser.add_argument("clock", type=int)
        self._parser.add_argument("enforce_timeout", type=bool) 
Example #13
Source File: dist.py    From CuckooSploit with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        RestResource.__init__(self, *args, **kwargs)

        self._parser = reqparse.RequestParser()
        self._parser.add_argument("name", type=str)
        self._parser.add_argument("url", type=str) 
Example #14
Source File: meta.py    From Pi-GPIO-Server with MIT License 5 votes vote down vote up
def __init__(self):
        super(BasicResource, self).__init__()
        self.parser = reqparse.RequestParser() 
Example #15
Source File: client_es.py    From poem with MIT License 5 votes vote down vote up
def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('id')
        args = parser.parse_args()
        index = 'default'
        if "id" in args:
            index = args['id']

        return make_response(sm.get_status(index))

# need to reserve, daniel is using this one 
Example #16
Source File: rest_api.py    From dash with MIT License 5 votes vote down vote up
def post(self):
        """
        Handle setting the architechture settings.
        """
        parser = reqparse.RequestParser()
        parser.add_argument('archmode', type=self.valid_archmode, required=True,
                            location='json')
        parser.add_argument('endian', type=self.valid_endianess, required=True,
                            location='json')
        args = parser.parse_args()
        ASSEMBLER.SetArchAndMode(args.archmode, args.endian)
        ASSEMBLY_STORE.ClearErrors()
        ASSEMBLER.DisassembleAll(ASSEMBLY_STORE) 
        return jsonify(success="1") 
Example #17
Source File: resources.py    From flask-rest-template with The Unlicense 5 votes vote down vote up
def _post_put_parser(self):
        """Request parser for HTTP POST or PUT.
        :returns: flask.ext.restful.reqparse.RequestParser object

        """
        parse = reqparse.RequestParser()
        parse.add_argument(
            'username', type=str, location='json', required=True)
        parse.add_argument(
            'password', type=str, location='json', required=True)

        return parse 
Example #18
Source File: resources.py    From flask-rest-template with The Unlicense 5 votes vote down vote up
def post_put_parser():
    """Request parser for HTTP POST or PUT.
    :returns: flask.ext.restful.reqparse.RequestParser object

    """
    parse = reqparse.RequestParser()
    parse.add_argument(
        'username', type=str, location='json', required=True)
    parse.add_argument(
        'password', type=str, location='json', required=True)

    return parse 
Example #19
Source File: api.py    From Flask-PostgreSQL-API-Seed with MIT License 5 votes vote down vote up
def post(self):
        req_parser = reqparse.RequestParser()
        req_parser.add_argument('email', type=str, required=True)
        args = req_parser.parse_args()

        user = db.session.query(AppUser).filter(AppUser.email==args['email']).first()
        if user:
            password_reset = PasswordReset(user=user)
            db.session.add(password_reset)
            db.session.commit()
            # TODO: Send the email using any preferred method

        return {}, 201 
Example #20
Source File: client_es.py    From poem with MIT License 4 votes vote down vote up
def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('model')
        parser.add_argument('action')
        parser.add_argument('line')
        parser.add_argument('words')
        parser.add_argument('id')

        args = parser.parse_args()

        model_type = int(args['model'])

        action = args['action']
        assert(action == "words" or action == "fsa" or action == "fsaline")

        index = 'default'
        if "id" in args:
            index = args['id']

        iline = int(args['line'])
        assert(iline <= 14 and iline >= 1)

        words = args['words']
        words = tokenize(words)

        line_reverse = 1
        if line_reverse == 1:
            words = words[::-1]

        if action == "words" and len(words) == 1 and words[0] == "":
            words = ["<UNK>"]

        print "poem_interactive", model_type, action, iline, words, index
        times, poems, rhyme_words, table_html = get_poem_interactive(
            model_type, action, index, iline, words)

        rhyme_words_html = "<br//>".join(rhyme_words)

        config_str = ""

        f = open(os.path.join(root_dir, 'py/config_es.txt'))
        for line in f:
            config_str += line.strip() + "<br//>"
        f.close()

        if len(poems) > 0:
            poems = poems[0]

        d = {}
        d['poem'] = poems
        d['config'] = config_str
        d['rhyme_words'] = rhyme_words_html
        d['rhyme_info'] = table_html
        json_str = json.dumps(d, ensure_ascii=False)
        r = make_response(json_str)

        return r 
Example #21
Source File: client_es.py    From poem with MIT License 4 votes vote down vote up
def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('k')
        parser.add_argument('model')
        parser.add_argument('topic')
        parser.add_argument('id')

        args = parser.parse_args()
        k = int(args['k'])
        model_type = int(args['model'])
        topic = args['topic']
        index = 'default'
        if "id" in args:
            index = args['id']

        assert(k > 0)
        assert(model_type == 0 or model_type ==
               1 or model_type == 2 or model_type == -1)
        assert(len(topic) > 0)

        print model_type, k, topic.encode('utf8')
        times, poems, rhyme_words, table_html,lines = get_poem(
            k, model_type, topic, index, check=True)
        
        
        # log it
        if model_type >= 0:
            log_it(beams[model_type],topic,poems,times)

        phrases = []
        if len(lines) > 0:
            phrases = list(check_plagiarism(lines[0],ngram))
        phrase_str = "<br//>".join(phrases)

        poem_str = "<br//><br//>".join(poems)

        rhyme_words_html = "<br//>".join(rhyme_words)

        config_str = ""

        f = open(os.path.join(root_dir, 'py/config_es.txt'))
        for line in f:
            config_str += line.strip() + "<br//>"
        f.close()

        d = {}
        d['poem'] = poem_str
        d['config'] = config_str
        d['rhyme_words'] = rhyme_words_html
        d['rhyme_info'] = table_html
        d['pc'] = phrase_str
        json_str = json.dumps(d, ensure_ascii=False)
        r = make_response(json_str)

        return r


# add endpoint 
Example #22
Source File: client_es.py    From poem with MIT License 4 votes vote down vote up
def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('k')
        parser.add_argument('model')
        parser.add_argument('topic')
        parser.add_argument('id')

        args = parser.parse_args()
        k = int(args['k'])
        model_type = int(args['model'])
        topic = args['topic']
        index = 'default'
        if "id" in args:
            index = args['id']

        assert(k > 0)
        assert(model_type == 0 or model_type ==
               1 or model_type == 2 or model_type == -1)
        assert(len(topic) > 0)

        print model_type, k, topic
        times, poems, rhyme_words, table_html = get_poem(
            k, model_type, topic, index)

        # log it
        if model_type >= 0:
            log_it(beams[model_type],topic,poems,times)

        poem_str = "<br//><br//>".join(poems)

        rhyme_words_html = "<br//>".join(rhyme_words)

        config_str = ""

        f = open(os.path.join(root_dir, 'py/config_es.txt'))
        for line in f:
            config_str += line.strip() + "<br//>"
        f.close()

        d = {}
        d['poem'] = poem_str
        d['config'] = config_str
        d['rhyme_words'] = rhyme_words_html
        d['rhyme_info'] = table_html
        json_str = json.dumps(d, ensure_ascii=False)
        r = make_response(json_str)

        return r


################### Interactive #################### 
Example #23
Source File: rest_api.py    From dash with MIT License 4 votes vote down vote up
def put(self, row_index):
        """
        Edit the values of a row via an HTTP PUT request.

        Args:
          row_index: an integer index into the assembly store

        Returns:
          A tuple of http return code and a dictionary to be serialized to JSON
        """
        try:
            row = ASSEMBLY_STORE.GetRow(row_index)
        except AssemblyStoreError:
            abort(404)

        parser = reqparse.RequestParser()
        parser.add_argument('offset', type=int, default=row.offset, 
                            location='json')
        parser.add_argument('label', default=row.label, location='json')
        parser.add_argument('address', type=str, default=row.address,
                            location='json')
        parser.add_argument('opcode', default=row.opcode, location='json')
        parser.add_argument('mnemonic', default=row.mnemonic, location='json')
        parser.add_argument('comment', default=row.comment, location='json')
        #this defaults to true as adding any data makes a row in use
        parser.add_argument('in_use', default=True, location='json')
        args = parser.parse_args()
        row.offset = args.offset
        row.SetLabel(args.label)
        row.SetAddress(args.address)
        row.SetComment(args.comment)
        row.in_use = args.in_use

        ASSEMBLY_STORE.UpdateRow(row.index, row)

        if str(args.opcode).strip() != row.opcode:
            row.SetOpcode(args.opcode)
            ASSEMBLY_STORE.UpdateRow(row.index, row)

            if row.error:
                return row.ToDict()

            ASSEMBLER.Disassemble(row.index, ASSEMBLY_STORE)
        else:

            if args.mnemonic != row.mnemonic or args.mnemonic == '':
                if args.mnemonic == '':
                   # delete the row. 
                    ASSEMBLY_STORE.DeleteRow(row_index)
                    return row.ToDict()
                else:
                    new_mnemonics = args.mnemonic.split(';')
                    self.InsertMultipleRowsByMnemonic(row, new_mnemonics)
            else:
                ASSEMBLY_STORE.UpdateRow(row.index, row)
            ASSEMBLER.Assemble(ASSEMBLY_STORE)

        row = ASSEMBLY_STORE.GetRow(row.index)
        return row.ToDict()