當前位置: 首頁>>代碼示例>>Python>>正文


Python decouple.config方法代碼示例

本文整理匯總了Python中decouple.config方法的典型用法代碼示例。如果您正苦於以下問題:Python decouple.config方法的具體用法?Python decouple.config怎麽用?Python decouple.config使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在decouple的用法示例。


在下文中一共展示了decouple.config方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: configure_device

# 需要導入模塊: import decouple [as 別名]
# 或者: from decouple import config [as 別名]
def configure_device(connection_params, variables):
    device_connection = Device(**connection_params)
    device_connection.open()
    # device_connection.facts_refresh()
    facts = device_connection.facts

    hostname = facts['hostname']

    config_variables = variables['devices'][hostname]

    with Config(device_connection, mode='private') as config:
        config.load(template_path='templates/candidate.conf', template_vars=config_variables, merge=True)
        print("Config diff:")
        config.pdiff()
        config.commit()
        print(f'Configuration was updated successfully on {hostname}')

    device_connection.close() 
開發者ID:dmfigol,項目名稱:network-programmability-stream,代碼行數:20,代碼來源:example.py

示例2: ftp_connect

# 需要導入模塊: import decouple [as 別名]
# 或者: from decouple import config [as 別名]
def ftp_connect(self):
        """
        Tries to connect to FTP server according to env vars:
        * `ALCHEMYDUMPS_FTP_SERVER`
        * `ALCHEMYDUMPS_FTP_USER`
        * `ALCHEMYDUMPS_FTP_PASSWORD`
        * `ALCHEMYDUMPS_FTP_PATH`
        :return: Python FTP class instance or False
        """
        server = decouple.config("ALCHEMYDUMPS_FTP_SERVER", default=None)
        user = decouple.config("ALCHEMYDUMPS_FTP_USER", default=None)
        password = decouple.config("ALCHEMYDUMPS_FTP_PASSWORD", default=None)
        path = decouple.config("ALCHEMYDUMPS_FTP_PATH", default=None)
        if not server or not user:
            return False

        try:
            ftp = ftplib.FTP(server, user, password)
        except ftplib.error_perm:
            click.secho(f"==> Couldn't connect to {server}", fg="red")
            return False

        return self.ftp_change_path(ftp, path) 
開發者ID:cuducos,項目名稱:alchemydumps,代碼行數:25,代碼來源:backup.py

示例3: set_position

# 需要導入模塊: import decouple [as 別名]
# 或者: from decouple import config [as 別名]
def set_position(self, latitude, longitude):
        """ Set the position of the user using Happn's API
            :param latitude Latitude to position the User
            :param longitude Longitude to position the User
        """

        # Create & Send the HTTP Post to Happn server
        h=headers
        h.update({
            'Authorization' : 'OAuth="'+ self.oauth + '"',
            'Content-Length': '342', #@TODO figure out length calculation
            'Content-Type'  : 'application/json'
            })

        url = 'https://api.happn.fr/api/users/' + self.id + '/devices/'+config('DEVICE_ID')
        payload = {
            "alt"       : 20 + random.uniform(-10,10),
            "latitude"  : round(latitude,7),
            "longitude" : round(longitude,7),
        }
        r = requests.put(url,headers=h,data=json.dumps(payload))

        # Check status of Position Update
        if r.status_code == 200:    #OK HTTP status
            self.lat = latitude
            self.lon = longitude
            logging.debug('Set User position at %f, %f', self.lat, self.lon)
        else:
            # Status failed, get the current location according to the server
            #@TODO IMPLEMENT ^
            self.lat = latitude
            self.lon = longitude

            logging.warning("""Server denied request for position change: %s,
                                will revert to server known location""", httpErrors[r.status_code])

            # If unable to change location raise an exception
            raise HTTP_MethodError(httpErrors[r.status_code]) 
開發者ID:rickhousley,項目名稱:happn,代碼行數:40,代碼來源:happn.py

示例4: set_device

# 需要導入模塊: import decouple [as 別名]
# 或者: from decouple import config [as 別名]
def set_device(self):
        """ Set device, necessary for updating position
            :TODO Add params for settings
        """

        # Create and send HTTP PUT to Happn server
        h=headers
        h.update({
          'Authorization'   : 'OAuth="'+ self.oauth + '"',
          'Content-Length'  :  '342', #@TODO figure out length calculation
          'Content-Type'    : 'application/json'})

        # Device specific payload, specific to my phone. @TODO offload to settings file?
        payload ={
            "app_build" : config('APP_BUILD'),
            "country_id": config('COUNTRY_ID'),
            "gps_adid"  : config('GPS_ADID'),
            "idfa"      : config('IDFA'),
            "language_id":"en",
            "os_version": config('OS_VERSION'),
            "token"     : config('GPS_TOKEN'),
            "type"      : config('TYPE')
        }

        url = 'https://api.happn.fr/api/users/' + self.id + '/devices/'+ config('DEVICE_ID')
        try:
            r = requests.post(url,headers=h,data=json.dumps(payload))
        except Exception as e:
            raise HTTP_MethodError('Error Setting Device: {}'.format(e))

        if r.status_code == 200: #200 = 'OK'
            logging.debug('Device Set')
        else:
            # Device set denied by server
            logging.warning('Server denied request for device set change: %d', r.status_code)
            raise HTTP_MethodError(httpErrors[r.status_code]) 
開發者ID:rickhousley,項目名稱:happn,代碼行數:38,代碼來源:happn.py

示例5: create

# 需要導入模塊: import decouple [as 別名]
# 或者: from decouple import config [as 別名]
def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)

        try:
            if serializer.is_valid(raise_exception=True):
                user = serializer.create(request.data)
                jwt_token = {'token': jwt.encode(
                    serializer.data, config('SECRET_KEY'))}
                return Response(jwt_token, status=status.HTTP_201_CREATED)
        except IntegrityError:
            serializer.error_messages = {
                'Error': 'Organization with that username already exists!'}
        return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST) 
開發者ID:JBossOutreach,項目名稱:certificate-generator-server-archive,代碼行數:15,代碼來源:views.py

示例6: form_headers

# 需要導入模塊: import decouple [as 別名]
# 或者: from decouple import config [as 別名]
def form_headers():
    api_token = decouple.config("NETBOX_API_TOKEN")

    headers = {
        "Authorization": "Token {}".format(api_token),
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    return headers 
開發者ID:dmfigol,項目名稱:network-programmability-stream,代碼行數:11,代碼來源:aiohttp_netbox.py

示例7: form_headers

# 需要導入模塊: import decouple [as 別名]
# 或者: from decouple import config [as 別名]
def form_headers():
    api_token = decouple.config("NETBOX_API_TOKEN")
    if api_token is None:
        raise NetboxAPITokenNotFound(
            "NETBOX_API_TOKEN was not found in environmental variables"
        )

    headers = {
        "Authorization": "Token {}".format(api_token),
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    return headers 
開發者ID:dmfigol,項目名稱:network-programmability-stream,代碼行數:15,代碼來源:configure_devices_from_netbox.py

示例8: main

# 需要導入模塊: import decouple [as 別名]
# 或者: from decouple import config [as 別名]
def main():
    params = get_username_password(VAULT_SERVER, decouple.config('VAULT_TOKEN'))
    worker = partial(get_outputs, commands=COMMANDS)
    devices_params = (form_device_params(host, params) for host in HOSTS)
    with ThreadPoolExecutor(2) as pool:
        results = pool.map(worker, devices_params)

    for host, result in zip(HOSTS, results):
        print(f'===== Device: {host} =====')
        for command, output in result.items():
            print(f'=== output from {command!r} ===')
            print(output, end='\n=========\n') 
開發者ID:dmfigol,項目名稱:network-programmability-stream,代碼行數:14,代碼來源:netmiko-vault.py

示例9: set_app

# 需要導入模塊: import decouple [as 別名]
# 或者: from decouple import config [as 別名]
def set_app(self, app, db=False):

        # basic testing vars
        app.config["TESTING"] = True
        app.config["WTF_CSRF_ENABLED"] = False

        # set db for tests
        if db:
            app.config["SQLALCHEMY_DATABASE_URI"] = config(
                "DATABASE_URL_TEST", default="sqlite://"
            )

        # create test app
        test_app = app.test_client()

        # create tables and testing db data
        if db:
            db.create_all()
            db.session.add(self.whisky_1)
            db.session.add(self.whisky_2)
            db.session.commit()
            query_1 = Whisky.query.filter(Whisky.slug == "isleofarran")
            query_2 = Whisky.query.filter(Whisky.slug == "glendeveronmacduff")
            calc_correlation_1 = self.whisky_1.get_correlation(query_2.first())
            calc_correlation_2 = self.whisky_2.get_correlation(query_1.first())
            correlation_1 = Correlation(**calc_correlation_1)
            correlation_2 = Correlation(**calc_correlation_2)
            db.session.add(correlation_1)
            db.session.add(correlation_2)
            db.session.commit()

        # return the text app
        return test_app 
開發者ID:cuducos,項目名稱:whiskyton,代碼行數:35,代碼來源:config.py

示例10: __init__

# 需要導入模塊: import decouple [as 別名]
# 或者: from decouple import config [as 別名]
def __init__(self, cachet_url="", cachet_token="",
                 cachet_components=None):
        self.cachet_url = cachet_url or config('CACHET_URL', default=None)
        self.cachet_token = (cachet_token or
                             config('CACHET_TOKEN', default=None))
        self.cachet_components = (cachet_components or
                                  config('CACHET_COMPONENTS', default=None,
                                         cast=self._components_to_dict)) 
開發者ID:marcopaz,項目名稱:is-service-up,代碼行數:10,代碼來源:cachet.py

示例11: __init__

# 需要導入模塊: import decouple [as 別名]
# 或者: from decouple import config [as 別名]
def __init__(self):
        # Will check if the Weblate website is OK.
        self.check_http = config('WEBLATE_CHECK_HTTP', default=True, cast=bool)
        # Will check if the Weblate JSON API is OK.
        self.check_json = config('WEBLATE_CHECK_JSON', default=True, cast=bool)
        # If you need to monitor multiple Weblate instances and need each one
        # to have a different behaviour: extend this class, override the
        # __init__ function, call super, and then override these properties. 
開發者ID:marcopaz,項目名稱:is-service-up,代碼行數:10,代碼來源:weblate.py

示例12: __init__

# 需要導入模塊: import decouple [as 別名]
# 或者: from decouple import config [as 別名]
def __init__(self):
        # Will check if the GitLab website is OK.
        self.check_http = config('GITLAB_CHECK_HTTP', default=True, cast=bool)
        # Will check if the GitLab JSON API is OK.
        self.check_json = config('GITLAB_CHECK_JSON', default=True, cast=bool)
        # Will check if the SSH connections to git@{gitlab_url} are OK.
        # To use this you need to set the PRIVATE_SSH_KEY option in the config.
        self.check_ssh = config('GITLAB_CHECK_SSH', default=False, cast=bool)
        # If you need to monitor multiple GitLab instances and need each one to
        # have a different behaviour: extend this class, override the __init__
        # function, call super, and then override these properties. 
開發者ID:marcopaz,項目名稱:is-service-up,代碼行數:13,代碼來源:gitlab.py

示例13: github_client

# 需要導入模塊: import decouple [as 別名]
# 或者: from decouple import config [as 別名]
def github_client():
    return Github(client_id=config('GITHUB_CLIENT_ID'),
                  client_secret=config('GITHUB_CLIENT_SECRET')) 
開發者ID:codesy,項目名稱:codesy,代碼行數:5,代碼來源:utils.py

示例14: make_details

# 需要導入模塊: import decouple [as 別名]
# 或者: from decouple import config [as 別名]
def make_details(self):
        details = {'username': "", "password": ""}
        try:
            details['username'] = config('EVENTAPI_TOKEN_USERNAME')
            details['password'] = config('EVENTAPI_TOKEN_PASSWORD')
        except KeyError as k:
            print("Error occured: {!s}".format(k)) 
開發者ID:fresearchgroup,項目名稱:Collaboration-System,代碼行數:9,代碼來源:generateToken.py

示例15: make_details

# 需要導入模塊: import decouple [as 別名]
# 或者: from decouple import config [as 別名]
def make_details(self):
        details = {'username': "", "password": ""}
        try:
            details['username'] = config('EVENTAPI_TOKEN_USERNAME')
            details['password'] = config('EVENTAPI_TOKEN_PASSWORD')
        except KeyError as k:
            print("Error occured: {!s}".format(k))
        return details 
開發者ID:fresearchgroup,項目名稱:Collaboration-System,代碼行數:10,代碼來源:_generateToken.py


注:本文中的decouple.config方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。