pythonaws-lambdasftpparamiko

AWS Lambda: Unable to import module 'python_handler': No module named '_cffi_backend'


I'm creating a AWS Lambda function when I need to read an info on an API, create a CSV file, and upload them on a SFTP server.

I've installed paramiko on my venv, using Ubuntu on Windows, and the cffi module comes like a dependency, but when the code runs, I receive this error:

{
  "errorMessage": "Unable to import module 'python_handler': No module named '_cffi_backend'",
  "errorType": "Runtime.ImportModuleError"
}

Follow my code:

import paramiko
import requests
from random import randrange
from datetime import datetime
from datetime import timedelta
from requests.auth import HTTPBasicAuth


def lambda_handler(event, context):
    # Lambda function
    addZero = lambda x : '0' + str(x) if x < 10 else str(x)

    # Actual datetime
    ac_yr = datetime.utcnow().year
    ac_mo = datetime.utcnow().month
    ac_da = datetime.utcnow().day
    ac_hh = datetime.utcnow().hour
    ac_mi = datetime.utcnow().minute
    ac_se = datetime.utcnow().second

    # 24 hours ago
    ag_yr = (datetime.utcnow() - timedelta(hours=24)).year
    ag_mo = (datetime.utcnow() - timedelta(hours=24)).month
    ag_da = (datetime.utcnow() - timedelta(hours=24)).day
    ag_hh = (datetime.utcnow() - timedelta(hours=24)).hour
    ag_mi = (datetime.utcnow() - timedelta(hours=24)).minute
    ag_se = (datetime.utcnow() - timedelta(hours=24)).second

    # API Infos
    api_key = 'XYZ'
    page_id = 'XYZ'

    # Call API
    param = {
        'sort_order': 'asc',
        'from': '{}-{}-{}T{}:{}:{}.000Z'.format(ag_yr, addZero(ag_mo), addZero(ag_da), addZero(ag_hh), addZero(ag_mi), addZero(ag_se)),
        'to': '{}-{}-{}T{}:{}:{}.000Z'.format(ac_yr, addZero(ac_mo), addZero(ac_da), addZero(ac_hh), addZero(ac_mi), addZero(ac_se))
    }
    r = requests.get('https://api.unbounce.com/pages/{}/leads'.format(page_id), auth=HTTPBasicAuth(api_key, 'pass'), params=param)

    # If connection it's ok
    if r.status_code == 200:
        # If has any result
        if len(r.json()['leads']) > 0:
            cont = ''
            for lead in r.json()['leads']:
                cont += lead['form_data']['cpf'][0] + ','
                cont += lead['form_data']['nome_completo'][0] + ','
                cont += lead['form_data']['email'][0]
        else:
            return 'Não há resultados no momento'
    else:
        return 'Falha na conexão'

    # Write a CSV file
    f = open('my_csv.csv','w')
    f.write('PAC_ID, PAC_NAME, PAC_EMAIL\n')
    f.write(cont)
    f.close()

    transport = paramiko.Transport(('host-info', 22))
    transport.connect(None, 'user-info', 'password-info', None)

    sftp = paramiko.SFTPClient.from_transport(transport)
    sftp.chdir('Import')
    sftpclient.put('my_csv.csv')

    return 'OK'

Any idea how I can solve this?


Solution

  • Working on Ubuntu, I haven't the success with pysftp or paramiko to Lambda. So I created an EC2 instance (and after an VirtualBox with Amazon Linux 2) on my desktop and develop the same code, with the same libraries. And... that's works...