コード例 #1
0
ファイル: request_helper.py プロジェクト: Kitingu/restplus
class RequestParser:
    parser = reqparse.RequestParser()
    parser.add_argument('username',
                        type=str,
                        required=True,
                        location='json',
                        help="Please enter a valid starting point")
    parser.add_argument(
        'email',
        type=inputs.regex('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'),
        action='append',
        required=True,
        location='json',
        help="please enter a valid email address")
    parser.add_argument('number_of_seats',
                        type=int,
                        required=True,
                        location='json',
                        help="This field cannot be blank")
    parser.add_argument('pick_up_point',
                        type=str,
                        required=True,
                        location='json',
                        help="Please enter a valid starting point")
    parser.add_argument('destination',
                        type=str,
                        required=True,
                        location='json',
                        help="This field cannot be blank")
コード例 #2
0
def get_legacy_params():
    legacy_params = reqparse.RequestParser()

    legacy_params.add_argument('s', type=str, dest='source', required=True)
    legacy_params.add_argument('t', type=str, dest='target', required=True)
    legacy_params.add_argument(
        'n',
        type=inputs.int_range(low=0,
                              high=configuration.get_config_int(
                                  'api', 'count_max')),
        dest='count',
        required=False,
        default=configuration.get_config_int('api', 'count_default'))
    legacy_params.add_argument('article',
                               type=inputs.regex(r'^([^|]+(\|[^|]+)*)?$'),
                               dest='seed',
                               required=False)
    legacy_params.add_argument('pageviews',
                               type=inputs.boolean,
                               dest='include_pageviews',
                               required=False,
                               default=True)
    legacy_params.add_argument('search',
                               type=str,
                               required=False,
                               default='morelike',
                               choices=['morelike', 'wiki'])

    return legacy_params
コード例 #3
0
def get_v1_params():
    v1_params = reqparse.RequestParser()

    v1_params.add_argument('source', type=str, required=True)
    v1_params.add_argument('target', type=str, required=True)
    v1_params.add_argument(
        'count',
        type=inputs.int_range(low=0,
                              high=configuration.get_config_int(
                                  'api', 'count_max')),
        required=False,
        default=configuration.get_config_int('api', 'count_default'))
    v1_params.add_argument('seed',
                           type=inputs.regex(r'^([^|]+(\|[^|]+)*)?$'),
                           required=False)
    v1_params.add_argument('include_pageviews',
                           type=inputs.boolean,
                           required=False,
                           default=True)
    v1_params.add_argument(
        'search',
        type=str,
        required=False,
        default='morelike',
        choices=['morelike', 'wiki', 'related_articles', 'category'])
    v1_params.add_argument('rank_method',
                           type=str,
                           required=False,
                           default='default',
                           choices=['default', 'sitelinks'])
    v1_params.add_argument('campaign', type=str, required=False, default='')

    return v1_params
コード例 #4
0
ファイル: views.py プロジェクト: akahard2dj/Blackberry
class GenerateAuthKeyApi(Resource):
    parser = api.parser()
    parser.add_argument('email',
                        type=inputs.regex("[^@]+@[^@]+\.[^@]+"),
                        required=True)

    @api.expect(parser)
    def get(self):
        query_args = self.parser.parse_args()
        email = query_args['email']

        if cache.get('auth_key:{}'.format(email)):
            return jsonify({'msg': 'already email is sent'})

        else:
            auth_key_status = dict()
            # TODO : auth code is needed to be random function
            auth_key_status['code'] = random_number()
            auth_key_status['status'] = 'SENT'
            # TODO: timeout variable should contain in app config
            cache.set('auth_key:{}'.format(email),
                      auth_key_status,
                      timeout=600)
            print('## TEMP LOG: code - {}'.format(auth_key_status['code']),
                  type(auth_key_status['code']))
            return jsonify({'msg': 'auth key is generated'})
コード例 #5
0
    def post(self):
        parser = RequestParser(bundle_errors=True)
        parser.add_argument('full_name', type=str, required=True, location='json')
        parser.add_argument('password', type=inputs.regex('[A-Za-z0-9@#$%^&+=]{8,}'), required=True, location='json',
                            help='Password must have a minimum of eight characters.')
        parser.add_argument('email_address', type=inputs.email(), required=True, location='json')
        args = parser.parse_args(strict=True)

        email = User.query.filter(User.email == args.email_address).first()
        if email:
            return {'message': 'Email address already exist'}, 400

        try:
            user = User()
            user.full_name = args.full_name
            user.email = args.email_address
            user.username = f'{args.full_name.replace(" ", "").lower()}{random.randint(1, 9999)}'
            user.password = generate_password_hash(args.password).decode()
            user.role = 'CLIENT'
            token = user.create_token()
            user.save()
            text = f"""Your Account has been created.
            Confirm Your Account By Clicking on this link.
            Link : <a href="{url_for('api.auth_confirm_account', token=token, _external=True)}"></a>
            """
            send_mail_rq.queue(user.email, text, 'Register')
            return {'message': 'Your account has been created, Check your email to confirm your account'}, 200
        except Exception as e:
            return jsonify(message=f'Unable to create account ::{e}'), 500
コード例 #6
0
    def test_valid_input(self):
        values = (
            '123',
            '1234567890',
            '00000',
        )

        num_only = inputs.regex(r'^[0-9]+$')

        self.assert_values(num_only, zip(values, values))
コード例 #7
0
ファイル: test_inputs.py プロジェクト: Dlotan/flask-restplus
    def test_valid_input(self):
        values = (
            '123',
            '1234567890',
            '00000',
        )

        num_only = inputs.regex(r'^[0-9]+$')

        self.assert_values(num_only, zip(values, values))
コード例 #8
0
def user_validation(create=True):
    parser = reqparse.RequestParser(trim=True, bundle_errors=True)
    parser.add_argument('user_name',
                        type=inputs.regex(r'^[0-9A-Za-z-]{3,50}$'),
                        required=create,
                        help='User alias unique name',
                        case_sensitive=False)
    parser.add_argument('first_name',
                        type=inputs.regex(r'^[A-Za-z]{3,100}$'),
                        required=create,
                        help='First name',
                        case_sensitive=False)
    parser.add_argument('last_name',
                        type=inputs.regex(r'^[A-Za-z]{3,100}$'),
                        required=create,
                        help='Last name',
                        case_sensitive=False)
    parser.add_argument('gender',
                        type=str,
                        required=create,
                        choices=('male', 'Male', 'MALE'
                                 'female', 'Female', 'FEMALE'),
                        help='Gender',
                        case_sensitive=False)
    parser.add_argument('dob',
                        type=inputs.date,
                        required=create,
                        help='Date of Birth')
    parser.add_argument('phone_no',
                        type=inputs.regex(r'^\+[0-9]{10,15}$'),
                        required=create,
                        help='Phone number')
    parser.add_argument('email',
                        type=inputs.email(check=True),
                        required=create,
                        help='Email',
                        case_sensitive=False)
    parser.add_argument(
        'password',
        type=inputs.regex(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,15}$'),
        required=create,
        help='Password')
    return parser.parse_args(strict=True)
コード例 #9
0
    def test_bad_input(self):
        values = (
            'abc',
            '123abc',
            'abc123',
            '',
        )

        num_only = inputs.regex(r'^[0-9]+$')

        self.assert_values_raises(num_only, values)
コード例 #10
0
ファイル: views.py プロジェクト: akahard2dj/Blackberry
class ConfirmAuthKeyApi(Resource):
    parser = api.parser()
    parser.add_argument('email',
                        type=inputs.regex("[^@]+@[^@]+\.[^@]+"),
                        required=True)
    parser.add_argument('authcode', type=str, required=True)

    @api.expect(parser)
    def get(self):
        query_args = self.parser.parse_args()
        email = query_args['email']
        authcode = query_args['authcode']

        res_from_cache = cache.get('auth_key:{}'.format(email))
        if res_from_cache is None:
            raise CommonException('Timed out : re-authentication is needed')
        else:
            auth_code_from_cache = res_from_cache['code']
            if authcode == auth_code_from_cache:
                cache.delete('auth_key:{}'.format(email))
                from_db_user = User.query.filter(User.email == email).first()
                if from_db_user is None:
                    res_from_cache['status'] = 'CONFIRM'
                    res_from_cache['usertype'] = 'NEW'
                    cache.set('auth_key:{}'.format(email),
                              res_from_cache,
                              timeout=1800)
                    domain = email.split('@')[-1]
                    university_from_db = University.query.filter(
                        domain == domain).first()

                    new_user = User()
                    new_user.email = email
                    new_user.password = '******'
                    # TODO: username uniqueness check is needed
                    new_user.username = random_digit_with_number()
                    new_user.university = university_from_db.id

                    db.session.add(new_user)
                    try:
                        db.session.commit()
                    except Exception as e:
                        return bad_request('internal error')
                else:
                    res_from_cache['status'] = 'CONFIRM'
                    res_from_cache['usertype'] = 'OLD'
                    cache.set('auth_key:{}'.format(email),
                              res_from_cache,
                              timeout=1800)

                return ResponseWrapper.ok()
            else:
                return ResponseWrapper.ok('invalid auth_code',
                                          data={'errors': 'auth code check'})
コード例 #11
0
ファイル: test_inputs.py プロジェクト: Dlotan/flask-restplus
    def test_bad_input(self):
        values = (
            'abc',
            '123abc',
            'abc123',
            '',
        )

        num_only = inputs.regex(r'^[0-9]+$')

        self.assert_values_raises(num_only, values)
コード例 #12
0
def role_validation(create=True):
    parser = reqparse.RequestParser(trim=True, bundle_errors=True)
    parser.add_argument('role',
                        type=inputs.regex(r'^[0-9A-Za-z_]{3,50}$'),
                        required=create,
                        help='role name',
                        case_sensitive=False)
    parser.add_argument('code',
                        type=inputs.positive,
                        required=create,
                        help='role code')
    return parser.parse_args(strict=True)
コード例 #13
0
    def put(self):
        xparser = RequestParser(bundle_errors=True)
        xparser.add_argument('token',
                             type=str,
                             required=True,
                             location='args',
                             help='Token is missing')
        xparser.add_argument(
            'new_pwd',
            type=inputs.regex('[A-Za-z0-9@#$%^&+=]{8,}'),
            required=True,
            location='json',
            help='Password must have a minimum of eight characters.')
        xparser.add_argument(
            'confirm_pwd',
            type=inputs.regex('[A-Za-z0-9@#$%^&+=]{8,}'),
            required=True,
            location='json',
            help='Password must have a minimum of eight characters.')
        args = xparser.parse_args(strict=True)

        token = User.authenticate_token(args.token)
        if not token:
            return {
                'message': 'Token is invalid or has expired',
                "other": 'Please regenerate token'
            }
        try:
            if not safe_str_cmp(args.confirm_pwd, args.new_pwd):
                return {"message": 'passwords dont match'}
            user = User.query.filter(
                User.uuid == UUID(token.get('id'))).first()
            user.password = generate_password_hash(args.new_pwd).decode()
            user.save()
            return {'message': 'Your password has been updated successfully'}
        except Exception:
            return {
                'message': 'Something went wrong',
                'other': 'unable to update password'
            }
コード例 #14
0
def get_v1_articles_params():
    v1_articles_params = reqparse.RequestParser()

    v1_articles_params.add_argument('source', type=str, required=True)
    v1_articles_params.add_argument(
        'count',
        type=inputs.int_range(low=0,
                              high=configuration.get_config_int(
                                  'api', 'count_max')),
        required=False,
        default=configuration.get_config_int('api', 'count_default'))
    v1_articles_params.add_argument('seed',
                                    type=inputs.regex(r'^[^|]+(\|[^|]+)*$'),
                                    required=True)

    return v1_articles_params
コード例 #15
0
class Register(Resource):
    """class contain POST method"""
    parser = reqparse.RequestParser()
    parser.add_argument('username',
                        required=True,
                        help="No username provided",
                        location=['json'])

    parser.add_argument(
        'email',
        required=True,
        help="No email provided",
        location=['json'],
        type=inputs.regex(
            r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"))

    parser.add_argument('password',
                        required=True,
                        help="No password provided",
                        location=['json'])

    parser.add_argument('is_driver', required=False, location=['json'])

    @api.expect(model_register)
    def post(self):
        """Register user"""
        args = self.parser.parse_args(strict=True)

        username = args['username']
        email = args['email']
        password = args['password']
        driver = args['is_driver']

        if username == "" or email == "" or password == "" or driver == "":
            return {"msg": "Field cannot be empty"}

        if driver == "True":
            driver_res = user.add_driver(email=email,
                                         username=username,
                                         password=password)
            return driver_res, 201

        user_res = user.add_users(email=email,
                                  username=username,
                                  password=password)
        return user_res, 201
コード例 #16
0
ファイル: views.py プロジェクト: akahard2dj/Blackberry
class EmailCheckApi(Resource):
    parser = api.parser()
    parser.add_argument('email',
                        type=inputs.regex("[^@]+@[^@]+\.[^@]+"),
                        required=True)
    parser.add_argument('uuid', type=str)

    @api.expect(parser)
    def get(self):
        # TODO: uuid argument is needed
        query_args = self.parser.parse_args()
        email = query_args['email']

        # when the information of user is not changed(email, uuid), go to app first
        from_db_user = User.query.filter(User.email == email).first()
        if from_db_user is None:
            # University Checking
            domain = email.split('@')[-1]
            university_from_db = University.query.filter(
                University.domain == domain).first()
            if university_from_db is None:
                return ResponseWrapper.ok(
                    'Requested University is Not Service',
                    data={'errors': '{} is not serviced'.format(domain)})
            else:
                return ResponseWrapper.ok('Email Check is completed')
        else:
            # already registered user
            # email & password check -> tracing an alteration of phone or re-installed app
            is_alteration = from_db_user.verify_password('test1234')
            if not is_alteration:
                return ResponseWrapper.ok('device is changed')
            from_db_user.status = "PENDING"
            try:
                db.session.commit()
            except Exception as e:
                CommonException('Server is not response')

            return ResponseWrapper.ok('already registered user')
コード例 #17
0
def test_regex_input_bulk_zip():
    print('============================',
          sys._getframe().f_code.co_name, '============================ ')

    bulk_regex = r'(\d{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])|all)$'
    input_regex = inputs.regex(bulk_regex)

    input = 'all'
    val = input_regex(input)

    assert val == input

    input = '2019-04-01'
    val = input_regex(input)

    assert val == input

    input = '2019-04-42'

    try:
        val = input_regex(input)
    except ValueError as ve:
        assert ve is not None
コード例 #18
0
class UserParser:
    parser = reqparse.RequestParser()
    parser.add_argument('username',
                        type=str,
                        required=True,
                        location='json',
                        help="Please enter a valid starting point")
    parser.add_argument('password',
                        type=str,
                        required=True,
                        location='json',
                        help="This field cannot be blank")
    parser.add_argument('confirm_password',
                        type=str,
                        required=True,
                        location='json',
                        help="This field cannot be blank")
    parser.add_argument(
        'email',
        type=inputs.regex('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'),
        required=True,
        location='json',
        help="please enter a valid date")
コード例 #19
0
class Login(Resource):
    """class contain post method"""
    req_data = reqparse.RequestParser()
    req_data.add_argument(
        'email',
        required=True,
        help='username required',
        location=['json'],
        type=inputs.regex(
            r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"))

    req_data.add_argument('password',
                          required=True,
                          help='password required',
                          location=['json'])

    @api.expect(model_login)
    def post(self):
        """Login user"""
        args = self.req_data.parse_args(strict=True)
        email = args['email']
        password = args['password']
        res = user.login(email=email, password=password)
        return res
コード例 #20
0
    default='Collections',
    title='Collections Dataset',
    description='COMP9321 Assignment-2\n\n'
    'NOTE:\n'
    '1.) "collection_id" has been assigned the same value as "indicator_id".\n'
    '2.) Countries with "countryiso3code" set to NULL have also been considered.\n'
    '3.) For Q6, countries with "value" set to NULL are excluded from sorting when parameter "q" is specified.\n'
    '4.) The database name is "data.db" and table name is "collections".')

collection_model = api.model(
    'collections',
    {'indicator_id': fields.String(required=True, example='NY.GDP.MKTP.CD')})

parser = api.parser()
parser.add_argument('q',
                    type=inputs.regex('^(top|bottom)([1-9][0-9]?|100)$'),
                    help='Format: top/bottom<1-100>')

db_name = 'data.db'


def create_db(db_file):
    try:
        conn = sqlite3.connect(db_file)
        c = conn.cursor()

        c.execute('CREATE TABLE IF NOT EXISTS collections(  '
                  '     collection_id       TEXT,           '
                  '     indicator           TEXT,           '
                  '     indicator_value     TEXT,           '
                  '     creation_time       TEXT,           '
コード例 #21
0
                                     help='Reviewed problem ID',
                                     location='json',
                                     error='Problem ID is required')
# @TODO validate this at request time - for now see problem_feedback.py
feedback_submission_req.add_argument('feedback',
                                     required=True,
                                     type=object_type,
                                     help='Problem feedback',
                                     location='json',
                                     error='Feedback object required')

# New user request
user_req = reqparse.RequestParser()
user_req.add_argument('email',
                      required=True,
                      type=inputs.regex(r".+@.+\..{2,}"),
                      location='json',
                      help='Email address',
                      error='Email address is not valid')
user_req.add_argument('firstname',
                      required=False,
                      type=length_restricted(1, 50, str),
                      location='json',
                      help='Given name',
                      default='',
                      error='First name is not valid (50 characters max)')
user_req.add_argument('lastname',
                      required=False,
                      type=length_restricted(1, 50, str),
                      location='json',
                      help='Family name',
コード例 #22
0
from flask_restplus import reqparse, fields, inputs
from data import create_account_handler, resend_Mail, update_account_handler, otp_generator, log_user_in, search_user, load_Chat
from flask_json import json_response
from flask import request, render_template, make_response, session

#----------------------------------------------------------------------------------
"""
	This handles creation of account, it also makes use of it's parser and marshal to ensure  
	proper passing of valid data
"""
#----------------------------------------------------------------------------------

post_params = api.parser()  # parsing arguments
post_params.add_argument(
    'usr',
    type=inputs.regex("(\S+)([A-z]+)([0-9]*)([-_]*)"),
    help='Username should not be left blank and must be a string',
    required=True)
post_params.add_argument(
    'name',
    type=inputs.regex("([A-z]+) ([A-z]+)"),
    help='fullname should not be left blank and must be a string',
    required=True)
post_params.add_argument(
    'email',
    type=inputs.regex(
        "([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+"),
    help='email should not be left blank or is invalid')
post_params.add_argument('phn',
                         type=inputs.regex("([+]+)([0-9]+)"),
                         help='phone number should not be left blank',
コード例 #23
0
from sokannonser import settings

api = Api(version='1.4.0',
          title='Download job ads',
          description='An API for retrieving job ads',
          default='bulkloader',
          default_label="An API for retrieving job ads.")

ns_bulk = Namespace('Bulk loader',
                    description='Endpoint for downloading ads in '
                    'stream.')

api.add_namespace(ns_bulk, '/')

bulk_zip_query = reqparse.RequestParser()
bulk_zip_query.add_argument(settings.APIKEY, location='headers', required=True)
# r for raw, PEP8
bulk_regex = r'^(\d{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])|all)$'

bulk_zip_query.add_argument(settings.DATE,
                            type=inputs.regex(bulk_regex),
                            required=True)

bulk_stream_query = reqparse.RequestParser()
bulk_stream_query.add_argument(settings.APIKEY,
                               location='headers',
                               required=True)
bulk_stream_query.add_argument(settings.DATE,
                               type=inputs.datetime_from_iso8601,
                               required=True)
コード例 #24
0
    def put(self, option):
        profile_parser = RequestParser(trim=True, bundle_errors=True)
        if option == 'general':
            profile_parser.add_argument('username',
                                        required=True,
                                        type=string,
                                        location='json')
            profile_parser.add_argument('full_name',
                                        required=True,
                                        type=string,
                                        location='json')
            profile_parser.add_argument('gender',
                                        required=True,
                                        type=str,
                                        choices=['Male', 'Female', 'Others'],
                                        help='Gender is required',
                                        location='json')
            args = profile_parser.parse_args(strict=True)
            if User.query.filter(User.username == args.username,
                                 User.id != current_user.id).first():
                return {
                    'message':
                    'Username already exist, please use different one'
                }, 400
            current_user.full_name = args.full_name
            current_user.gender = args.gender
            return current_user.save(**args)

        if option == 'pwd':
            profile_parser.add_argument('old_pwd',
                                        required=True,
                                        type=str,
                                        location='json')
            profile_parser.add_argument(
                'new_pwd',
                type=inputs.regex('[A-Za-z0-9@#$%^&+=]{8,}'),
                required=True,
                location='json',
                help='Password must have a minimum of eight characters.')
            profile_parser.add_argument(
                'confirm_pwd',
                type=inputs.regex('[A-Za-z0-9@#$%^&+=]{8,}'),
                required=True,
                location='json',
                help='Password must have a minimum of eight characters.')
            args = profile_parser.parse_args(strict=True)
            if not bcrypt.check_password_hash(current_user.password,
                                              args.old_pwd):
                return {
                    'message': 'Old password doesnt match current password'
                }, 400
            if not safe_str_cmp(args.confirm_pwd, args.new_pwd):
                return {"message": 'passwords dont match'}
            current_user.password = bcrypt.generate_password_hash(
                args.new_pwd).decode()
            current_user.save()
            send_mail_rq.queue('Your password was changed!',
                               [current_user.email], 'Password Changed')
            return {'message': 'Your password has been updated successfully'}
        if option == 'email':
            profile_parser.add_argument('pwd',
                                        required=True,
                                        type=str,
                                        location='json')
            profile_parser.add_argument('old_email',
                                        required=True,
                                        type=inputs.email(),
                                        help='Email address is required',
                                        location='json')
            profile_parser.add_argument('new_email',
                                        required=True,
                                        type=inputs.email(),
                                        help='Email address is required',
                                        location='json')
            args = profile_parser.parse_args(strict=True)
            if not bcrypt.check_password_hash(current_user.password, args.pwd):
                return abort(401)
            token = current_user.create_token(
                payload={'email': args.new_email})
            url = url_for('api.auth_change_email', token=token, _external=True)
            send_mail_rq.queue(
                CHANGE_EMAIL.format(name=current_user.full_name, url=url),
                [args.new_email], 'Change Email')
            return {'message': 'Email has been sent'}
        if option == 'img':
            profile_parser.add_argument(
                'files',
                required=True,
                location='files',
                type=werkzeug.datastructures.FileStorage)
            args = profile_parser.parse_args(strict=True)
            file = img_upload(args.file)
            if file.get('message'):
                return file, 400
            current_user.img = file.get('filename')
            file.get('upload').save(file.get('full_path'))
            return current_user.save(filename=current_user.img), 201
        return abort(404)
コード例 #25
0
from api_version.utils import validate_
from data import create_account_handler, resend_mail, update_account_handler, otp_generator, log_user_in, search_user, load_Chat, transfer_funds_with_email, transfer_funds_with_number, virtual_wallet_handler
from flask_json import json_response
from flask import request, render_template, make_response, session

#----------------------------------------------------------------------------------
"""
	This handles creation of account, it also makes use of it's parser and marshal to ensure  
	proper passing of valid data
"""
#----------------------------------------------------------------------------------

post_params = api.parser()  # parsing arguments
post_params.add_argument(
    'usr',
    type=inputs.regex("(\S+)([A-z]+)([0-9]*)([-_]*)"),
    help='Username should not be left blank and must be a string',
    required=True)
post_params.add_argument(
    'name',
    type=inputs.regex("([A-z]+) ([A-z]+)"),
    help='fullname should not be left blank and must be a string',
    required=True)
post_params.add_argument(
    'email',
    type=inputs.regex(
        "([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+"),
    help='email should not be left blank or is invalid')
post_params.add_argument('phn',
                         type=inputs.regex("([+]+)([0-9]+)"),
                         help='phone number should not be left blank',
コード例 #26
0
ファイル: test_inputs.py プロジェクト: Dlotan/flask-restplus
 def test_schema(self):
     self.assert_schema(inputs.regex(r'^[0-9]+$'), {'type': 'string', 'pattern': '^[0-9]+$'})
コード例 #27
0
ファイル: game_api.py プロジェクト: slwolfram/p1ePoker-server
from flask import Flask, Blueprint, jsonify
from flask_restplus import (Api, Resource, fields, Namespace, inputs)
from datetime import datetime
from .decorators.token_required import token_required
from .decorators.catch_api_exceptions import catch_api_exceptions
from ..models.game import Game
from ..models.game_state import GameState
from ..models.table_state import TableState

api = Namespace('games', description='Game related operations')

game_parser = api.parser()
game_parser.add_argument('Name',
                         type=inputs.regex('^[a-zA-Z][a-zA-Z0-9@\.]{1,16}$'),
                         required=True,
                         location='form',
                         help='The table name.')
game_parser.add_argument('NumSeats',
                         type=int,
                         required=True,
                         location='form',
                         help='Max number of players that can be seated.')
game_parser.add_argument(
    'TurnTime',
    type=int,
    location='form',
    help="Max seconds a player can take to move. By default, players"
    " have infinite time.")
game_parser.add_argument(
    'Blinds',
    type=inputs.regex('^[0-9]+,[0-9]+(\|[0-9]+,[0-9]+)*$'),
コード例 #28
0
 def test_bad_pattern(self):
     with pytest.raises(re.error):
         inputs.regex('[')
コード例 #29
0
ファイル: queries.py プロジェクト: ixuz/sokannonser-api
load_ad_query = reqparse.RequestParser()
load_ad_query.add_argument(settings.APIKEY, location='headers', required=True)

annons_complete_query = reqparse.RequestParser()
annons_complete_query.add_argument(settings.APIKEY,
                                   location='headers',
                                   required=True)
annons_complete_query.add_argument(
    settings.PUBLISHED_BEFORE,
    type=lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S'))
# annons_complete_query.add_argument(settings.PUBLISHED_AFTER,
#                                    type=lambda x: datetime.strptime(x,
#                                                                     '%Y-%m-%dT%H:%M:%S'))
datetime_or_minutes_regex = r'^(\d\d\d\d-(0?[1-9]|1[0-2])-(0?[1-9]|[12][0-9]|3[01])T(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]))|(\d+)$'
annons_complete_query.add_argument(
    settings.PUBLISHED_AFTER, type=inputs.regex(datetime_or_minutes_regex))
annons_complete_query.add_argument(taxonomy.OCCUPATION, action='append')
annons_complete_query.add_argument(taxonomy.GROUP, action='append')
annons_complete_query.add_argument(taxonomy.FIELD, action='append')
annons_complete_query.add_argument(taxonomy.SKILL, action='append')
annons_complete_query.add_argument(taxonomy.LANGUAGE, action='append')
annons_complete_query.add_argument(taxonomy.WORKTIME_EXTENT, action='append')
annons_complete_query.add_argument(settings.PARTTIME_MIN, type=float)
annons_complete_query.add_argument(settings.PARTTIME_MAX, type=float)
annons_complete_query.add_argument(taxonomy.DRIVING_LICENCE_REQUIRED,
                                   type=inputs.boolean)
annons_complete_query.add_argument(taxonomy.DRIVING_LICENCE, action='append')
annons_complete_query.add_argument(taxonomy.EMPLOYMENT_TYPE, action='append')
annons_complete_query.add_argument(settings.EXPERIENCE_REQUIRED,
                                   choices=['true', 'false'])
annons_complete_query.add_argument(taxonomy.MUNICIPALITY, action='append')
コード例 #30
0
feedback_submission_req.add_argument(
    'pid', required=True, type=str, help='Reviewed problem ID',
    location='json',
    error='Problem ID is required'
)
# @TODO validate this at request time - for now see problem_feedback.py
feedback_submission_req.add_argument(
    'feedback', required=True, type=object_type, help='Problem feedback',
    location='json',
    error='Feedback object required'
)

# New user request
user_req = reqparse.RequestParser()
user_req.add_argument(
    'email', required=True, type=inputs.regex(r".+@.+\..{2,}"),
    location='json', help='Email address',
    error='Email address is not valid'
)
user_req.add_argument(
    'firstname', required=False, type=length_restricted(1, 50, str),
    location='json', help='Given name', default='',
    error='First name is not valid (50 characters max)'
)
user_req.add_argument(
    'lastname', required=False, type=length_restricted(1, 50, str),
    location='json', help='Family name', default='',
    error='Last name is not valid (50 characters max)'
)
user_req.add_argument(
    'username', required=True, type=length_restricted(3, 20, str),
コード例 #31
0
app.wsgi_app = ProxyFix(app.wsgi_app)
api = Api(app,
          version='1.0',
          title='covid API',
          description='API pour générer une attestation de déplacement')

regex_sexe = r'^(H|F)$'
regex_string = r'^[A-Za-zàáâäçèéêëìíîïñòóôöùúûü\s-]{2,50}$'
regex_naissance = r'^([0-2][0-9]|(3)[0-1])(\/)(((0)[0-9])|((1)[0-2]))(\/)\d{4}$'
regex_adresse = r'^[A-Za-zàáâäçèéêëìíîïñòóôöùúûü0-9\s]{2,50}$'
regex_codepostal = r'\d{5}'
regex_motif = r'(convocation|missions|handicap|sante|enfants|famille|sport_animaux|travail|achats)'

parser = reqparse.RequestParser()
parser.add_argument('sexe',
                    type=inputs.regex(regex_sexe),
                    required=True,
                    help='Sexe (H/F)')
parser.add_argument('prenom',
                    type=inputs.regex(regex_string),
                    required=True,
                    help='Prénom')
parser.add_argument('nom',
                    type=inputs.regex(regex_string),
                    required=True,
                    help='Nom de famille')
parser.add_argument('naissance',
                    type=inputs.regex(regex_naissance),
                    required=True,
                    help='Date de naissance (JJ/MM/AAAA)')
parser.add_argument('lieu',
コード例 #32
0
ファイル: app.py プロジェクト: michigg/roofis2_api
from config import BUILDING_KEY_MAP, API_V1_ROOT, UNI_INFO_API
from flask_cors import CORS

app = Flask(__name__)
api = Api(app=app,
          doc='/docs',
          version='1.0',
          title='RooFiS2 API',
          description='Room Finder Service 2 API')
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

roofis_parser = reqparse.RequestParser()
roofis_parser.add_argument(
    'start_date',
    required=True,
    type=inputs.regex('^([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))$'),
    help='date from which free rooms are to be searched for')
roofis_parser.add_argument(
    'start_time',
    required=True,
    type=inputs.regex('^(?:[01]\d|2[0123]):(?:[012345]\d)$'),
    help='time from which free rooms are to be searched for')
roofis_parser.add_argument('min_size',
                           type=int,
                           help='filter room by minumum room size')
roofis_parser.add_argument('location',
                           type=str,
                           help='filter rooms by location')
roofis_parser.add_argument('building_key',
                           type=str,
                           help='filter rooms by building key')
コード例 #33
0
 def test_valid_input(self, value):
     num_only = inputs.regex(r'^[0-9]+$')
     assert num_only(value) == value
コード例 #34
0
 def test_bad_input(self, value):
     num_only = inputs.regex(r'^[0-9]+$')
     with pytest.raises(ValueError):
         num_only(value)
コード例 #35
0
from flask_restplus import Api, Namespace, reqparse, inputs
from sokannonser import settings

api = Api(version='1.0', title='Download job ads',
          description='An API for retrieving job ads',
          default='bulkloader',
          default_label="An API for retrieving job ads.")

ns_bulk = Namespace('Bulk loader', description='Endpoint for downloading all ads in '
                    'zip-file formt.')

api.add_namespace(ns_bulk, '/bulk')

bulk_query = reqparse.RequestParser()
bulk_query.add_argument(settings.APIKEY, location='headers', required=True)
bulk_query.add_argument(settings.DATE,
                        type=inputs.regex('^\\d{4}-\\d{2}-\\d{2}|all|yesterday$'),
                        required=True)
コード例 #36
0
 def test_schema(self):
     assert inputs.regex(r'^[0-9]+$').__schema__ == {'type': 'string', 'pattern': '^[0-9]+$'}
コード例 #37
0
ファイル: openData.py プロジェクト: jeorme/quanTools
from flask import request, jsonify
from flask_restplus import Namespace, Resource, fields, reqparse, inputs
import requests

from requests.auth import HTTPBasicAuth

api = Namespace('openData', 'wrapper of end point without autorization')
parserSearch = reqparse.RequestParser()
parserSearch.add_argument('address', type=inputs.regex(""),
                          help="address of the appartment",
                          default="42, West Mead", required=True)
parserSearch.add_argument('postcode', type=inputs.regex(""),
                          help="postcode of the appartment",
                          default="HA4 0TL", required=True)

parserLmkey = reqparse.RequestParser()
parserLmkey.add_argument('lmkey', type=inputs.natural,
                          help="lmkey of the appartment",
                          default="1827209002922020092007053442338480", required=True)

@api.route('/api/v1/domestic/search')
class search(Resource):
    @api.response(200,"Success")
    @api.expect(parserSearch)
    def get(self):
        """
        :return: the search of an appartment based on address and postcode
        """

        url = "https://epc.opendatacommunities.org/api/v1/domestic/search"
        user = "******"