Python flask.request.url_root() Examples

The following are 30 code examples of flask.request.url_root(). 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: web_ui.py    From PatchServer with MIT License 6 votes vote down vote up
def rss_feed():
    feed = AtomFeed(
        'Patch Server Software Titles',
        feed_url=request.url,
        url=request.url_root,
        generator=('Patch Server', None, __version__))

    titles = SoftwareTitle.query.all()

    for title in titles:
        feed.add(
            title=title.name,
            author=title.publisher,
            content='<b>Version:</b> {} '
                    '<b>| App Name:</b> {} '
                    '<b>| Bundle ID:</b> {}'.format(
                        title.current_version, title.app_name, title.bundle_id),
            url=url_for(
                'patch_by_name_id', name_id=title.id_name, _external=True),
            updated=title.last_modified)

    return feed.get_response() 
Example #2
Source File: router.py    From maple-blog with GNU General Public License v3.0 6 votes vote down vote up
def get(self):
        title = SITE['title']
        subtitle = SITE['subtitle']
        feed = AtomFeed(
            '%s' % (title),
            feed_url=request.url,
            url=request.url_root,
            subtitle=subtitle)
        articles = Article.query.limit(10)
        for article in articles:
            feed.add(
                article.title,
                article.to_html(),
                content_type='html',
                author=article.user.username,
                url=urljoin(request.url_root,
                            url_for('blog.article', pk=article.id)),
                updated=article.updated_at,
                published=article.created_at)
        return feed.get_response() 
Example #3
Source File: front.py    From white with GNU General Public License v2.0 6 votes vote down vote up
def _feed_json():
    posts = []
    for post in post_service.get_published_posts():
        data = dict(author=post.user.username,
                    html=markdown.convert(post.html),
                    url=urljoin(request.url_root,  '/post/' + post.slug),
                    updated=post.updated,
                    published=post.created
                    )
        posts.append(data)

    rss = {
        'sitename': config.sitename(),
        'site': request.url_root,
        'updated': datetime.now(),
        'description': config.description(),
        'posts': posts
    }
    return rss 
Example #4
Source File: Update.py    From FuzzFlow with MIT License 6 votes vote down vote up
def get(self, hash):
        path = 'static' + os.sep + 'client.zip'
        try:
            os.remove(path)
        except:
            None
        zip = zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED)
        for root, dirs, files in os.walk(CLIENT_FOLDER):
            for f in files:
                zip.write(os.path.join(root, f))
        zip.close()

        client = open(path).read()

        if hash == hashlib.md5(client).hexdigest():
            return {"err": "invalid request"}, 400
        else:
            return {"url": request.url_root + path}, 200 
Example #5
Source File: advisory.py    From arch-security-tracker with MIT License 6 votes vote down vote up
def advisory_atom():
    return not_found()

    last_recent_entries = 15
    data = get_advisory_data()['published'][:last_recent_entries]
    # TODO:fix me
    feed = AtomFeed('Arch Linux Security - Recent advisories',
                    feed_url=request.url, url=request.url_root)

    for entry in data:
        advisory = entry['advisory']
        package = entry['package']
        title = '[{}] {}: {}'.format(advisory.id, package.pkgname, advisory.advisory_type)

        feed.add(title=title,
                 content=render_template('feed.html', content=advisory.content),
                 content_type='html',
                 summary=render_template('feed.html', content=advisory.impact),
                 summary_tpe='html',
                 author='Arch Linux Security Team',
                 url=TRACKER_ISSUE_URL.format(advisory.id),
                 published=advisory.created,
                 updated=advisory.created)
    return feed.get_response() 
Example #6
Source File: settings.py    From the-example-app.py with MIT License 6 votes vote down vote up
def reset_settings():
    session.pop('space_id', None)
    session.pop('delivery_token', None)
    session.pop('preview_token', None)
    session.pop('editorial_features', None)

    space = contentful().space(api_id())

    return render_with_globals(
        'settings',
        title=translate('settingsLabel', locale().code),
        errors={},
        has_errors=False,
        success=False,
        space=space,
        host=request.url_root
    ) 
Example #7
Source File: technology.py    From age-of-empires-II-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def map_to_resource_url(self):
        out = []
        for item in self.applies_to.split(';'):
            unit = get_model('units').query.filter_by(name=item).first()
            structure = get_model('structures').query.filter_by(name=item).first()
            civilization = get_model('civilizations').query.filter_by(name=item).first()

            if unit:
                out.append('{}unit/{}'.format(request.url_root + request.blueprint, self.format_name_to_query(unit.name)))
            elif structure:
                out.append('{}structure/{}'.format(request.url_root + request.blueprint, self.format_name_to_query(structure.name)))
            elif civilization:
                out.append('{}civilization/{}'.format(request.url_root + request.blueprint, self.format_name_to_query(civilization.name)))
            else:
                out.append(item)
        return out 
Example #8
Source File: settings.py    From the-example-app.py with MIT License 6 votes vote down vote up
def save_settings():
    space_id = request.values.get('spaceId', None)
    delivery_token = request.values.get('deliveryToken', None)
    preview_token = request.values.get('previewToken', None)
    editorial_features = bool(request.values.get('editorialFeatures', False))

    errors = check_errors(space_id, delivery_token, preview_token)

    if not errors:
        update_session_for('space_id', space_id)
        update_session_for('delivery_token', delivery_token)
        update_session_for('preview_token', preview_token)
        update_session_for('editorial_features', editorial_features)

    space = contentful().space(api_id())
    return render_with_globals(
        'settings',
        title=translate('settingsLabel', locale().code),
        errors=errors,
        has_errors=bool(errors),
        success=not bool(errors),
        space=space,
        host=request.url_root
    ), 201 if not errors else 409 
Example #9
Source File: __init__.py    From flask-restless-swagger with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def init_app(self, app, **kwargs):
        self.app = app
        self.manager = APIManager(self.app, **kwargs)

        swagger = Blueprint('swagger', __name__, static_folder='static',
                            static_url_path=self.app.static_url_path + '/swagger', )

        @swagger.route('/swagger')
        def swagger_ui():
            return redirect('/static/swagger/swagger-ui/index.html')

        @swagger.route('/swagger.json')
        def swagger_json():
            # I can only get this from a request context
            self.swagger['host'] = urlparse.urlparse(request.url_root).netloc
            return jsonify(self.swagger)

        app.register_blueprint(swagger) 
Example #10
Source File: civilization.py    From age-of-empires-II-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def json(self):
        civilization = [('id', self._id),
                        ('name', self.name),
                        ('expansion', self.expansion),
                        ('army_type', self.army_type),
                        ('unique_unit', self.parse_array_field(self.unique_unit)
                         if not self.unit.first()
                         else ['{}unit/{}'.format(request.url_root + request.blueprint,
                                                  self.format_name_to_query(self.unit.first().name))]
                         ),
                        ('unique_tech', self.parse_array_field(self.unique_tech)
                         if not self.technology.first()
                         else ['{}technology/{}'.format(request.url_root + request.blueprint,
                               self.format_name_to_query(self.technology.first().name))]
                         ),
                        ('team_bonus', self.team_bonus),
                        ('civilization_bonus', self.civilization_bonus.split(";"))
                        ]
        return OrderedDict(civilization) 
Example #11
Source File: unit.py    From age-of-empires-II-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def json(self):
        unit = [('id', self._id), ('name', self.name),
                ('description', self.description),
                ('expansion', self.expansion),
                ('age', self.age),
                ('created_in',
                '{}structure/{}'.format(request.url_root + request.blueprint,
                                        self.format_name_to_query(self.structure.first().name))
                 if self.structure.first() else self.created_in),
                ('cost', json.loads(self.cost.replace(";", ","))),
                ('build_time', self.build_time),
                ('reload_time', self.reload_time),
                ('attack_delay', self.attack_delay),
                ('movement_rate', self.movement_rate),
                ('line_of_sight', self.line_of_sight),
                ('hit_points', self.hit_points),
                ('range', int(self.range) if self.range.isdigit() else self.range),
                ('attack', self.attack), ('armor', self.armor),
                ('attack_bonus', self.attack_bonus.split(";") if self.attack_bonus else None),
                ('armor_bonus', self.armor_bonus.split(";") if self.armor_bonus else None),
                ('search_radius', self.search_radius),
                ('accuracy', self.accuracy),
                ('blast_radius', self.blast_radius)]
        return OrderedDict([(k, v) for k, v in unit if v]) 
Example #12
Source File: __init__.py    From CHN-Server with GNU Lesser General Public License v2.1 6 votes vote down vote up
def get_feed():
    from mhn.common.clio import Clio
    from mhn.auth import current_user
    authfeed = mhn.config['FEED_AUTH_REQUIRED']
    if authfeed and not current_user.is_authenticated():
        abort(404)
    feed = AtomFeed('MHN HpFeeds Report', feed_url=request.url,
                    url=request.url_root)
    sessions = Clio().session.get(options={'limit': 1000})
    for s in sessions:
        feedtext = u'Sensor "{identifier}" '
        feedtext += '{source_ip}:{source_port} on sensorip:{destination_port}.'
        feedtext = feedtext.format(**s.to_dict())
        feed.add('Feed', feedtext, content_type='text',
                 published=s.timestamp, updated=s.timestamp,
                 url=makeurl(url_for('api.get_session', session_id=str(s._id))))
    return feed 
Example #13
Source File: glance_dummy_api.py    From son-emu with Apache License 2.0 6 votes vote down vote up
def get(self):
        LOG.debug("API CALL: %s GET" % str(self.__class__.__name__))
        resp = dict()
        resp['versions'] = dict()
        versions = [{
            "status": "CURRENT",
            "id": "v2",
            "links": [
                {
                    "href": request.url_root + '/v2',
                    "rel": "self"
                }
            ]
        }]
        resp['versions'] = versions
        return Response(json.dumps(resp), status=200,
                        mimetype='application/json') 
Example #14
Source File: neutron_dummy_api.py    From son-emu with Apache License 2.0 6 votes vote down vote up
def get(self):
        """
        Lists API versions.

        :return: Returns a json with API versions.
        :rtype: :class:`flask.response`
        """
        LOG.debug("API CALL: Neutron - List API Versions")
        resp = dict()
        resp['versions'] = dict()

        versions = [{
            "status": "CURRENT",
            "id": "v2.0",
            "links": [
                {
                    "href": request.url_root + '/v2.0',
                    "rel": "self"
                }
            ]
        }]
        resp['versions'] = versions

        return Response(json.dumps(resp), status=200,
                        mimetype='application/json') 
Example #15
Source File: track-ncco.py    From nexmo-python-code-snippets with MIT License 6 votes vote down vote up
def answer_call():
  ncco = [{
      "action": "talk",
      "text": "Thanks for calling the notification line"
    },
    {
      "action": "notify",
      "payload": {
        "foo": "bar"
      },
      "eventUrl": [
        "{url_root}webhooks/notification".format(url_root=request.url_root)
      ]
    },
    {
      "action": "talk",
      "text": "You will never hear me as the notification URL will return an NCCO "
    }]
  return jsonify(ncco) 
Example #16
Source File: server.py    From voice-quickstart-server-python with MIT License 6 votes vote down vote up
def placeCall():
  account_sid = os.environ.get("ACCOUNT_SID", ACCOUNT_SID)
  api_key = os.environ.get("API_KEY", API_KEY)
  api_key_secret = os.environ.get("API_KEY_SECRET", API_KEY_SECRET)

  client = Client(api_key, api_key_secret, account_sid)
  to = request.values.get("to")
  call = None

  if to is None or len(to) == 0:
    call = client.calls.create(url=request.url_root + 'incoming', to='client:' + IDENTITY, from_=CALLER_ID)
  elif to[0] in "+1234567890" and (len(to) == 1 or to[1:].isdigit()):
    call = client.calls.create(url=request.url_root + 'incoming', to=to, from_=CALLER_NUMBER)
  else:
    call = client.calls.create(url=request.url_root + 'incoming', to='client:' + to, from_=CALLER_ID)
  return str(call) 
Example #17
Source File: handle-user-input.py    From nexmo-python-code-snippets with MIT License 6 votes vote down vote up
def answer_call():
    for param_key, param_value in request.args.items():
        print("{}: {}".format(param_key, param_value))
    input_webhook_url = request.url_root + "webhooks/dtmf"
    ncco =[
        {
            "action": "talk",
            "text": "Hello, please press any key to continue."
        },
        {
            "action": "input",
            "maxDigits": 1,
            "eventUrl": [input_webhook_url]
        }
    ]
    return jsonify(ncco) 
Example #18
Source File: factory-package-news-web.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def current():
    _dir = get_dir(request.url_root)
    fn = os.path.join(_dir, 'current')
    if request.method == 'POST':
        if not 'version' in request.form:
            return "missing version", 400
        version = request.form['version']
        if not digits_re.match(version):
            return "malformed version", 400
        if not os.path.exists(os.path.join(_dir, version)):
            return "invalid version", 400
        tmpfn = os.path.join(_dir, '.' + version)
        app.logger.debug(tmpfn)
        if os.path.exists(tmpfn):
            os.unlink(tmpfn)
        os.symlink(version, tmpfn)
        os.rename(tmpfn, fn)
        return "ok"
    else:
        if not os.path.exists(fn):
            return "", 404
        return os.readlink(fn) 
Example #19
Source File: factory-package-news-web.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def list():
    _dir = get_dir(request.url_root)
    fn = os.path.join(_dir, 'current')
    current = None
    if os.path.exists(fn):
        current = os.readlink(fn)

    ret = ''
    for i in sorted(os.listdir(_dir), reverse=True):
        if not digits_re.match(i):
            continue
        ret = ret + '<a href="diff/%s">%s</a>' % (i, i)
        if i == current:
            ret = ret + " &lt;--"
        ret = ret + '<br/>'
    return ret 
Example #20
Source File: record-a-message.py    From nexmo-python-code-snippets with MIT License 6 votes vote down vote up
def answer_call():
    for param_key, param_value in request.args.items():
        print("{}: {}".format(param_key, param_value))
    recording_webhook_url = request.url_root + "webhooks/recording"
    ncco =[
        {
            "action": "talk",
            "text": "Please leave a message after the tone, then press the hash key."
        },
        {
            "action": "record",
            "endOnKey": "#",
            "beepStart": "true",
            "eventUrl": [recording_webhook_url]
        },
        {
            "action": "talk",
            "text": "Thank you for your message."
        }
    ])
    return jsonify(ncco) 
Example #21
Source File: wc.py    From tushe with MIT License 6 votes vote down vote up
def receive():
    data = request.data
    data = xmltodict.parse(data)['xml']
    if data['MsgType'] == 'text':
        return send_text(data['FromUserName'], 'hi')
    if data['MsgType'] == 'image':
        token = current_access_token()
        file_url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s' % (token, data['MediaId'])
        file = requests.get(file_url, stream=True).raw
        i = Image()
        i.image = file
        uuid = shortuuid.ShortUUID().random(length=6)
        while Image.objects(iid=uuid):
            uuid = shortuuid.ShortUUID().random(length=6)
        i.iid = uuid
        i.title = data['MediaId']
        i.user = system_user
        i.description = ''
        i.tags = []
        i.save()
        return send_text(
            data['FromUserName'], '上传成功!图片地址:%s%s' % (
                request.url_root[:-1], url_for('light-cms.image', iid=i.iid)
            )
        ) 
Example #22
Source File: label.py    From c3bottles with MIT License 5 votes vote down vote up
def _create_pdf(dp: DropPoint):
    img = qrcode.make(request.url_root + str(dp.number))
    f = BytesIO()
    img.save(f)
    b64 = b64encode(f.getvalue()).decode("utf-8")
    label_style = app.config.get("LABEL_STYLE", "default")
    specific_label_style = label_style + "_" + snakecase(lowercase(dp.category.name))
    print(specific_label_style, label_style)
    try:
        return svg2pdf(render_template("label/{}.svg".format(specific_label_style), number=dp.number, qr=b64))  # noqa
    except:  # noqa
        return svg2pdf(render_template("label/{}.svg".format(label_style), number=dp.number, qr=b64))  # noqa 
Example #23
Source File: handshake.py    From QuestradeAPI_PythonWrapper with Apache License 2.0 5 votes vote down vote up
def callback():
    questradeAPI = OAuth2Session(client_id, redirect_uri=__get_redirect_uri__(request.url_root), state=session['oauth_state'])
    token = questradeAPI.fetch_token(token_url, client_secret=client_secret, authorization_response=request.url)
    
    __set_session_token__(token)
    
    return redirect(url_for('.token')) 
Example #24
Source File: blaskapp.py    From blask with GNU General Public License v3.0 5 votes vote down vote up
def _get_sitemap(self):
        """
        render the sitemap.xml file
        :returns: prints the sitemapfile
        """
        return Response(
            self.blogrenderer.generate_sitemap_xml(self.settings["postDir"], request.url_root),
            content_type="text/xml",
        ) 
Example #25
Source File: post_notifications.py    From notifications-api with MIT License 5 votes vote down vote up
def create_response_for_post_notification(
    notification_id,
    client_reference,
    template_id,
    template_version,
    service_id,
    notification_type,
    reply_to,
    template_with_content
):
    if notification_type == SMS_TYPE:
        create_resp_partial = functools.partial(
            create_post_sms_response_from_notification,
            from_number=reply_to,
        )
    elif notification_type == EMAIL_TYPE:
        create_resp_partial = functools.partial(
            create_post_email_response_from_notification,
            subject=template_with_content.subject,
            email_from='{}@{}'.format(authenticated_service.email_from, current_app.config['NOTIFY_EMAIL_DOMAIN']),
        )
    elif notification_type == LETTER_TYPE:
        create_resp_partial = functools.partial(
            create_post_letter_response_from_notification,
            subject=template_with_content.subject,
        )
    resp = create_resp_partial(
        notification_id, client_reference, template_id, template_version, service_id,
        url_root=request.url_root,
        content=template_with_content.content_with_placeholders_filled_in,
    )
    return resp 
Example #26
Source File: handshake.py    From QuestradeAPI_PythonWrapper with Apache License 2.0 5 votes vote down vote up
def authorize():
    questradeAPI = OAuth2Session(client_id, redirect_uri=__get_redirect_uri__(request.url_root))
    user_authorization_url, state = questradeAPI.authorization_url(authorization_url)
    
    session['oauth_state'] = state
    return redirect(user_authorization_url) 
Example #27
Source File: settings.py    From the-example-app.py with MIT License 5 votes vote down vote up
def show_settings():
    current_space_id = space_id()
    current_delivery_token = delivery_token()
    current_preview_token = preview_token()

    errors = check_errors(
        current_space_id,
        current_delivery_token,
        current_preview_token
    )

    if errors:
        restore_session_to_last_valid_values()

    space = contentful().space(api_id())
    return render_with_globals(
        'settings',
        title=translate('settingsLabel', locale().code),
        errors=errors,
        has_errors=bool(errors),
        success=False,
        space=space,
        is_using_custom_credentials=is_using_custom_credentials(session),
        space_id=current_space_id,
        delivery_token=current_delivery_token,
        preview_token=current_preview_token,
        host=request.url_root
    ) 
Example #28
Source File: views.py    From squealy with MIT License 5 votes vote down vote up
def swagger():
    paths = {}
    for resource in resources.values():
        path = {}
        path['summary'] = resource.summary
        path['description'] = resource.description
        path['responses'] = {
            "200": {"description": "A JSON"}
        }
        path['parameters'] = _load_parameters(resource)
        paths[resource.path] = {"get": path}
        

    return {
        "openapi": "3.0.0",
        "info": {
            "title": "Squealy APi",
            "version": "0.1.9"
        },
        "servers": [ 
            {
            "url": request.url_root
            }
        ],
        "paths": paths,
        "components": {
            "securitySchemes": {
            "BearerAuth": {
                "type": "http",
                "scheme": "bearer",
                "bearerFormat": "JWT"
            }
            }
        },
        "security": [
            {
            "BearerAuth": []
            }
        ]
    } 
Example #29
Source File: helpers.py    From yeti with Apache License 2.0 5 votes vote down vote up
def csrf_protect():
    if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
        referer = request.headers.get('Referer')
        print(referer)

        if referer is None or different_origin(referer, request.url_root):
            raise Forbidden(description="Referer check failed.") 
Example #30
Source File: app.py    From wechatpy with MIT License 5 votes vote down vote up
def index():
    host = request.url_root
    return render_template("index.html", host=host)