You see I have this script
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import pymysql
import ipaddress
red_ipv4 = ipaddress.ip_network('192.168.1.0/24')
for ip in red_ipv4:
try:
conexion = pymysql.connect(host=str(ip),
user='gviera',
password='hola',
db='calificaciones')
try:
with conexion.cursor() as cursor:
for consulta in range(1,11):
consulta = "INSERT INTO pbd2019 VALUES (%s, %s, %s);"
cursor.execute(consulta, ("216411051","Frank Miller", 100))
conexion.commit()
finally:
conexion.close()
except (pymysql.err.OperationalError, pymysql.err.InternalError) as e:
print("Ocurrió un error al conectar: ", e)
If it works but I would like to speed it up since the function of this script is to insert several records in different mysql hosts in a network segment, they had previously told me that with the asynchronous map it could be speeded up but I did not understand how to do it, could you give me a example of how it would look
First of all, Thanks.
Since you are executing the same SQL code on several different hosts without the need for them to interact, there is no need to make these requests sequentially, so as you mentioned, you can take advantage of Python's concurrent / multi-threading features to optimize this code.
Since you have a list of
hostnames
, and you want to execute a function for each element, you can use a map in parallel, in particular I recommend the included library frompython 3.2+
concurrent.futures .The code would look like this: