当前位置: 首页>>代码示例>>Python>>正文


Python current_app.testing方法代码示例

本文整理汇总了Python中flask.current_app.testing方法的典型用法代码示例。如果您正苦于以下问题:Python current_app.testing方法的具体用法?Python current_app.testing怎么用?Python current_app.testing使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在flask.current_app的用法示例。


在下文中一共展示了current_app.testing方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __call__

# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import testing [as 别名]
def __call__(self, form, field):
        if current_app.testing:
            return True

        if request.json:
            response = request.json.get('g-recaptcha-response', '')
        else:
            response = request.form.get('g-recaptcha-response', '')
        remote_ip = request.remote_addr

        if not response:
            raise ValidationError(field.gettext(self.message))

        if not self._validate_recaptcha(response, remote_ip):
            field.recaptcha_error = 'incorrect-captcha-sol'
            raise ValidationError(field.gettext(self.message)) 
开发者ID:jpush,项目名称:jbox,代码行数:18,代码来源:validators.py

示例2: password_recovery

# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import testing [as 别名]
def password_recovery():
    ''' creates a password_recovery_hash and sends email to user (assumes login=email)'''
    post_data = request.get_json()
    if not post_data:
        raise InvalidPayload()
    email = post_data.get('email')
    if not email:
        raise InvalidPayload()

    # fetch the user data
    user = User.first_by(email=email)
    if user:
        token = user.encode_password_token()
        with session_scope(db.session):
            user.token_hash = bcrypt.generate_password_hash(token, current_app.config.get('BCRYPT_LOG_ROUNDS')).decode()
        if not current_app.testing:
            from project.api.common.utils.mails import send_password_recovery_email
            send_password_recovery_email(user, token.decode())  # send recovery email
        return {
            'status': 'success',
            'message': 'Successfully sent email with password recovery.',
        }
    else:
        raise NotFoundException(message='Login/email does not exist, please write a valid login/email') 
开发者ID:mtnbarreto,项目名称:flask-base-api,代码行数:26,代码来源:auth.py

示例3: email_verification

# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import testing [as 别名]
def email_verification(user_id):
    ''' creates a email_token_hash and sends email with token to user (assumes login=email), idempotent (could be use for resend)'''
    post_data = request.get_json()
    if not post_data:
        raise InvalidPayload()
    email = post_data.get('email')
    if not email:
        raise InvalidPayload()

    # fetch the user data
    user = User.first_by(email=email)
    if user:
        token = user.encode_email_token()
        with session_scope(db.session):
            user.email_token_hash = bcrypt.generate_password_hash(token, current_app.config.get('BCRYPT_LOG_ROUNDS')).decode()
        if not current_app.testing:
            from project.api.common.utils.mails import send_email_verification_email
            send_email_verification_email(user, token.decode())  # send recovery email
        return {
            'status': 'success',
            'message': 'Successfully sent email with email verification.',
        }
    else:
        raise NotFoundException(message='Login/email does not exist, please write a valid login/email') 
开发者ID:mtnbarreto,项目名称:flask-base-api,代码行数:26,代码来源:email_validation.py

示例4: redirect_to_ssl

# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import testing [as 别名]
def redirect_to_ssl(self):
        """
        Redirect incoming requests to HTTPS.
        """
        criteria = [
            request.is_secure,
            current_app.debug,
            current_app.testing,
            request.headers.get("X-Forwarded-Proto", "http") == "https",
        ]

        if (
            request.headers.get("User-Agent", "")
            .lower()
            .startswith(self.exclude_user_agents)
        ):
            return

        if not any(criteria):
            if request.url.startswith("http://"):
                url = request.url.replace("http://", "https://", 1)
                r = redirect(url, code=301)
                return r 
开发者ID:getsentry,项目名称:zeus,代码行数:25,代码来源:ssl.py

示例5: insecure_transport

# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import testing [as 别名]
def insecure_transport(self):
        """Creates a context to enable the oauthlib environment variable in
        order to debug with insecure transport.
        """
        origin = os.environ.get('OAUTHLIB_INSECURE_TRANSPORT')
        if current_app.debug or current_app.testing:
            try:
                os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
                yield
            finally:
                if origin:
                    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = origin
                else:
                    os.environ.pop('OAUTHLIB_INSECURE_TRANSPORT', None)
        else:
            if origin:
                warnings.warn(
                    'OAUTHLIB_INSECURE_TRANSPORT has been found in os.environ '
                    'but the app is not running in debug mode or testing mode.'
                    ' It may put you in danger of the Man-in-the-middle attack'
                    ' while using OAuth 2.', RuntimeWarning)
            yield 
开发者ID:gita,项目名称:BhagavadGita,代码行数:24,代码来源:application.py

示例6: save

# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import testing [as 别名]
def save(self, check_status=True, **kwargs):
        # While used in async method, app context is not available by default
        # and needs to be imported
        from flask import current_app as app
        from kqueen.server import create_app
        try:
            if not app.testing:
                app = create_app()
        except RuntimeError:
            app = create_app()

        with app.app_context():
            if check_status:
                self.state = self.engine_status(save=False)
            self.verbose_name = getattr(self.get_engine_cls(), 'verbose_name', self.engine)
            return super().save(**kwargs)


#
# AUTHENTICATION
# 
开发者ID:Mirantis,项目名称:kqueen,代码行数:23,代码来源:models.py

示例7: fetch_data

# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import testing [as 别名]
def fetch_data(gs, url):
  """Fetches a URL from Kubernetes (production) or reads it from a file (test).

  The file name is derived from the URL in the following way:
  The file name is 'testdata/' + last element of the URL + '.input.json'.

  For example, if the URL is 'https://host:port/api/v1beta3/path/to/resource',
  then the file name is 'testdata/resource.input.json'.

  The input is always JSON. It is converted to an internal representation
  by this routine.

  Args:
   gs: global state.
   url: the URL to fetch from Kubernetes in production.

  Returns:
    The contents of the URL (in production) or the contents of the file
    (in a test).

  Raises:
    IOError: if cannot open the test file.
    ValueError: if cannot convert the contents of the file to JSON.
    Other exceptions may be raised as the result of attempting to
    fetch the URL.
  """
  start_time = time.time()
  if app.testing:
    # Read the data from a file.
    url_elements = url.split('/')
    fname = 'testdata/' + url_elements[-1] + '.input.json'
    v = json.loads(open(fname, 'r').read())
    gs.add_elapsed(start_time, fname, time.time() - start_time)
    return v
  else:
    # Send the request to Kubernetes
    headers = get_kubernetes_headers()
    v = requests.get(url, headers=headers, verify=False).json()
    gs.add_elapsed(start_time, url, time.time() - start_time)
    return v 
开发者ID:google,项目名称:cluster-insight,代码行数:42,代码来源:kubernetes.py

示例8: create_users

# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import testing [as 别名]
def create_users():
    if current_app.testing:
        return
    db.create_all()
    user_datastore.create_role(
        name="admin",
        permissions={"admin-read", "admin-write", "user-read", "user-write"},
    )
    user_datastore.create_role(name="monitor", permissions={"admin-read", "user-read"})
    user_datastore.create_role(name="user", permissions={"user-read", "user-write"})
    user_datastore.create_role(name="reader", permissions={"user-read"})

    user_datastore.create_user(
        email="admin@me.com", password=hash_password("password"), roles=["admin"]
    )
    user_datastore.create_user(
        email="ops@me.com", password=hash_password("password"), roles=["monitor"]
    )
    real_user = user_datastore.create_user(
        email="user@me.com", password=hash_password("password"), roles=["user"]
    )
    user_datastore.create_user(
        email="reader@me.com", password=hash_password("password"), roles=["reader"]
    )

    # create initial blog
    blog = app.blog_cls(text="my first blog", user=real_user)
    db.session.add(blog)
    db.session.commit()
    print(f"First blog id {blog.id}")


# Views
# Note that we always add @auth_required so that if a client isn't logged in
# we will get a proper '401' and redirected to login page. 
开发者ID:Flask-Middleware,项目名称:flask-security,代码行数:37,代码来源:app.py

示例9: __init__

# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import testing [as 别名]
def __init__(self, *args, **kwargs):
        if current_app.testing:
            self.TIME_LIMIT = None
        super().__init__(*args, **kwargs) 
开发者ID:Flask-Middleware,项目名称:flask-security,代码行数:6,代码来源:forms.py

示例10: __init__

# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import testing [as 别名]
def __init__(self, data_name):
        if ChatAPI.bot_name != data_name:
            ChatAPI.bot_name = data_name
            ChatAPI.bot = web_bot.FrozenBot(frozen_model_dir=data_name,
                                            is_testing=current_app.testing)
            config = ChatAPI.bot.config
            _ = get_database_model('Chatbot',
                                   filter=ChatAPI.bot_name,
                                   dataset=config['dataset'],
                                   **config['model_params'])
            db.session.commit()
            # TODO: delete this after refactor rest of file.
            session['data_name'] = data_name 
开发者ID:mckinziebrandon,项目名称:DeepChatModels,代码行数:15,代码来源:views.py

示例11: register_user_cellphone

# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import testing [as 别名]
def register_user_cellphone(user_id: int):
    ''' generates cellphone_validation_code, idempotent (could be used for resend cellphone_validation_code)
        allows just 1 user per cellphone validation!
    '''
    post_data = request.get_json()
    if not post_data:
        raise InvalidPayload()
    cellphone_number = post_data.get('cellphone_number')
    cellphone_cc = post_data.get('cellphone_cc')
    if not cellphone_number or not cellphone_cc:
        raise InvalidPayload()
    user = User.get(user_id)
    if user.cellphone_validation_date and user.cellphone_number == cellphone_number and user.cellphone_cc == cellphone_cc:
        raise BusinessException(message='Registered. You have already registered this cellphone number.')

    cellphone_validation_code, cellphone_validation_code_expiration = User.generate_cellphone_validation_code()
    with session_scope(db.session) as session:
        user.cellphone_number = cellphone_number
        user.cellphone_cc = cellphone_cc
        user.cellphone_validation_code = cellphone_validation_code
        user.cellphone_validation_code_expiration = cellphone_validation_code_expiration
        user.cellphone_validation_date = None

    if not current_app.testing:
        from project.api.common.utils.twilio import send_cellphone_verification_code
        send_cellphone_verification_code(user, cellphone_validation_code)

    return {
        'status': 'success',
        'message': 'Successfully sent validation code.'
    } 
开发者ID:mtnbarreto,项目名称:flask-base-api,代码行数:33,代码来源:phone_validation.py

示例12: verify_cms_signers

# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import testing [as 别名]
def verify_cms_signers(f):
    """Verify the signers of a request containing a CMS/PKCS#7, DER encoded body.

    The certificate of each signer is placed on the global **g** variable as **g.signers** and the signed data is
    set as **g.signed_data**.

    In unit tests, this decorator is completely disabled by the presence of testing = True

    Raises:
          - TypeError if *Content-Type* header is not "application/pkcs7-signature"
          - SigningError if any signer on the CMS content is not valid.
    """
    @wraps(f)
    def decorator(*args, **kwargs):
        if current_app.testing:
            return f(*args, **kwargs)

        current_app.logger.debug('Verifying CMS Request Data for request to %s', request.url)

        if request.headers['Content-Type'] != "application/pkcs7-signature":
            raise TypeError("verify_cms_signers expects application/pkcs7-signature, got: {}".format(
                request.headers['Content-Type']))

        g.signers, g.signed_data = _verify_cms_signers(request.data)

        return f(*args, **kwargs)

    return decorator 
开发者ID:cmdmnt,项目名称:commandment,代码行数:30,代码来源:decorators.py

示例13: verify_mdm_signature

# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import testing [as 别名]
def verify_mdm_signature(f):
    """Verify the signature supplied by the client in the request using the ``Mdm-Signature`` header.

    If the authenticity of the message has been verified,
    then the signer is attached to the **g** object as **g.signer**.

    In unit tests, this decorator is completely disabled by the presence of app.testing = True.
    You can also disable enforcement in dev by setting the flask setting DEBUG to true.

    :reqheader Mdm-Signature: BASE64-encoded CMS Detached Signature of the message. (if `SignMessage` was true)
    """
    @wraps(f)
    def decorator(*args, **kwargs):
        if current_app.testing:
            return f(*args, **kwargs)

        if 'Mdm-Signature' not in request.headers:
            raise TypeError('Client did not supply an Mdm-Signature header but signature is required.')

        detached_signature = b64decode(request.headers['Mdm-Signature'])

        try:
            signers, signed_data = _verify_cms_signers(detached_signature, detached=True)
            g.signers = signers
            g.signed_data = signed_data
        except InvalidSignature as e:
            current_app.logger.warn("Invalid Signature in Mdm-Signature header")
            if not current_app.config.get('DEBUG', False):
                return abort(403)

        return f(*args, **kwargs)

    return decorator 
开发者ID:cmdmnt,项目名称:commandment,代码行数:35,代码来源:decorators.py

示例14: _send_mail_async

# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import testing [as 别名]
def _send_mail_async(subject_or_message=None, to=None, template=None, **kwargs):
    subject_or_message = subject_or_message or kwargs.pop('subject')
    if current_app and current_app.testing:
        return async_mail_task.apply([subject_or_message, to, template], kwargs)
    return async_mail_task.delay(subject_or_message, to, template, **kwargs) 
开发者ID:briancappello,项目名称:flask-unchained,代码行数:7,代码来源:tasks.py

示例15: __init__

# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import testing [as 别名]
def __init__(self, *args, **kwargs):
        if app.testing:
            self.TIME_LIMIT = None
        super().__init__(*args, **kwargs) 
开发者ID:briancappello,项目名称:flask-unchained,代码行数:6,代码来源:forms.py


注:本文中的flask.current_app.testing方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。