Почему выход не генерируется из этой функции? - PullRequest
0 голосов
/ 20 февраля 2020

У меня есть функция python и я sh, чтобы выполнить это с помощью функции обработчика lambda, поэтому я написал этот код. Когда я выполняю в Pycharm, я не вижу никакого вывода в консоли. Может кто-нибудь подсказать в чем проблема с приведенным ниже кодом?

import json
from json import loads

import requests
from requests import exceptions
from requests.auth import HTTPBasicAuth


def lambda_handler(event, context):
    test_post_headers_body_json()
    return {"statusCode": 200, "body": json.dumps("Hello from Lambda!")}


def test_post_headers_body_json():
    client_id = "WJRYDHNGROIZHL8B"
    client_secret = "V5VXK6FLG1YI0GD2XY3H"
    user = "automation-store-admin1@abc.com"


    password = "c0Ba5PBdvVl2"

    access_point = "https://api.platform.abc.com/auth/oauth/token"
    grant_type = "password"

    headers = {"Content-Type": "application/x-www-form-urlencoded"}

    # auth = auth.HTTPBasicAuth(client_id, client_secret)

    data = {"grant_type": grant_type, "username": user, "password": password}

    resp = None
    try:
        resp = requests.post(
            access_point,
            auth=HTTPBasicAuth(client_id, client_secret),
            data=data,
            headers=headers,
        )
    except exceptions.ConnectionError:
        exit(1)

    if resp.status_code == 200:
        resp = loads(resp.text)
        if "access_token" in resp:
            print(resp["access_token"])
            exit(0)

    exit(1)

1 Ответ

0 голосов
/ 20 февраля 2020

Это нормально, потому что при запуске вашего кода, Python объявляет только функцию, не использующую его. Вы должны добавить __main__ точку входа в конце вашего файла:

import json
from json import loads

import requests
from requests import exceptions
from requests.auth import HTTPBasicAuth


def lambda_handler(event, context):
    test_post_headers_body_json()
    return {"statusCode": 200, "body": json.dumps("Hello from Lambda!")}


def test_post_headers_body_json():
    client_id = "WJRYDHNGROIZHL8B"
    client_secret = "V5VXK6FLG1YI0GD2XY3H"
    user = "automation-store-admin1@abc.com"


    password = "c0Ba5PBdvVl2"

    access_point = "https://api.platform.abc.com/auth/oauth/token"
    grant_type = "password"

    headers = {"Content-Type": "application/x-www-form-urlencoded"}

    # auth = auth.HTTPBasicAuth(client_id, client_secret)

    data = {"grant_type": grant_type, "username": user, "password": password}

    resp = None
    try:
        resp = requests.post(
            access_point,
            auth=HTTPBasicAuth(client_id, client_secret),
            data=data,
            headers=headers,
        )
    except exceptions.ConnectionError:
        exit(1)

    if resp.status_code == 200:
        resp = loads(resp.text)
        if "access_token" in resp:
            print(resp["access_token"])
            exit(0)

    exit(1)

# added part
if __name__ == '__main__':
    test_post_headers_body_json()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...