Best Python code snippet using localstack_python
export_non_crfs.py
Source:export_non_crfs.py
...26 objs = model_cls.objects.all()27 count = 028 models_data = []29 for obj in objs:30 data = self.export_methods_cls.fix_date_format(self.export_methods_cls.non_crf_obj_dict(obj=obj))31 if exclude:32 exclude_fields.append(exclude)33 for e_fields in exclude_fields:34 try:35 del data[e_fields]36 except KeyError:37 pass38 models_data.append(data)39 count += 140 timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')41 fname = f'{study}_' + model_name + '_' + timestamp + '.csv'42 final_path = self.export_path + fname43 df_crf = pd.DataFrame(models_data)44 df_crf.rename(columns={'subject_identifier':45 'subject_identifier'}, inplace=True)46 df_crf.to_csv(final_path, encoding='utf-8', index=False)47 def follow_models(self, follow_model_list=None, exclude=None, study=None):48 for model_name in follow_model_list:49 model_cls = django_apps.get_model(study, model_name)50 objs = model_cls.objects.all()51 count = 052 models_data = []53 for obj in objs:54 data = self.export_methods_cls.fix_date_format(55 self.export_methods_cls.follow_data_dict(model_obj=obj))56 if exclude:57 exclude_fields.append(exclude)58 for e_fields in exclude_fields:59 try:60 del data[e_fields]61 except KeyError:62 pass63 models_data.append(data)64 count += 165 timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')66 fname = f'{study}_' + model_name + '_' + timestamp + '.csv'67 final_path = self.export_path + fname68 df_crf = pd.DataFrame(models_data)69 df_crf.to_csv(final_path, encoding='utf-8', index=False)70 def follow_m2m(self, many_to_many_models=None, study=None):71 for follow_model_info in many_to_many_models:72 model_name, mm_field, _ = follow_model_info73 model_cls = django_apps.get_model(study, model_name)74 count = 075 mergered_data = []76 model_objs = model_cls.objects.all()77 for model_obj in model_objs:78 mm_objs = getattr(model_obj, mm_field).all()79 if mm_objs:80 for mm_obj in mm_objs:81 mm_data = {mm_field: mm_obj.short_name}82 model_data = self.export_methods_cls.follow_data_dict(model_obj=model_obj)83 # Merged many to many and CRF data84 data = self.export_methods_cls.fix_date_format({**model_data, **mm_data})85 for e_fields in exclude_m2m_fields:86 try:87 del data[e_fields]88 except KeyError:89 pass90 mergered_data.append(data)91 count += 192 else:93 model_data = self.export_methods_cls.fix_date_format(94 self.export_methods_cls.follow_data_dict(model_obj=model_obj))95 for e_fields in exclude_fields:96 try:97 del model_data[e_fields]98 except KeyError:99 pass100 mergered_data.append(model_data)101 count += 1102 timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')103 fname = f'{study}_' + model_name + '_' + 'merged' '_' + mm_field + '_' + timestamp + '.csv'104 final_path = self.export_path + fname105 df_crf_many2many = pd.DataFrame(mergered_data)106 df_crf_many2many.to_csv(final_path, encoding='utf-8', index=False)107 def caregiver_m2m_non_crf(self, caregiver_many_to_many_non_crf=None, study=None):108 """.109 """110 for crf_infor in caregiver_many_to_many_non_crf:111 crf_name, mm_field = crf_infor112 crf_cls = django_apps.get_model(study, crf_name)113 count = 0114 mergered_data = []115 crf_objs = crf_cls.objects.all()116 for crf_obj in crf_objs:117 mm_objs = getattr(crf_obj, mm_field).all()118 if mm_objs:119 for mm_obj in mm_objs:120 mm_data = {mm_field: mm_obj.short_name}121 crfdata = self.export_methods_cls.non_crf_obj_dict(obj=crf_obj)122 # Merged many to many and CRF data123 data = self.export_methods_cls.fix_date_format({**crfdata, **mm_data})124 for e_fields in exclude_m2m_fields:125 try:126 del data[e_fields]127 except KeyError:128 pass129 mergered_data.append(data)130 count += 1131 else:132 crfdata = self.export_methods_cls.fix_date_format(133 self.export_methods_cls.non_crf_obj_dict(obj=crf_obj))134 for e_fields in exclude_fields:135 try:136 del crfdata[e_fields]137 except KeyError:138 pass139 mergered_data.append(crfdata)140 count += 1141 timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')142 fname = f'{study}_' + crf_name + '_' + 'merged' '_' + mm_field + '_' + timestamp + '.csv'143 final_path = self.export_path + fname144 df_crf_many2many = pd.DataFrame(mergered_data)145 df_crf_many2many.to_csv(final_path, encoding='utf-8', index=False)146 def child_non_crf(self, child_model_list=None):147 """.148 """149 for model_name in child_model_list:150 model_cls = django_apps.get_model('flourish_child', model_name)151 objs = model_cls.objects.all()152 count = 0153 models_data = []154 for obj in objs:155 data = obj.__dict__156 data = self.export_methods_cls.encrypt_values(data, obj.__class__)157 try:158 rs = self.rs_cls.objects.get(subject_identifier=obj.subject_identifier)159 except self.rs_cls.DoesNotExist:160 if not 'dob' in data:161 data.update(dob=None)162 if not 'gender' in data:163 data.update(gender=None)164 data.update(165 relative_identifier=None,166 screening_age_in_years=None,167 registration_datetime=None168 )169 else:170 if not 'dob' in data:171 data.update(dob=rs.dob)172 if not 'gender' in data:173 data.update(gender=rs.gender)174 if not 'screening_identifier' in data:175 data.update(screening_identifier=rs.screening_identifier)176 data.update(177 relative_identifier=rs.relative_identifier,178 screening_age_in_years=rs.screening_age_in_years,179 registration_datetime=rs.registration_datetime180 )181 last_data = self.export_methods_cls.fix_date_format(data)182 for e_fields in exclude_fields:183 try:184 del last_data[e_fields]185 except KeyError:186 pass187 models_data.append(last_data)188 count += 1189 timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')190 fname = 'flourish_child_' + model_name + '_' + timestamp + '.csv'191 final_path = self.export_path + fname192 df_crf = pd.DataFrame(models_data)193 df_crf.to_csv(final_path, encoding='utf-8', index=False)194 def offstudy(self, offstudy_prn_model_list=None):195 """Export off study forms.196 """197 for model_name in offstudy_prn_model_list:198 model_cls = django_apps.get_model('flourish_prn', model_name)199 objs = model_cls.objects.all()200 count = 0201 models_data = []202 for obj in objs:203 data = obj.__dict__204 data = self.export_methods_cls.encrypt_values(data, obj.__class__)205 try:206 rs = self.rs_cls.objects.get(subject_identifier=obj.subject_identifier)207 except self.rs_cls.DoesNotExist:208 raise ValidationError('Registered subject can not be missing')209 else:210 if not 'dob' in data:211 data.update(dob=rs.dob)212 if not 'gender' in data:213 data.update(gender=rs.gender)214 if not 'screening_identifier' in data:215 data.update(screening_identifier=rs.screening_identifier)216 data.update(217 relative_identifier=rs.relative_identifier,218 screening_age_in_years=rs.screening_age_in_years,219 registration_datetime=rs.registration_datetime220 )221 last_data = self.export_methods_cls.fix_date_format(data)222 for e_fields in exclude_fields:223 try:224 del last_data[e_fields]225 except KeyError:226 pass227 models_data.append(last_data)228 count += 1229 timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')230 fname = 'flourish_prn_' + model_name + '_' + timestamp + '.csv'231 final_path = self.export_path + fname232 df_crf = pd.DataFrame(models_data)233 df_crf.to_csv(final_path, encoding='utf-8', index=False)234 def death_report(self, death_report_prn_model_list=None):235 # Export child Non CRF data236 for model_name in death_report_prn_model_list:237 model_cls = django_apps.get_model('flourish_prn', model_name)238 objs = model_cls.objects.all()239 count = 0240 models_data = []241 for obj in objs:242 data = obj.__dict__243 try:244 rs = self.rs_cls.objects.get(subject_identifier=obj.subject_identifier)245 except self.rs_cls.DoesNotExist:246 raise ValidationError('Registered subject can not be missing')247 else:248 if not 'dob' in data:249 data.update(dob=rs.dob)250 if not 'gender' in data:251 data.update(gender=rs.gender)252 if not 'screening_identifier' in data:253 data.update(screening_identifier=rs.screening_identifier)254 data.update(255 relative_identifier=rs.relative_identifier,256 screening_age_in_years=rs.screening_age_in_years,257 registration_datetime=rs.registration_datetime258 )259 data = self.export_methods_cls.encrypt_values(data, obj.__class__)260 last_data = self.export_methods_cls.fix_date_format(data)261 for e_fields in exclude_fields:262 try:263 del last_data[e_fields]264 except KeyError:265 pass266 models_data.append(last_data)267 count += 1268 timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')269 fname = 'flourish_prn_' + model_name + '_' + timestamp + '.csv'270 final_path = self.export_path + fname271 df_crf = pd.DataFrame(models_data)272 df_crf.to_csv(final_path, encoding='utf-8', index=False)273 def caregiver_visit(self):274 caregiver_visits = django_apps.get_model('flourish_caregiver.maternalvisit').objects.all()275 data = []276 for mv in caregiver_visits:277 d = mv.__dict__278 d = self.export_methods_cls.fix_date_format(d)279 for e_fields in exclude_fields:280 try:281 del d[e_fields]282 except KeyError:283 pass284 data.append(d)285 timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')286 fname = 'flourish_caregiver_maternal_visit' + '_' + timestamp + '.csv'287 final_path = self.export_path + fname288 df_crf = pd.DataFrame(data)289 df_crf.to_csv(final_path, encoding='utf-8', index=False)290 def child_visit(self):291 child_visits = django_apps.get_model('flourish_child.childvisit').objects.all()292 data = []293 for mv in child_visits:294 d = mv.__dict__295 d = self.export_methods_cls.fix_date_format(d)296 for e_fields in exclude_fields:297 try:298 del d[e_fields]299 except KeyError:300 pass301 data.append(d)302 timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')303 fname = 'flourish_child_child_visit' + '_' + timestamp + '.csv'304 final_path = self.export_path + fname305 df_crf = pd.DataFrame(data)...
maternal_requisition_admin.py
Source:maternal_requisition_admin.py
...13from ..forms import MaternalRequisitionForm14from ..models import MaternalRequisition15from .modeladmin_mixins import CrfModelAdminMixin16class ExportRequisitionCsvMixin:17 def fix_date_format(self, obj_dict=None):18 """Change all dates into a format for the export19 and split the time into a separate value.20 Format: m/d/y21 """22 result_dict_obj = {**obj_dict}23 for key, value in obj_dict.items():24 if isinstance(value, datetime.datetime):25 value = timezone.make_naive(value)26 time_value = value.time()27 time_variable = key + '_time'28 result_dict_obj[key] = value.date()29 result_dict_obj[time_variable] = time_value30 return result_dict_obj31 def export_as_csv(self, request, queryset):32 response = HttpResponse(content_type='application/ms-excel')33 response['Content-Disposition'] = 'attachment; filename=%s.xls' % (34 self.get_export_filename())35 wb = xlwt.Workbook(encoding='utf-8', style_compression=2)36 ws = wb.add_sheet('%s')37 row_num = 038 font_style = xlwt.XFStyle()39 font_style.font.bold = True40 font_style.num_format_str = 'YYYY/MM/DD h:mm:ss'41 field_names = self.fix_date_format(queryset[0].__dict__)42 field_names = [a for a in field_names.keys()]43 field_names += ['panel_name']44 field_names.remove('_state')45 for col_num in range(len(field_names)):46 ws.write(row_num, col_num, field_names[col_num], font_style)47 field_names.remove('panel_name')48 for obj in queryset:49 obj_data = self.fix_date_format(obj.__dict__)50 data = [obj_data[field] for field in field_names]51 data += [obj.panel.name]52 row_num += 153 for col_num in range(len(data)):54 if isinstance(data[col_num], uuid.UUID):55 ws.write(row_num, col_num, str(data[col_num]))56 elif isinstance(data[col_num], datetime.date):57 ws.write(row_num, col_num, data[col_num], xlwt.easyxf(num_format_str='YYYY/MM/DD'))58 elif isinstance(data[col_num], datetime.time):59 ws.write(row_num, col_num, data[col_num], xlwt.easyxf(num_format_str='h:mm:ss'))60 else:61 ws.write(row_num, col_num, data[col_num])62 wb.save(response)63 return response...
calendar_heler.py
Source:calendar_heler.py
1import datetime2async def fix_date_format(date: str) -> str:3 date = date.split("-")4 date.reverse()5 return ".".join(date[:2])6async def get_date_list() -> list:7 date_list = []8 today = datetime.date.today()9 date_list.append(await fix_date_format(str(today)))10 for i in range(13):11 today = today + datetime.timedelta(days=1)12 date_list.append(await fix_date_format(str(today)))...
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!!