Best Python code snippet using localstack_python
places.py
Source:places.py  
...68            "Keys": [{"Place id ": place_id} for place_id in items]69        }70    }71    try:72        return dynamodb.batch_get_item(RequestItems=RequestItems)["Responses"]["places"]73    except Exception as e:74        return {'message': str(e)}75def add_likedPlace(data):76    place = data["place_id"]77    email = data["email"]78    response = app.get_app_db('users').query(79        KeyConditionExpression=Key('email').eq(data["email"])80    )81    likedPlaces = response.get('Items')[0]["likedPlaces"]82    likedPlaces.append(place)83    response = app.get_app_db('users').update_item(84        Key={85            'email': email,86        },87        UpdateExpression="set likedPlaces=:l",88        ExpressionAttributeValues={89            ':l': likedPlaces90        },91        ReturnValues="UPDATED_NEW"92    )93    return response["Attributes"]["likedPlaces"]94def get_list_likedPlaces(data):95    response = app.get_app_db('users').query(96        KeyConditionExpression=Key('email').eq(data["email"])97    )98    items = response.get('Items')[0]["likedPlaces"]99    RequestItems = {100        "places": {101            "Keys": [{"Place id ": place_id} for place_id in items]102        }103    }104    try:105        return dynamodb.batch_get_item(RequestItems=RequestItems)["Responses"]["places"]106    except Exception as e:107        return {'message': str(e)}108def me_placesAdded(data):109    place = data["place_id"]110    email = data["email"]111    response = app.get_app_db('users').query(112        KeyConditionExpression=Key('email').eq(data["email"])113    )114    placesAdded = response.get('Items')[0]["placesAdded"]115    placesAdded.append(place)116    response = app.get_app_db('users').update_item(117        Key={118            'email': email,119        },120        UpdateExpression="set placesAdded=:l",121        ExpressionAttributeValues={122            ':l': placesAdded123        },124        ReturnValues="UPDATED_NEW"125    )126    return response["Attributes"]["placesAdded"]127def get_me_placesAdded(data):128    response = app.get_app_db('users').query(129        KeyConditionExpression=Key('email').eq(data["email"])130    )131    items = response.get('Items')[0]["placesAdded"]132    RequestItems = {133        "places": {134            "Keys": [{"Place id ": place_id} for place_id in items]135        }136    }137    try:138        return dynamodb.batch_get_item(RequestItems=RequestItems)["Responses"]["places"]139    except Exception as e:140        return {'message': str(e)}141def add_placesVisited(data):142    place = data["place_id"]143    email = data["email"]144    response = app.get_app_db('users').query(145        KeyConditionExpression=Key('email').eq(data["email"])146    )147    visitedPlaces = response.get('Items')[0]["visitedPlaces"]148    visitedPlaces.append(place)149    response = app.get_app_db('users').update_item(150        Key={151            'email': email,152        },153        UpdateExpression="set visitedPlaces=:v",154        ExpressionAttributeValues={155            ':v': visitedPlaces156        },157        ReturnValues="UPDATED_NEW"158    )159    return response["Attributes"]["visitedPlaces"]160def get_list_placesVisited(data):161    response = app.get_app_db('users').query(162        KeyConditionExpression=Key('email').eq(data["email"])163    )164    items = response.get('Items')[0]["visitedPlaces"]165    RequestItems = {166        "places": {167            "Keys": [{"Place id ": place_id} for place_id in items]168        }169    }170    try:171        return dynamodb.batch_get_item(RequestItems=RequestItems)["Responses"]["places"]172    except Exception as e:...dynamodb_getitem_batchgetitem_comparison.py
Source:dynamodb_getitem_batchgetitem_comparison.py  
...16        'max_attempts': 317    }18)19#Execute batch_get_item dynamodb call    20def batch_get_item(FILE_TO_READ,REGION_CONFIG):21    df = pd.DataFrame(columns=['batch_get_item'])22    dynamodb_client = boto3.client('dynamodb', config=REGION_CONFIG) 23    for i in range(0, MAX_RANGE_VALUE):24        random_lines = random.choice(open(FILE_TO_READ).readlines())25        start_timer = time.perf_counter()26        response = dynamodb_client.batch_get_item(RequestItems={'workload':27            {'Keys': [{'uuid': {'S': random_lines.strip()}}]}})28        end_timer = time.perf_counter()29        #print("%s:-:%s" %(response['ResponseMetadata']['HTTPHeaders']['content-length'],response['Responses']['workload'][0]['uuid'])) #print the response size and uuid is in response to validate the response30        df = df.append({'batch_get_item': end_timer-start_timer}, ignore_index=True)31    return df32#Execute get_item dynamodb call   33def get_item(FILE_TO_READ,REGION_CONFIG):34    df = pd.DataFrame(columns=['get_item'])35    dynamodb = boto3.resource('dynamodb', config=REGION_CONFIG)36    table = dynamodb.Table('workload')37    for i in range(0, MAX_RANGE_VALUE):38        random_lines = random.choice(open(FILE_TO_READ).readlines())39        start_timer = time.perf_counter()40        response = table.get_item(Key={'uuid': random_lines.strip()})41        end_timer = time.perf_counter()42        #print("%s:-:%s" %(response['ResponseMetadata']['HTTPHeaders']['content-length'],response['Item']['uuid'])) #print the response size and uuid is in response to validate the response43        df = df.append({'get_item': end_timer-start_timer}, ignore_index=True)44    return df45def generate_stats_graph(RESULT_FILE):46    df = pd.read_csv(RESULT_FILE)47    48        49    fig, axes = plt.subplots(2, 2, figsize=(12, 10), sharey=False)50    51    #generate response time distribution52    kwargs = dict(element='step',shrink=.8, alpha=0.6, fill=True, legend=True) 53    ax = sns.histplot(ax=axes[0,0],data=df,**kwargs)54    #ax.set(xlim=(0.00,1.00)) #set the ylim boundary if auto option is not what you need55    ax.set_title('Response Time Distribution')56    ax.set_xlabel('Response Time (s)')57    ax.set_ylabel('Request Count')58    59    60    #Response Time Distribution using boxplot61    ax = sns.boxplot(ax=axes[0,1], data=df)62    #ax.legend(fontsize='medium')63    #ax.set(ylim=(0.0,1.0)) #set the ylim boundary if auto option is not what you need64    ax.set_title('Response Time Distribution')65    ax.set_xlabel('Operation Type')66    ax.set_ylabel('Response Time (s)')67    68    69    #generate percentile distribution       70    summary = np.round(df.describe(percentiles=[0, 0.1, 0.2,71                                                     0.3, 0.4, 0.5,72                                                     0.6, 0.7, 0.8,  73                                                     0.9, 0.95, 0.99, 1],include='all'),2) # show basic statistics as in row74    stats_summary = summary.copy()75    dropping = ['count', 'mean', 'std', 'min','max'] #remove metrics not needed for percentile graph76    77    for drop in dropping:78        summary = summary.drop(drop)79    ax = sns.lineplot(ax=axes[1,0],data=summary,dashes=False, legend=True)80    ax.legend(fontsize='medium')81    #ax.set(ylim=(0.0,1.0)) #set the ylim boundary if auto option is not what you need82    ax.set_title('Percentile Distribution')83    ax.set_xlabel('Percentile')84    ax.set_ylabel('Response Time (s)')85    86    87    #generate latency/response time basic statistics 88    axes[1, 1].axis("off")89    dropping = ['0%','100%']90    for drop in dropping:91        stats_summary = stats_summary.drop(drop)    92    table_result = axes[1, 1].table(cellText=stats_summary.values,93              rowLabels=stats_summary.index,94              colLabels=stats_summary.columns,95              cellLoc = 'right', rowLoc = 'center',96              loc='upper left')97    table_result.auto_set_font_size(False)98    table_result.set_fontsize(9)99    axes[1, 1].set_title('Response Time Statistics')100    fig.tight_layout(pad=1)101    102def main():103    FILE_TO_READ ='./Data/testdata.csv'  # Replace with your test data file104    RESULT_FILE ="./Data/result-getItem-batchGetItem.csv" #Replace where the result needs to be saved105    df_get = get_item(FILE_TO_READ,REGION_CONFIG)106    df_batch = batch_get_item(FILE_TO_READ,REGION_CONFIG)107    df_col_merged = pd.concat([df_get, df_batch], axis=1)108    #print(df_col_merged.describe(percentiles=[0.25,0.5,0.75,0.90,0.95],include='all'))109    df_col_merged.to_csv(RESULT_FILE,index=False)110    generate_stats_graph(RESULT_FILE)111    112if __name__ == "__main__":113    main()...GetRecommendation.py
Source:GetRecommendation.py  
...15    16def get_recomm(genid):17    ids = [genid]18    keys = [{'userId':  {'S':i}} for i in ids]19    list_of_movie = dynamodb.batch_get_item(RequestItems = {DYNAMODB_TABLE_NAME:{"Keys":keys}})['Responses'][DYNAMODB_TABLE_NAME][0]['movielist']20    list_of_movie = list_of_movie["L"]21    return list_of_movie22def get_moviename(listofid):23    # listofid = ["3635","228"]24    keys = [{"MovieId":  {'S':i}} for i in listofid]25    return dynamodb.batch_get_item(RequestItems = {"MovieRev":{"Keys":keys}})['Responses']["MovieRev"]26    27def datacleaning(response):28    movieid = []29    rank = []30    moviename = []31    for i in range(len(response)):32        movieid.append(response[i]["L"][0]["S"])33        rank.append(response[i]["L"][1]["S"])34    response = get_moviename(movieid)35    for i in range(len(response)):36        moviename.append(response[i]['title']['S'])...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
