Python flask.request.base_url() Examples

The following are 22 code examples of flask.request.base_url(). 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.request , or try the search function .
Example #1
Source File: flask_profiler.py    From flask-profiler with MIT License 7 votes vote down vote up
def wrapHttpEndpoint(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        context = {
            "url": request.base_url,
            "args": dict(request.args.items()),
            "form": dict(request.form.items()),
            "body": request.data.decode("utf-8", "strict"),
            "headers": dict(request.headers.items()),
            "func": request.endpoint,
            "ip": request.remote_addr
        }
        endpoint_name = str(request.url_rule)
        wrapped = measure(f, endpoint_name, request.method, context)
        return wrapped(*args, **kwargs)

    return wrapper 
Example #2
Source File: views.py    From guides-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
def review(title):
    """
    This URL only exists for legacy reasons so try to find the article where
    it is in the new scheme and return 301 to indicate moved.
    """

    branch = request.args.get('branch', u'master')

    article = models.search_for_article(title)
    if article is not None:
        return redirect(filters.url_for_article(article, branch=branch), 301)

    return missing_article(request.base_url, title=title, branch=branch)


# Note this URL is directly linked to the filters.url_for_article filter.
# These must be changed together! 
Example #3
Source File: query.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def to_url(self, url=None, replace=False, **kwargs):
        '''Serialize the query into an URL'''
        params = copy.deepcopy(self.filter_values)
        if self._query:
            params['q'] = self._query
        if self.page_size != DEFAULT_PAGE_SIZE:
            params['page_size'] = self.page_size
        if kwargs:
            for key, value in kwargs.items():
                if not replace and key in params:
                    if not isinstance(params[key], (list, tuple)):
                        params[key] = [params[key], value]
                    else:
                        params[key].append(value)
                else:
                    params[key] = value
        else:
            params['page'] = self.page
        href = Href(url or request.base_url)
        return href(params) 
Example #4
Source File: renderers.py    From puncover with MIT License 6 votes vote down vote up
def col_sortable_filter(context, title, is_alpha=False, id=None):

    id = title if id is None else id
    id = id.lower()

    # when sorting for numbers, we're interested in large numbers first
    next_sort = 'asc' if is_alpha else 'desc'
    sort_id, sort_order = context.parent.get('sort', 'a_b').split('_')
    classes = ['sortable']
    if sort_id.lower() == id:
        sort_class = 'sort_' + sort_order
        next_sort = 'desc' if sort_order == 'asc' else 'asc'
        if is_alpha:
            sort_class += '_alpha'
        classes.append(sort_class)

    next_sort = id + '_' + next_sort

    # replace/set ?sort= in URL
    args = request.args.copy()
    args['sort'] = next_sort
    url = Href(request.base_url, sort=True)

    return '<a href="%s" class="%s">%s</a>' % (url(args), ' '.join(classes), title) 
Example #5
Source File: mails.py    From flask-base-api with MIT License 5 votes vote down vote up
def send_password_recovery_email(user, token):
    href = request.base_url + '/' + token
    send_async_password_recovery_email.delay(subject="Password Recovery by Flask Base Api! %s" % user.username,
                                             recipient=user.email,
                                             text_body=render_template("auth/password_recovery_user.txt", user=user),
                                             html_body=render_template("auth/password_recovery_user.html", user=user, href=href)) 
Example #6
Source File: paging.py    From frest with MIT License 5 votes vote down vote up
def get_url(page=0):
    values = request.args.to_dict()
    values.update({'page': page})

    return request.base_url + '?' + urllib.urlencode(values) 
Example #7
Source File: views.py    From guides-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
def partner(article_path):
    """
    URL for articles from hackhands blog -- these articles are not
    editable.
    """

    try:
        repo_path = '%s/%s' % (app.config['SECONDARY_REPO_OWNER'],
                               app.config['SECONDARY_REPO_NAME'])
    except KeyError:
        flash('No secondary guide configuration', category='error')
        return redirect(url_for('index'))

    if article_path is None:
        articles = models.get_available_articles(status=PUBLISHED,
                                                 repo_path=repo_path)
        return render_template('review.html', articles=articles)

    article = models.read_article(article_path, repo_path=repo_path)
    if article is None:
        flash('Failed reading guide', category='error')
        return redirect(url_for('index'))

    # Use http as canonical protocol for url to avoid having two separate
    # comment threads for an article. Disqus uses this variable to save
    # comments.
    canonical_url = request.base_url.replace('https://', 'http://')

    form = forms.SignupForm()

    return render_template('article.html',
                           article=article,
                           allow_edits=False,
                           canonical_url=canonical_url,
                           form=form,
                           disclaimer=True) 
Example #8
Source File: app.py    From biolink-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def hello():
    return render_template('index.html', base_url=request.base_url) 
Example #9
Source File: utils.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def _get_uri_from_request(request):
    """
    The uri returned from request.uri is not properly urlencoded
    (sometimes it's partially urldecoded) This is a weird hack to get
    werkzeug to return the proper urlencoded string uri
    """
    uri = request.base_url
    if request.query_string:
        uri += '?' + request.query_string.decode('utf-8')
    return uri 
Example #10
Source File: views.py    From planespotter with MIT License 5 votes vote down vote up
def create_link_string(page, last_page, per_page):
    """Returns a string representing the value of the ``Link`` header.

    `page` is the number of the current page, `last_page` is the last page in
    the pagination, and `per_page` is the number of results per page.

    """
    linkstring = ''
    if page < last_page:
        next_page = page + 1
        linkstring = LINKTEMPLATE.format(request.base_url, next_page,
                                         per_page, 'next') + ', '
    linkstring += LINKTEMPLATE.format(request.base_url, last_page,
                                      per_page, 'last')
    return linkstring 
Example #11
Source File: mails.py    From flask-base-api with MIT License 5 votes vote down vote up
def send_email_verification_email(user, token):
    href = request.base_url + '/' + token
    send_async_email_verification_email.delay(subject="Email confirmation by Flask Base Api! %s" % user.username,
                                              recipient=user.email,
                                              text_body=render_template("auth/email_verification_user.txt", user=user),
                                              html_body=render_template("auth/email_verification_user.html", user=user, href=href)) 
Example #12
Source File: util.py    From pscheduler with Apache License 2.0 5 votes vote down vote up
def base_url(path = None):
    return request.base_url + ("" if path is None else "/" + path) 
Example #13
Source File: plugin.py    From indico-plugins with MIT License 5 votes vote down vote up
def track_download(self, attachment, from_preview, **kwargs):
        if from_preview or not self.settings.get('enabled_for_downloads'):
            return
        if attachment.type == AttachmentType.link:
            resource_url = attachment.link_url
            resource_title = u'Link - {0.title}'.format(attachment)
        else:
            resource_url = request.base_url
            resource_title = u'Download - {0.title}'.format(attachment)
        track_download_request.delay(resource_url, resource_title) 
Example #14
Source File: rest_decorators.py    From cloudify-manager with Apache License 2.0 5 votes vote down vote up
def _get_api_version():
        url = request.base_url
        if 'api' not in url:
            return None
        version = url.split('/api/')[1]
        return version.split('/')[0] 
Example #15
Source File: base.py    From freight with Apache License 2.0 5 votes vote down vote up
def build_cursor_link(self, name, cursor):
        querystring = "&".join(
            f"{quote(k)}={quote(v)}" for k, v in request.args.items() if k != "cursor"
        )
        base_url = request.base_url
        if querystring:
            base_url = f"{base_url}?{querystring}"
        else:
            base_url = base_url + "?"

        return LINK_HEADER.format(uri=base_url, cursor=str(cursor), name=name) 
Example #16
Source File: response.py    From pscheduler with Apache License 2.0 5 votes vote down vote up
def not_implemented(message="Not implemented."):
    log.debug("Response 501: %s", message)
    log.warning("Not implemented %s %s %s: %s", request.remote_addr, request.method, request.base_url, message)
    return Response(message + "\n", status=501, mimetype="text/plain") 
Example #17
Source File: response.py    From pscheduler with Apache License 2.0 5 votes vote down vote up
def error(message="Unknown internal error"):
    log.debug("Response 500: %s", message)
    log.error("Internal error %s %s %s: %s", request.remote_addr, request.method, request.base_url, message)
    return Response(message + '\n', status=500, mimetype="text/plain") 
Example #18
Source File: response.py    From pscheduler with Apache License 2.0 5 votes vote down vote up
def not_allowed():
    log.debug("Response 405: %s not allowed.", request.method)
    log.info("Disallowed %s %s %s", request.remote_addr, request.method, request.base_url)
    return Response("%s not allowed on this resource\n" % (request.method),
                    status=405, mimetype="text/plain") 
Example #19
Source File: response.py    From pscheduler with Apache License 2.0 5 votes vote down vote up
def forbidden(message="Forbidden."):
    log.debug("Response 403: %s", message)
    log.info("Forbade %s %s %s: %s", request.remote_addr, request.method, request.base_url, message)
    return Response(message + "\n", status=403, mimetype="text/plain") 
Example #20
Source File: firetactoe.py    From python-docs-samples with Apache License 2.0 4 votes vote down vote up
def main_page():
    """Renders the main page. When this page is shown, we create a new
    channel to push asynchronous updates to the client."""
    user = users.get_current_user()
    game_key = request.args.get('g')

    if not game_key:
        game_key = user.user_id()
        game = Game(id=game_key, userX=user, moveX=True, board=' '*9)
        game.put()
    else:
        game = Game.get_by_id(game_key)
        if not game:
            return 'No such game', 404
        if not game.userO:
            game.userO = user
            game.put()

    # [START pass_token]
    # choose a unique identifier for channel_id
    channel_id = user.user_id() + game_key
    # encrypt the channel_id and send it as a custom token to the
    # client
    # Firebase's data security rules will be able to decrypt the
    # token and prevent unauthorized access
    client_auth_token = create_custom_token(channel_id)
    _send_firebase_message(channel_id, message=game.to_json())

    # game_link is a url that you can open in another browser to play
    # against this player
    game_link = '{}?g={}'.format(request.base_url, game_key)

    # push all the data to the html template so the client will
    # have access
    template_values = {
        'token': client_auth_token,
        'channel_id': channel_id,
        'me': user.user_id(),
        'game_key': game_key,
        'game_link': game_link,
        'initial_message': urllib.unquote(game.to_json())
    }

    return flask.render_template('fire_index.html', **template_values)
    # [END pass_token] 
Example #21
Source File: auth.py    From notifications-api with MIT License 4 votes vote down vote up
def requires_auth():
    request_helper.check_proxy_header_before_request()

    auth_token = get_auth_token(request)
    issuer = __get_token_issuer(auth_token)  # ie the `iss` claim which should be a service ID

    try:
        with AUTH_DB_CONNECTION_DURATION_SECONDS.time():
            service = SerialisedService.from_id(issuer)
    except DataError:
        raise AuthError("Invalid token: service id is not the right data type", 403)
    except NoResultFound:
        raise AuthError("Invalid token: service not found", 403)

    if not service.api_keys:
        raise AuthError("Invalid token: service has no API keys", 403, service_id=service.id)

    if not service.active:
        raise AuthError("Invalid token: service is archived", 403, service_id=service.id)

    for api_key in service.api_keys:
        try:
            decode_jwt_token(auth_token, api_key.secret)
        except TokenExpiredError:
            err_msg = "Error: Your system clock must be accurate to within 30 seconds"
            raise AuthError(err_msg, 403, service_id=service.id, api_key_id=api_key.id)
        except TokenAlgorithmError:
            err_msg = "Invalid token: algorithm used is not HS256"
            raise AuthError(err_msg, 403, service_id=service.id, api_key_id=api_key.id)
        except TokenDecodeError:
            # we attempted to validate the token but it failed meaning it was not signed using this api key.
            # Let's try the next one
            # TODO: Change this so it doesn't also catch `TokenIssuerError` or `TokenIssuedAtError` exceptions (which
            # are children of `TokenDecodeError`) as these should cause an auth error immediately rather than
            # continue on to check the next API key
            continue
        except TokenError:
            # General error when trying to decode and validate the token
            raise AuthError(GENERAL_TOKEN_ERROR_MESSAGE, 403, service_id=service.id, api_key_id=api_key.id)

        if api_key.expiry_date:
            raise AuthError("Invalid token: API key revoked", 403, service_id=service.id, api_key_id=api_key.id)

        g.service_id = service.id
        _request_ctx_stack.top.authenticated_service = service
        _request_ctx_stack.top.api_user = api_key

        current_app.logger.info('API authorised for service {} with api key {}, using issuer {} for URL: {}'.format(
            service.id,
            api_key.id,
            request.headers.get('User-Agent'),
            request.base_url
        ))
        return
    else:
        # service has API keys, but none matching the one the user provided
        raise AuthError("Invalid token: API key not found", 403, service_id=service.id) 
Example #22
Source File: flask_swagger_ui.py    From flask-swagger-ui with MIT License 4 votes vote down vote up
def get_swaggerui_blueprint(
        base_url,
        api_url,
        config=None,
        oauth_config=None,
        blueprint_name='swagger_ui'
):

    swagger_ui = Blueprint(blueprint_name,
                           __name__,
                           static_folder='dist',
                           template_folder='templates')

    default_config = {
        'app_name': 'Swagger UI',
        'dom_id': '#swagger-ui',
        'url': api_url,
        'layout': 'StandaloneLayout',
        'deepLinking': True
    }

    if config:
        default_config.update(config)

    fields = {
        # Some fields are used directly in template
        'base_url': base_url,
        'app_name': default_config.pop('app_name'),
        # Rest are just serialized into json string for inclusion in the .js file
        'config_json': json.dumps(default_config),

    }
    if oauth_config:
        fields['oauth_config_json'] = json.dumps(oauth_config)

    @swagger_ui.route('/')
    @swagger_ui.route('/<path:path>')
    def show(path=None):
        if not path or path == 'index.html':
            if not default_config.get('oauth2RedirectUrl', None):
                default_config.update(
                    {"oauth2RedirectUrl": os.path.join(request.base_url, "oauth2-redirect.html")}
                )
                fields['config_json'] = json.dumps(default_config)
            return render_template('index.template.html', **fields)
        else:
            return send_from_directory(
                # A bit of a hack to not pollute the default /static path with our files.
                os.path.join(
                    swagger_ui.root_path,
                    swagger_ui._static_folder
                ),
                path
            )

    return swagger_ui