none처리에 해당하는 글 1

[flask] sqlalchemy로 디비 입력시 None 에러

Computer 관심/Flask|2022. 6. 28. 23:16
반응형

sqlalchemy로 디비에 정보가 none이 들어가게 되면 에러가 발생하게 된다. 

그래서 디비에 들어가는 orm을 만들기 전에 아래처럼 체크를 하여 none이 있으면 다른 값으로 바꾸어서 넣어준다.

그 전에 pandas를 사용할 때는 none을 다른 값으로 바꾸어주는 함수를 사용했는데 

아래의 방법이 더 나은것 같다. 

 

if inflow_product['customFields']['custom8'] == "part" or inflow_product['customFields']['custom8'] == "Part" :
                inflow_product['customFields']['custom8'] = True
            else:
                inflow_product['customFields']['custom8'] = False
            
            # checking none
            name = inflow_product['name']
            description = inflow_product['description'] or 'NO INFO'
            size = inflow_product['customFields']['custom3'] or 'NO INFO'
            if inflow_product['defaultPrice'] is None:
                price = 0
            else:
                price = inflow_product['defaultPrice']['unitPrice'] or 0
            
            if inflow_product['defaultImage'] is None:
                img_url = '/favicon.png'
            else:
                img_url = inflow_product['defaultImage']['originalUrl'] or '/favicon.png'
                
            material=inflow_product['customFields']['custom4'] or 'no info'
            is_part = inflow_product['customFields']['custom8'] or False
            discount_rate = inflow_product['customFields']['custom2'] or 0

            if not product_info:
                print('new product')
                counts['insert'] = counts['insert'] + 1 
                s1 = ProductInfo(article=name.strip(), description=description,size=size,\
                        price=price, img_url=img_url, material =material, is_part=is_part)
                try:
                    s1.online_shop = False
                    s1.discount_rate = discount_rate
                except Exception as e:
                    return(e)
                db.session.add(s1)      
            else:
                print('existing product')
                counts['update'] = counts['update'] + 1
                data_to_update = dict(article = name.strip(), description = description, size=size,\
                        price = price, img_url=img_url, material=material, is_part=is_part)  
                try:
                    data_to_update['discount_rate'] = discount_rate  
                    data_to_update['online_shop'] = product_info.online_shop or False
                    
                except Exception as e:    
                    return(e)
                db.session.query(ProductInfo).filter_by(article=name).update(data_to_update)
            db.session.commit()
반응형

댓글()