コード例 #1
0
 def setUp(self):
     self.api = fastly.API()
     self.host = os.environ.get('FASTLY_SERVICE_HOST', 'test.com')
     self.service_id = os.environ.get('FASTLY_SERVICE_ID', 'test.com')
     self.api_key = os.environ.get('FASTLY_API_KEY', 'TESTAPIKEY')
     self.user = os.environ.get('FASTLY_USER', '*****@*****.**')
     self.password = os.environ.get('FASTLY_PASSWORD', 'password')
コード例 #2
0
 def __init__(self, env):
     '''
     Connect & auth to the Fastly API
     '''
     try:
         self.api = fastly.API(timeout=15)
         self.api.authenticate_by_key(env.apikey)
     except BaseException:
         exit('Error: could not connect & auth to Fastly API')
コード例 #3
0
def purge_service():
    if len(sys.argv) < 3:
        print "not enough arguments!"
        exit()
    else:
        auth_key = sys.argv[1]
        svc_key = sys.argv[2]

    api = fastly.API()
    api.authenticate_by_key(auth_key)
    api.purge_service(svc_key)
コード例 #4
0
ファイル: purge_url.py プロジェクト: jonathanchu/fastly-py
def purge_url():
    if len(sys.argv) < 4:
        print "not enough arguments!"
        exit()
    else:
        auth_key = sys.argv[1]
        url_host = sys.argv[2]
        url_path = sys.argv[3]

    api = fastly.API()
    api.authenticate_by_key(auth_key)
    api.purge_url(url_host, url_path)
コード例 #5
0
def fastly_list():
    logger.debug("Getting configs...")
    # Set environment variables fastly needs from config file
    config = configparser.ConfigParser()
    CONFIG_FILE = 'fastly.cfg'
    try:
        config.read(CONFIG_FILE)
    except (IOError, OSError):
        logger.info('Config File not found or not readable!')
        quit()

    fastly_user = config.get('FASTLY', 'FASTLY_USER')
    os.environ['FASTLY_USER'] = fastly_user
    fastly_api_key = config.get('FASTLY', 'FASTLY_API_KEY')
    fastly_host = config.get('FASTLY', 'FASTLY_HOST')
    os.environ['FASTLY_HOST'] = fastly_host
    fastly_secure = config.get('FASTLY', 'FASTLY_SECURE')
    os.environ['FASTLY_SECURE'] = fastly_secure
    fastly_password = config.get('FASTLY', 'FASTLY_PASSWORD')
    os.environ['FASTLY_PASSWORD'] = fastly_password

    # login
    api = fastly.API()
    api.authenticate_by_key(fastly_api_key)

    # list services
    services_list = api.services()
    print("List of current services:")
    count = 0
    for service in services_list:
        svc = vars(service)['_original_attrs']
        print(f"{count}: {svc['name']} [{svc['id']}] Version {svc['version']}")
        # list backends
        backends = api.backends(svc['id'], svc['version'])
        print(f"Number of Backends: {len(backends)}")
        for backend in backends:
            backend_vars = vars(backend)
            print(f"Backend: {backend_vars['_original_attrs']['hostname']}")
        count += 1
コード例 #6
0
def fastly_add(**kwargs):
    logger.debug("Getting configs...")
    # Set environment variables fastly needs from config file
    config = configparser.ConfigParser()
    CONFIG_FILE = 'fastly.cfg'
    try:
        config.read(CONFIG_FILE)
    except (IOError, OSError):
        logger.info('Config File not found or not readable!')
        quit()

    fastly_user = config.get('FASTLY', 'FASTLY_USER')
    os.environ['FASTLY_USER'] = fastly_user
    fastly_api_key = config.get('FASTLY', 'FASTLY_API_KEY')
    fastly_host = config.get('FASTLY', 'FASTLY_HOST')
    os.environ['FASTLY_HOST'] = fastly_host
    fastly_secure = config.get('FASTLY', 'FASTLY_SECURE')
    os.environ['FASTLY_SECURE'] = fastly_secure
    fastly_password = config.get('FASTLY', 'FASTLY_PASSWORD')
    os.environ['FASTLY_PASSWORD'] = fastly_password

    # login
    api = fastly.API()
    api.authenticate_by_key(fastly_api_key)

    # list services
    services_list = api.services()
    print("List of current services:")
    count = 0
    for service in services_list:
        svc = vars(service)['_original_attrs']
        print(f"{count}: {svc['name']} [{svc['id']}] Version {svc['version']}")
        # list backends
        backends = api.backends(svc['id'], svc['version'])
        print(f"Number of Backends: {len(backends)}")
        for backend in backends:
            backend_vars = vars(backend)
            print(f"Backend: {backend_vars['_original_attrs']['hostname']}")
        count += 1
    domain = kwargs['domain']
    service_target = input(f"Service to add {domain} to?")
    fastly_subdomain = domain[0:5] + '1'
    fastly_domain_confirm = input(
        f"Fastly subdomain ({fastly_subdomain}.global.ssl.fastly.net)?")
    if fastly_domain_confirm:
        fastly_subdomain = fastly_domain_confirm
    fastly_domain = fastly_subdomain + '.global.ssl.fastly.net'
    # Clone version
    target_service = services_list[int(service_target)]
    target_service_vars = vars(
        services_list[int(service_target)])['_original_attrs']
    version = api.version(target_service_vars['id'],
                          target_service_vars['version'])
    new_version = int(target_service_vars['version']) + 1
    clone = input("Need to clone a new version (y/N)?")
    if clone.lower() == 'y':
        logger.debug("Cloning version...")
        version.clone()

    # Domain
    domain_add = input("Need to add a new domain (y/N)?")
    if domain_add.lower() == 'y':
        version = api.version(target_service_vars['id'], new_version)
        comment = input("Any comment?")
        version.domain(fastly_domain, comment)

    # Condition
    condition_add = input("Need to add a new condition (y/N)?")
    if condition_add.lower() == 'y':
        # Get the version object
        version = api.version(target_service_vars['id'], new_version)
        # add new condition
        condition_name = fastly_subdomain
        cond_statement = 'req.http.host ~ "' + fastly_domain + '"'
        logger.debug("Saving condition...")
        version.condition(name=condition_name,
                          statement=cond_statement,
                          type='REQUEST')
    else:
        condition_name = input(
            f"Name of current condition for {fastly_domain}?")
    # Header
    header_add = input("Need to add a new header (y/N)?")
    if header_add.lower() == 'y':
        version = api.version(target_service_vars['id'], new_version)
        header_name = fastly_subdomain
        src = '"' + domain + '"'
        version.header(name=header_name,
                       type='REQUEST',
                       dst='http.Host',
                       src=src,
                       priority='10',
                       request_condition=condition_name)

    # Backend
    backend_add = input("Need a new origin (y/N)?")
    if backend_add.lower() == 'y':
        version = api.version(target_service_vars['id'], new_version)
        origin_name = fastly_subdomain
        version.backend(name=origin_name,
                        hostname=domain,
                        port='443',
                        request_condition=condition_name,
                        ssl_check_cert='false')
    activate_version = input(f"Activate new version (y/N)?")
    if activate_version.lower() == 'y':
        logger.debug("Activating new version!")
        version = api.version(target_service_vars['id'], new_version)
        version.activate()

    return fastly_domain
コード例 #7
0
import logging
import urlparse

import requests
from django.conf import settings
from wagtail.contrib.wagtailfrontendcache.backends import HTTPBackend

import fastly

logger = logging.getLogger(__name__)

FASTLY_API_KEY = settings.FASTLY_API_KEY
FASTLY_SERVICE_ID = settings.FASTLY_SERVICE_ID

fastly_api = fastly.API()
fastly_api.authenticate_by_key(FASTLY_API_KEY)


class FastlyBackend(HTTPBackend):
    def __init__(self, params):
        self.api_key = params.pop('API_KEY')
        self.hosts = params.pop('HOSTS')

    def get_surrogate_key_for_url(self, url):
        """Get path from url"""
        path = urlparse.urlparse(url).path
        """Strip trailing slash unless homepage"""
        if path != "/":
            surrogate_key = path.rstrip('/')
        else:
コード例 #8
0
 def setUp(self):
     self.api = fastly.API()  #host='127.0.0.1', port=5500, secure=False)
コード例 #9
0
def purge_cdn(domain, path):
    print("Purging cache for " + domain + path)
    fastly_client = fastly.API()
    fastly_client.authenticate_by_key(os.environ.get('FASTLY_API_KEY'))
    fastly_client.purge_url(domain, path)
コード例 #10
0
 def handle_noargs(self, **options):
     key = settings.FASTLY_CACHE_API_KEY
     if key:
         self.api = fastly.API()
         self.api.authenticate_by_key(key)
         self.purge_all()