def value_to_db_ipaddress(self, value): if value: return Inet(value) return None
def adapt_ipaddressfield_value(self, value): if value: return Inet(value) return None
async def _store_path(self, p: SanePath) -> Prefix: p_dic = dict(p) # Obtain AS name via in-memory cache, database cache, or DNS lookup await self.get_as_name(p.source_asn) asn_id = p.source_asn communities = list(p_dic['communities']) del p_dic['family'] del p_dic['source_asn'] del p_dic['first_hop'] del p_dic['communities'] for x, nh in enumerate(p_dic['next_hops']): p_dic['next_hops'][x] = Inet(nh) async with self.pg_pool.acquire() as conn: pfx = await conn.fetchrow( "SELECT * FROM prefix WHERE asn_id = $1 AND prefix.prefix = $2 LIMIT 1;", asn_id, p_dic['prefix']) # type: Record # pfx = Prefix.query.filter_by(source_asn=asn_id, prefix=p_dic['prefix']).first() # type: Prefix # new_pfx = dict(**p_dic, asn_id=asn_id, last_seen=datetime.utcnow()) age = convert_datetime(p_dic.get('age'), fail_empty=False, if_empty=None) if age is not None: age = age.replace(tzinfo=None) if not pfx: await conn.execute( "INSERT INTO prefix (" " asn_id, asn_path, prefix, next_hops, neighbor, ixp, last_seen, " " age, created_at, updated_at" ")" "VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10);", asn_id, p_dic.get('asn_path', []), p_dic['prefix'], p_dic.get('next_hops', []), p_dic.get('neighbor'), p_dic.get('ixp'), datetime.utcnow(), age, datetime.utcnow(), datetime.utcnow()) pfx = await conn.fetchrow( "SELECT * FROM prefix WHERE asn_id = $1 AND prefix.prefix = $2 LIMIT 1;", asn_id, p_dic['prefix']) else: await conn.execute( "UPDATE prefix SET asn_path = $1, next_hops = $2, neighbor = $3, ixp = $4, last_seen = $5, " "age = $6, updated_at = $7 WHERE prefix = $8 AND asn_id = $9;", p_dic.get('asn_path', []), p_dic.get('next_hops', []), p_dic.get('neighbor'), p_dic.get('ixp'), datetime.utcnow(), age, datetime.utcnow(), p_dic['prefix'], asn_id) # for k, v in p_dic.items(): # setattr(pfx, k, v) for c in communities: # type: LargeCommunity if c not in self._cache['community_in_db']: try: await conn.execute( "insert into community (id, created_at, updated_at) values ($1, $2, $2);", c, datetime.utcnow()) except asyncpg.UniqueViolationError: pass try: await conn.execute( "insert into prefix_communities (prefix_id, community_id) values ($1, $2);", pfx['id'], c) except asyncpg.UniqueViolationError: pass # pfx.communities.append(comm) return pfx