Python django.conf.settings.SITE_ROOT Examples

The following are 29 code examples for showing how to use django.conf.settings.SITE_ROOT(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: opencraft   Author: open-craft   File: load_balancer.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def run_playbook(self, ansible_vars):
        """
        Run the playbook to perform the server reconfiguration.

        This is factored out into a separate method so it can be mocked out in the tests.
        """
        if settings.DISABLE_LOAD_BALANCER_CONFIGURATION:
            self.logger.info(
                'Direct load balancer reconfiguration disabled. Skipping %s configuration...',
                self
            )
            return

        playbook_path = pathlib.Path(settings.SITE_ROOT) / "playbooks/load_balancer_conf/load_balancer_conf.yml"
        returncode = ansible.capture_playbook_output(
            requirements_path=str(playbook_path.parent / "requirements.txt"),
            inventory_str=self.domain,
            vars_str=ansible_vars,
            playbook_path=str(playbook_path),
            username=self.ssh_username,
            logger_=self.logger,
        )
        if returncode != 0:
            self.logger.error("Playbook to reconfigure load-balancing server %s failed.", self)
            raise ReconfigurationFailed 
Example 2
Project: opencraft   Author: open-craft   File: openedx_appserver.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def manage_services_playbook(self, action, services="all"):
        """
        Return a Playbook instance for creating LMS users.
        """
        playbook_settings = yaml.dump(
            {
                "supervisord_action": action,
                "services": services,
            },
            default_flow_style=False
        )

        return Playbook(
            version=None,
            source_repo=os.path.join(settings.SITE_ROOT, 'playbooks/manage_services'),
            requirements_path='requirements.txt',
            playbook_path='manage_services.yml',
            variables=playbook_settings,
        ) 
Example 3
Project: opencraft   Author: open-craft   File: test_openedx_appserver.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_manage_instance_services(self, mocks, mock_consul):
        """
        Test if manage instance services is correctly running the playbook
        """
        instance = OpenEdXInstanceFactory(internal_lms_domain='test.activate.opencraft.co.uk')
        appserver_id = instance.spawn_appserver()
        appserver = instance.appserver_set.get(pk=appserver_id)
        expected_playbook = Playbook(
            version=None,
            source_repo=os.path.join(settings.SITE_ROOT, 'playbooks/manage_services'),
            playbook_path='manage_services.yml',
            requirements_path='requirements.txt',
            variables='services: all\nsupervisord_action: start\n'
        )

        appserver.manage_instance_services(active=True)

        self.assertEqual(mocks.mock_run_appserver_playbooks.call_count, 1)
        mocks.mock_run_appserver_playbooks.assert_called_once_with(
            playbook=expected_playbook,
            working_dir=expected_playbook.source_repo,
        ) 
Example 4
Project: suponoff   Author: GambitResearch   File: views.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def action(request):
    server = request.POST['server']
    supervisor = _get_supervisor(server)
    try:
        if 'action_start_all' in request.POST:
            supervisor.supervisor.startAllProcesses()
            return HttpResponse(json.dumps("ok"),
                                content_type='application/json')
        elif 'action_stop_all' in request.POST:
            supervisor.supervisor.stopAllProcesses()
            return HttpResponse(json.dumps("ok"),
                                content_type='application/json')
        program = "{}:{}".format(request.POST['group'], request.POST['program'])
        if 'action_start' in request.POST:
            supervisor.supervisor.startProcess(program)
        elif 'action_stop' in request.POST:
            supervisor.supervisor.stopProcess(program)
        elif 'action_restart' in request.POST:
            supervisor.supervisor.stopProcess(program)
            supervisor.supervisor.startProcess(program)

    finally:
        supervisor("close")()
    return redirect(settings.SITE_ROOT) 
Example 5
Project: healthchecks   Author: healthchecks   File: settelegramwebhook.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def handle(self, *args, **options):
        if settings.TELEGRAM_TOKEN is None:
            return "Abort: settings.TELEGRAM_TOKEN is not set"

        form = {
            "url": settings.SITE_ROOT + reverse("hc-telegram-webhook"),
            "allowed_updates": ["message"],
        }

        url = SETWEBHOOK_TMPL % settings.TELEGRAM_TOKEN
        r = requests.post(url, json=form)

        if r.status_code != 200:
            return "Fail: status=%d, %s" % (r.status_code, r.content)

        return "Done, Telegram's webhook set to: %s" % form["url"] 
Example 6
Project: healthchecks   Author: healthchecks   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def add_discord(request, code):
    project = _get_project_for_user(request, code)
    redirect_uri = settings.SITE_ROOT + reverse("hc-add-discord-complete")
    state = token_urlsafe()
    auth_url = "https://discordapp.com/api/oauth2/authorize?" + urlencode(
        {
            "client_id": settings.DISCORD_CLIENT_ID,
            "scope": "webhook.incoming",
            "redirect_uri": redirect_uri,
            "response_type": "code",
            "state": state,
        }
    )

    ctx = {"page": "channels", "project": project, "authorize_url": auth_url}

    request.session["add_discord"] = (state, str(project.code))
    return render(request, "integrations/add_discord.html", ctx) 
Example 7
Project: rocket-league-replays   Author: rocket-league-replays   File: update_patreon_tokens.py    License: GNU General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        r = requests.post('http://api.patreon.com/oauth2/token', data={
            'grant_type': 'refresh_token',
            'refresh_token': os.getenv('PATREON_REFRESH_TOKEN'),
            'client_id': os.getenv('PATREON_CLIENT_ID'),
            'client_secret': os.getenv('PATREON_CLIENT_SECRET'),
        })

        tokens = r.json()

        print(tokens)

        if 'error' in tokens:
            exit()

        with open(os.path.join(settings.SITE_ROOT, 'settings/secrets.py'), 'r') as f:
            settings_data = f.read()

        settings_data = settings_data.replace(os.getenv('PATREON_REFRESH_TOKEN'), tokens['refresh_token'])
        settings_data = settings_data.replace(os.getenv('PATREON_ACCESS_TOKEN'), tokens['access_token'])

        print(settings_data)

        with open(os.path.join(settings.SITE_ROOT, 'settings/secrets.py'), 'w') as f:
            f.write(settings_data) 
Example 8
Project: opencraft   Author: open-craft   File: openedx_appserver.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def enable_bulk_emails_playbook(self):
        """
        Return a Playbook instance for enabling the Bulk Email feature.
        """
        return Playbook(
            version=None,
            source_repo=os.path.join(settings.SITE_ROOT, 'playbooks/enable_bulk_emails'),
            requirements_path='requirements.txt',
            playbook_path='enable_bulk_emails.yml',
            variables='{}',
        ) 
Example 9
Project: suponoff   Author: GambitResearch   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_index_template_data():
    metadata, tags_config, taggroups_dict = _get_metadata_conf()
    services_by_host = _get_data({}, metadata)

    all_tags = set()
    for server_data in services_by_host.values():
        for group in server_data.values():
            all_tags.update(group['tags'])

    tags_by_group = defaultdict(set)
    for tag_name in all_tags:
        tag = tags_config[tag_name]
        tags_by_group[tag.taggroup].add(tag_name)
    taggroups = []
    for name, tags in sorted(tags_by_group.items()):
        taggroups.append((taggroups_dict[name].label, sorted(tags)))

    # sort everything
    data = []
    for server, groups in sorted(services_by_host.items()):
        data.append((server, sorted(groups.items())))

    context = {
        "data": data,
        "taggroups": taggroups,
        'tags_config': tags_config,
        "SITE_ROOT": settings.SITE_ROOT,
    }
    return context 
Example 10
Project: healthchecks   Author: healthchecks   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def notifications_url(self):
        return settings.SITE_ROOT + reverse("hc-notifications") 
Example 11
Project: healthchecks   Author: healthchecks   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def reports_unsub_url(self):
        signer = TimestampSigner(salt="reports")
        signed_username = signer.sign(self.user.username)
        path = reverse("hc-unsubscribe-reports", args=[signed_username])
        return settings.SITE_ROOT + path 
Example 12
Project: healthchecks   Author: healthchecks   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_instant_login_link(self, inviting_project=None, redirect_url=None):
        token = self.prepare_token("login")
        path = reverse("hc-check-token", args=[self.user.username, token])
        if redirect_url:
            path += "?next=%s" % redirect_url

        ctx = {
            "button_text": "Sign In",
            "button_url": settings.SITE_ROOT + path,
            "inviting_project": inviting_project,
        }
        emails.login(self.user.email, ctx) 
Example 13
Project: healthchecks   Author: healthchecks   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_transfer_request(self, project):
        token = self.prepare_token("login")
        settings_path = reverse("hc-project-settings", args=[project.code])
        path = reverse("hc-check-token", args=[self.user.username, token])
        path += "?next=%s" % settings_path

        ctx = {
            "button_text": "Project Settings",
            "button_url": settings.SITE_ROOT + path,
            "project": project,
        }
        emails.transfer_request(self.user.email, ctx) 
Example 14
Project: healthchecks   Author: healthchecks   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_set_password_link(self):
        token = self.prepare_token("set-password")
        path = reverse("hc-set-password", args=[token])
        ctx = {"button_text": "Set Password", "button_url": settings.SITE_ROOT + path}
        emails.set_password(self.user.email, ctx) 
Example 15
Project: healthchecks   Author: healthchecks   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_sms_limit_notice(self, transport):
        ctx = {"transport": transport, "limit": self.sms_limit}
        if self.sms_limit != 500 and settings.USE_PAYMENTS:
            ctx["url"] = settings.SITE_ROOT + reverse("hc-pricing")

        emails.sms_limit(self.user.email, ctx) 
Example 16
Project: healthchecks   Author: healthchecks   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def details_url(self):
        return settings.SITE_ROOT + reverse("hc-details", args=[self.code]) 
Example 17
Project: healthchecks   Author: healthchecks   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def to_dict(self, readonly=False):

        result = {
            "name": self.name,
            "tags": self.tags,
            "desc": self.desc,
            "grace": int(self.grace.total_seconds()),
            "n_pings": self.n_pings,
            "status": self.get_status(with_started=True),
            "last_ping": isostring(self.last_ping),
            "next_ping": isostring(self.get_grace_start()),
            "manual_resume": self.manual_resume,
        }

        if self.last_duration:
            result["last_duration"] = int(self.last_duration.total_seconds())

        if readonly:
            result["unique_key"] = self.unique_key
        else:
            update_rel_url = reverse("hc-api-single", args=[self.code])
            pause_rel_url = reverse("hc-api-pause", args=[self.code])

            result["ping_url"] = self.url()
            result["update_url"] = settings.SITE_ROOT + update_rel_url
            result["pause_url"] = settings.SITE_ROOT + pause_rel_url
            result["channels"] = self.channels_str()

        if self.kind == "simple":
            result["timeout"] = int(self.timeout.total_seconds())
        elif self.kind == "cron":
            result["schedule"] = self.schedule
            result["tz"] = self.tz

        return result 
Example 18
Project: healthchecks   Author: healthchecks   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_verify_link(self):
        args = [self.code, self.make_token()]
        verify_link = reverse("hc-verify-email", args=args)
        verify_link = settings.SITE_ROOT + verify_link
        emails.verify_email(self.email_value, {"verify_link": verify_link}) 
Example 19
Project: healthchecks   Author: healthchecks   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_unsub_link(self):
        signer = TimestampSigner(salt="alerts")
        signed_token = signer.sign(self.make_token())
        args = [self.code, signed_token]
        verify_link = reverse("hc-unsubscribe-alerts", args=args)
        return settings.SITE_ROOT + verify_link 
Example 20
Project: healthchecks   Author: healthchecks   File: transports.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def notify(self, check):
        url = self.channel.value
        headers = {"Conent-Type": "application/json"}
        payload = {
            "incident_key": str(check.code),
            "event_type": "trigger" if check.status == "down" else "resolve",
            "title": tmpl("pagertree_title.html", check=check),
            "description": tmpl("pagertree_description.html", check=check),
            "client": settings.SITE_NAME,
            "client_url": settings.SITE_ROOT,
            "tags": ",".join(check.tags_list()),
        }

        return self.post(url, json=payload, headers=headers) 
Example 21
Project: healthchecks   Author: healthchecks   File: test_list_checks.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_it_works(self):
        r = self.get()
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r["Access-Control-Allow-Origin"], "*")

        doc = r.json()
        self.assertEqual(len(doc["checks"]), 2)

        by_name = {}
        for check in doc["checks"]:
            by_name[check["name"]] = check

        a1 = by_name["Alice 1"]
        self.assertEqual(a1["timeout"], 3600)
        self.assertEqual(a1["grace"], 900)
        self.assertEqual(a1["ping_url"], self.a1.url())
        self.assertEqual(a1["last_ping"], None)
        self.assertEqual(a1["n_pings"], 0)
        self.assertEqual(a1["status"], "new")
        self.assertEqual(a1["channels"], str(self.c1.code))
        self.assertEqual(a1["desc"], "This is description")

        update_url = settings.SITE_ROOT + "/api/v1/checks/%s" % self.a1.code
        pause_url = update_url + "/pause"
        self.assertEqual(a1["update_url"], update_url)
        self.assertEqual(a1["pause_url"], pause_url)

        self.assertEqual(a1["next_ping"], None)

        a2 = by_name["Alice 2"]
        self.assertEqual(a2["timeout"], 86400)
        self.assertEqual(a2["grace"], 3600)
        self.assertEqual(a2["ping_url"], self.a2.url())
        self.assertEqual(a2["status"], "up")
        next_ping = self.now + td(seconds=86400)
        self.assertEqual(a2["last_ping"], self.now.isoformat())
        self.assertEqual(a2["next_ping"], next_ping.isoformat()) 
Example 22
Project: healthchecks   Author: healthchecks   File: views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def serve_doc(request, doc="introduction"):
    path = os.path.join(settings.BASE_DIR, "templates/docs", doc + ".html")
    if not os.path.exists(path):
        raise Http404("not found")

    replaces = {
        "{{ default_timeout }}": str(int(DEFAULT_TIMEOUT.total_seconds())),
        "{{ default_grace }}": str(int(DEFAULT_GRACE.total_seconds())),
        "SITE_NAME": settings.SITE_NAME,
        "SITE_ROOT": settings.SITE_ROOT,
        "SITE_HOSTNAME": site_hostname(),
        "SITE_SCHEME": site_scheme(),
        "PING_ENDPOINT": settings.PING_ENDPOINT,
        "PING_URL": settings.PING_ENDPOINT + "your-uuid-here",
        "IMG_URL": os.path.join(settings.STATIC_URL, "img/docs"),
    }

    content = open(path, "r", encoding="utf-8").read()
    for placeholder, value in replaces.items():
        content = content.replace(placeholder, value)

    ctx = {
        "page": "docs",
        "section": doc,
        "content": content,
        "first_line": content.split("\n")[0],
    }

    return render(request, "front/docs_single.html", ctx) 
Example 23
Project: healthchecks   Author: healthchecks   File: views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_pdc(request, code):
    project = _get_project_for_user(request, code)

    state = token_urlsafe()
    callback = settings.SITE_ROOT + reverse(
        "hc-add-pdc-complete", args=[project.code, state]
    )
    connect_url = "https://connect.pagerduty.com/connect?" + urlencode(
        {"vendor": settings.PD_VENDOR_KEY, "callback": callback}
    )

    ctx = {"page": "channels", "project": project, "connect_url": connect_url}
    request.session["pd"] = state
    return render(request, "integrations/add_pdc.html", ctx) 
Example 24
Project: healthchecks   Author: healthchecks   File: views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_discord_complete(request):
    if "add_discord" not in request.session:
        return HttpResponseForbidden()

    state, code = request.session.pop("add_discord")
    project = _get_project_for_user(request, code)

    if request.GET.get("error") == "access_denied":
        messages.warning(request, "Discord setup was cancelled.")
        return redirect("hc-p-channels", project.code)

    if request.GET.get("state") != state:
        return HttpResponseForbidden()

    redirect_uri = settings.SITE_ROOT + reverse("hc-add-discord-complete")
    result = requests.post(
        "https://discordapp.com/api/oauth2/token",
        {
            "client_id": settings.DISCORD_CLIENT_ID,
            "client_secret": settings.DISCORD_CLIENT_SECRET,
            "code": request.GET.get("code"),
            "grant_type": "authorization_code",
            "redirect_uri": redirect_uri,
        },
    )

    doc = result.json()
    if "access_token" in doc:
        channel = Channel(kind="discord", project=project)
        channel.value = result.text
        channel.save()
        channel.assign_all_checks()
        messages.success(request, "The Discord integration has been added!")
    else:
        messages.warning(request, "Something went wrong.")

    return redirect("hc-p-channels", project.code) 
Example 25
Project: healthchecks   Author: healthchecks   File: views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_trello(request, code):
    project = _get_project_for_user(request, code)
    if request.method == "POST":
        channel = Channel(project=project, kind="trello")
        channel.value = request.POST["settings"]
        channel.save()

        channel.assign_all_checks()
        return redirect("hc-p-channels", project.code)

    return_url = settings.SITE_ROOT + reverse("hc-add-trello", args=[project.code])
    authorize_url = "https://trello.com/1/authorize?" + urlencode(
        {
            "expiration": "never",
            "name": settings.SITE_NAME,
            "scope": "read,write",
            "response_type": "token",
            "key": settings.TRELLO_APP_KEY,
            "return_url": return_url,
        }
    )

    ctx = {
        "page": "channels",
        "project": project,
        "authorize_url": authorize_url,
    }

    return render(request, "integrations/add_trello.html", ctx) 
Example 26
Project: healthchecks   Author: healthchecks   File: hc_extras.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def site_scheme():
    parts = settings.SITE_ROOT.split("://")
    assert parts[0] in ("http", "https")
    return parts[0] 
Example 27
Project: healthchecks   Author: healthchecks   File: hc_extras.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def site_hostname():
    parts = settings.SITE_ROOT.split("://")
    return parts[1] 
Example 28
Project: healthchecks   Author: healthchecks   File: badges.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_badge_url(username, tag, fmt="svg"):
    sig = base64_hmac(str(username), tag, settings.SECRET_KEY)

    if tag == "*":
        url = reverse("hc-badge-all", args=[username, sig[:8], fmt])
    else:
        url = reverse("hc-badge", args=[username, sig[:8], tag, fmt])

    return settings.SITE_ROOT + url 
Example 29
Project: rocket-league-replays   Author: rocket-league-replays   File: test_parser.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _save_replay(self, replay_id):
        base_dir = os.path.join(settings.SITE_ROOT, 'apps/replays/tests/replays')

        with open(os.path.join(base_dir, '{}.replay'.format(replay_id)), 'rb') as f:
            # Test the standard header
            r = Replay.objects.create(
                file=File(f),
            )

            # Test parsing the netstream
            r.save(parse_netstream=True)