Пример #1
0
def post_doc():
    try:
        req = "\r\n".join(
            ["{}={}".format(k, v) for k, v in request.form.items()])
        app.logger.info("DOC_FORM\r\n%s", req)
    except:
        app.logger.info("DOC_FORM %s", str(request.form))

    doc_api_key = request.form['doc_api_key']
    doc_api_url = request.form['doc_api_url']
    doc_api_path = request.form['doc_api_path']
    document_id = request.form['document_id']
    doc_filename = request.form['doc_filename']
    document_body = request.form['document_body']

    method = "POST"
    url = doc_api_url + doc_api_path

    if document_id:
        url += '/' + document_id

    try:
        session = Session()
        login_pass = tuple(doc_api_key.split(':', 1))
        session.auth = BasicAuth(*login_pass)
        kw = {}

        if 'upload' in doc_api_path:
            doc_mimetype, _ = guess_type(doc_filename)
            kw['files'] = {'file': (doc_filename, document_body, doc_mimetype)}
        else:
            kw['data'] = {
                'hash': "md5:{}".format(md5(document_body).hexdigest())
            }

        app.logger.info("{} {} {}".format(method, url, kw))

        resp = session.request(method, url, **kw)
    except Exception as e:
        app.logger.exception(e)
        return jsonify(exception=str(e))

    try:
        hdrs = "\r\n".join(
            ["{}: {}".format(k, v) for k, v in resp.headers.items()])
        hdrs = "{} {}\r\n\r\n{}\r\n\r\n".format(resp.status_code, resp.reason,
                                                hdrs)
        response = hdrs + resp.text
        data = json.loads(resp.text)
        text = json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True)
        response = hdrs + text
    except Exception as e:
        app.logger.exception("Exception due response processing {}".format(e))

    app.logger.info("RESP %s", response)

    return response
Пример #2
0
    def __init__(self, login_pass=None, headers=None, user_agent=None):
        self.headers = headers or {}
        self.session = Session()
        if login_pass is not None:
            self.session.auth = BasicAuth(*login_pass)

        if user_agent is None:
            self.session.headers['User-Agent'] \
                = 'op.client/{}'.format(uuid.uuid4().hex)
        else:
            self.session.headers['User-Agent'] = user_agent
def get_auth_token(ENV: Dict[AnyStr, Any]) -> AnyStr:
    """Generates Auth Token for DNAC

    Parameters
    ----------
    ENV : Dict[AnyStr, Any]
        Environment variables

    Returns
    -------
    AnyStr
        Auth token

    Raises
    ------
    SystemExit
        ConnectionError, HTTPError
    SystemExit
        KeyboardInterrupt
    """
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
    }

    try:
        cprint(text="Generating auth token...", color="magenta")
        response = requests.post(
            url=f"{ENV['BASE_URL']}/dna/system/api/v1/auth/token",
            auth=BasicAuth(username=ENV["USERNAME"], password=ENV["PASSWORD"]),
            headers=headers,
            data=None,
            verify=bool(strtobool(val=ENV["SSL_CERTIFICATE"])),
        )

        response.raise_for_status()
    except (ConnectionError, HTTPError) as e:
        raise SystemExit(colored(text=e, color="red"))
    except KeyboardInterrupt:
        raise SystemExit(
            colored(text="Process interrupted by the user", color="yellow"))
    else:
        cprint(text="Successful Token Generation.\n", color="green")
        return response.json()["Token"]
Пример #4
0
import requests
from requests.auth import HTTPBasicAuth as BasicAuth

# CONSTNATS
BASE_URL = "https://sandboxdnac2.cisco.com"
USERNAME = "******"
PASSWORD = "******"
VERIFY = True  # Set to True in Case of Cisco Sandbox ONLY

# Input
headers = {
    "Content-Type": "application/json",
    "Accept": "application/json",
}

# Processing (Using try and except to handle any HTTP Error)
try:
    r = requests.post(
        url=f"{BASE_URL}/dna/system/api/v1/auth/token",
        headers=headers,
        auth=BasicAuth(USERNAME, PASSWORD),
        verify=VERIFY,
    )
    r.raise_for_status()
except Exception as ex:
    raise SystemExit(ex)

# Output
print(r.json(), type(r.json()))
Пример #5
0
def post_api():
    try:
        req = "\r\n".join(
            ["{}={}".format(k, v) for k, v in request.form.items()])
        app.logger.info("FORM\r\n%s", req)
    except:
        app.logger.info("FORM %s", str(request.form))

    method = request.form['method']
    api_key = request.form['api_key']
    api_url = request.form['api_url']
    path_url = request.form['path_url']
    acc_token = request.form['acc_token']
    json_text = request.form['editor']

    url = api_url + path_url

    match_version = re.match(r'/api/(\d[\d\.]*)/', path_url)
    api_version = match_version.group(1) if match_version else '2.3'

    try:
        session = Session()
        login_pass = (api_key, '')
        session.auth = BasicAuth(*login_pass)
        response = session.request(
            'HEAD', '{}/api/{}/spore'.format(api_url, api_version))
        response.raise_for_status()

        headers = {}
        if acc_token:
            headers['X-Access-Token'] = acc_token

        kw = {'headers': headers}

        if method != 'GET':
            tender = json.loads(json_text)
            prepare_tender(tender)
            kw['json'] = tender

        app.logger.info("{} {} {}".format(method, url, kw))

        resp = session.request(method, url, **kw)
    except Exception as e:
        app.logger.exception(e)
        return jsonify(exception=str(e))

    try:
        hdrs = "\r\n".join(
            ["{}: {}".format(k, v) for k, v in resp.headers.items()])
        hdrs = "{} {}\r\n\r\n{}\r\n\r\n".format(resp.status_code, resp.reason,
                                                hdrs)
        response = hdrs + resp.text
        data = json.loads(resp.text)
        text = json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True)
        response = hdrs + text
    except Exception as e:
        app.logger.exception("Exception due response processing {}".format(e))

    app.logger.info("RESP %s", response)

    return response