def upload_contact(): file = request.files['file'] tags = json.loads(request.form['data']) try: if file: filename = file.filename foldertemp = os.path.join( UPLOAD_FOLDER, 'contacts') if os.path.exists(foldertemp): filetemp = os.path.join( foldertemp, filename) file.save(filetemp) else: os.makedirs(foldertemp) filetemp = os.path.join( foldertemp, filename) file.save(filetemp) with open(filetemp, mode="r") as csv_file: csv_data = list(csv.reader(csv_file, delimiter=",")) for item in csv_data: name = item[0] + '-' + item[1] contact_one = str(item[6]) contact_two = str(item[7]) address = str(item[2]) city = ''.join(i for i in item[3] if not i.isdigit()).lower().strip() state = item[4] country = item[5] email = item[8] tag = tags city = city.split('-')[0].split('(')[0].split(',')[0].title() if len(contact_one) == 10: contact_one = '91' + contact_one if city == "": if state == "": city = country.title() else: city = state.title() if item[0] is not "": try: city_obj = City.query.filter_by(name=str(city)).first() if city_obj: pass else: city_obj = City(str(city), str(state), str(country)) db.session.add(city_obj) con_obj = Contact(name , contact_one , contact_two , address , email , city_obj) db.session.add(con_obj) for item in tag: tag_obj = Tag.query.filter_by( name=item['name']).first() if tag_obj: pass else: tag_obj = Tag(str(item['name'])) db.session.add(tag_obj) con_obj.tag_contact.append(tag_obj) db.session.commit() except IntegrityError as e: db.session.rollback() try: con_obj = Contact.query.filter_by(contact_one=contact_one).first() con_obj.city = [] db.session.commit() con_obj.city.append(city_obj) con_obj.name = name con_obj.address = address con_obj.email = email for item in tag: tag_obj = Tag.query.filter_by( name=item['name']).first() if tag_obj: pass else: tag_obj = Tag(str(item['name'])) db.session.add(tag_obj) con_obj.tag_contact.append(tag_obj) db.session.commit() except Exception as f: db.session.rollback() except Exception as e: db.session.rollback() return jsonify({'success': 'Data Added'}) except Exception as e: # return Exception for duplicate data print(str(e)) return jsonify({'message': 'Returns error'})