Python flask.current_app.test_request_context() Examples

The following are 9 code examples of flask.current_app.test_request_context(). 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.current_app , or try the search function .
Example #1
Source File: commands.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def create():
    '''Create a new user'''
    data = {
        'first_name': click.prompt('First name'),
        'last_name': click.prompt('Last name'),
        'email': click.prompt('Email'),
        'password': click.prompt('Password', hide_input=True),
        'password_confirm': click.prompt('Confirm Password', hide_input=True),
    }
    # Until https://github.com/mattupstate/flask-security/issues/672 is fixed
    with current_app.test_request_context():
        form = RegisterForm(MultiDict(data), meta={'csrf': False})
    if form.validate():
        data['password'] = encrypt_password(data['password'])
        del data['password_confirm']
        data['confirmed_at'] = datetime.utcnow()
        user = datastore.create_user(**data)
        success('User(id={u.id} email={u.email}) created'.format(u=user))
        return user
    errors = '\n'.join('\n'.join(e) for e in form.errors.values())
    exit_with_error('Error creating user', errors) 
Example #2
Source File: screenshots.py    From incubator-superset with Apache License 2.0 6 votes vote down vote up
def get_auth_cookies(user: "User") -> List[Dict[Any, Any]]:
    # Login with the user specified to get the reports
    with current_app.test_request_context("/login"):
        login_user(user)
        # A mock response object to get the cookie information from
        response = Response()
        current_app.session_interface.save_session(current_app, session, response)

    cookies = []

    # Set the cookies in the driver
    for name, value in response.headers:
        if name.lower() == "set-cookie":
            cookie = parse_cookie(value)
            cookies.append(cookie["session"])
    return cookies 
Example #3
Source File: blueprint.py    From website with MIT License 5 votes vote down vote up
def get_emails(self, user):
        """
        Gets the verified email addresses of the authenticated GitHub user.
        """
        with current_app.test_request_context("/"):
            login_user(user)
            return self.session.get("user/emails", all_pages=True) 
Example #4
Source File: commands.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def validate():
    '''Validate the Swagger/OpenAPI specification with your config'''
    with current_app.test_request_context():
        schema = json.loads(json.dumps(api.__schema__))
    try:
        schemas.validate(schema)
        success('API specifications are valid')
    except schemas.SchemaValidationError as e:
        exit_with_error('API specifications are not valid', e) 
Example #5
Source File: commands.py    From notifications-api with MIT License 5 votes vote down vote up
def bulk_invite_user_to_service(file_name, service_id, user_id, auth_type, permissions):
    #  permissions
    #  manage_users | manage_templates | manage_settings
    #  send messages ==> send_texts | send_emails | send_letters
    #  Access API keys manage_api_keys
    #  platform_admin
    #  view_activity
    # "send_texts,send_emails,send_letters,view_activity"
    from app.invite.rest import create_invited_user
    file = open(file_name)
    for email_address in file:
        data = {
            'service': service_id,
            'email_address': email_address.strip(),
            'from_user': user_id,
            'permissions': permissions,
            'auth_type': auth_type,
            'invite_link_host': current_app.config['ADMIN_BASE_URL']
        }
        with current_app.test_request_context(
            path='/service/{}/invite/'.format(service_id),
            method='POST',
            data=json.dumps(data),
            headers={"Content-Type": "application/json"}
        ):
            try:
                response = create_invited_user(service_id)
                if response[1] != 201:
                    print("*** ERROR occurred for email address: {}".format(email_address.strip()))
                print(response[0].get_data(as_text=True))
            except Exception as e:
                print("*** ERROR occurred for email address: {}. \n{}".format(email_address.strip(), e))

    file.close() 
Example #6
Source File: screenshots.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def get_url_path(view: str, **kwargs: Any) -> str:
    with current_app.test_request_context():
        return headless_url(url_for(view, **kwargs)) 
Example #7
Source File: utils.py    From microflack_common with MIT License 5 votes vote down vote up
def url_for(*args, **kwargs):
    """url_for replacement that works even when there is no request context.
    """
    if '_external' not in kwargs:
        kwargs['_external'] = False
    reqctx = _request_ctx_stack.top
    if reqctx is None:
        if kwargs['_external']:
            raise RuntimeError('Cannot generate external URLs without a '
                               'request context.')
        with current_app.test_request_context():
            return _url_for(*args, **kwargs)
    return _url_for(*args, **kwargs) 
Example #8
Source File: api.py    From udata with GNU Affero General Public License v3.0 4 votes vote down vote up
def get(self):
        """
        An OEmbed compliant API endpoint

        See: http://oembed.com/

        Support datasets and reuses URLs
        """
        args = oembed_parser.parse_args()
        if args['format'] != 'json':
            return {'message': 'Only JSON format is supported'}, 501

        url = args['url']

        # Fix flask not detecting URL with https://domain:443/
        if 'https:' in url and ':443/' in url:
            url = url.replace(':443/', '/')

        with current_app.test_request_context(url) as ctx:
            if not ctx.request.endpoint:
                return {'message': 'Unknown URL "{0}"'.format(url)}, 404
            endpoint = ctx.request.endpoint.replace('_redirect', '')
            view_args = ctx.request.view_args

        if endpoint not in self.ROUTES:
            return {'message': 'The URL "{0}" does not support oembed'.format(url)}, 404

        param, prefix = self.ROUTES[endpoint]
        item = view_args[param]
        if isinstance(item, Exception):
            if isinstance(item, HTTPException):
                return {
                    'message': 'An error occured on URL "{0}": {1}'.format(url, str(item))
                }, item.code
            raise item
        width = maxwidth = 1000
        height = maxheight = 200
        params = {
            'width': width,
            'height': height,
            'item': item,
            'type': prefix
        }
        params[param] = item
        html = theme.render('oembed.html', **params)
        return {
            'type': 'rich',
            'version': '1.0',
            'html': html,
            'width': width,
            'height': height,
            'maxwidth': maxwidth,
            'maxheight': maxheight,
        } 
Example #9
Source File: tasks.py    From timesketch with Apache License 2.0 4 votes vote down vote up
def run_email_result_task(index_name, sketch_id=None):
    """Create email Celery task.

    This task is run after all sketch analyzers are done and emails
    the result of all analyzers to the user who imported the data.

    Args:
        index_name: An index name.
        sketch_id: A sketch ID (optional).

    Returns:
        Email sent status.
    """
    # We need to get a fake request context so that url_for() will work.
    with current_app.test_request_context():
        searchindex = SearchIndex.query.filter_by(index_name=index_name).first()
        sketch = None

        try:
            to_username = searchindex.user.username
        except AttributeError:
            logging.warning('No user to send email to.')
            return ''

        if sketch_id:
            sketch = Sketch.query.get(sketch_id)

        subject = 'Timesketch: [{0:s}] is ready'.format(searchindex.name)

        # TODO: Use jinja templates.
        body = 'Your timeline [{0:s}] has been imported and is ready.'.format(
            searchindex.name)

        if sketch:
            view_urls = sketch.get_view_urls()
            view_links = []
            for view_url, view_name in iter(view_urls.items()):
                view_links.append('<a href="{0:s}">{1:s}</a>'.format(
                    view_url,
                    view_name))

            body = body + '<br><br><b>Sketch</b><br>{0:s}'.format(
                sketch.external_url)

            analysis_results = searchindex.description.replace('\n', '<br>')
            body = body + '<br><br><b>Analysis</b>{0:s}'.format(
                analysis_results)

            if view_links:
                body = body + '<br><br><b>Views</b><br>' + '<br>'.join(
                    view_links)

        try:
            send_email(subject, body, to_username, use_html=True)
        except RuntimeError as e:
            return repr(e)

    return 'Sent email to {0:s}'.format(to_username)