python-migrations / PythonDataset /dev /gwells-task-instances.jsonl.all
12Parker's picture
Upload 96 files
5980447 verified
{"repo": "bcgov/gwells", "pull_number": 1031, "instance_id": "bcgov__gwells-1031", "issue_numbers": "", "base_commit": "23f8a27ee1da1673fb8522056ca1d0168fd051c2", "patch": "diff --git a/app/backend/wells/management/__init__.py b/app/backend/wells/management/__init__.py\nnew file mode 100644\ndiff --git a/app/backend/wells/management/commands/__init__.py b/app/backend/wells/management/commands/__init__.py\nnew file mode 100644\ndiff --git a/app/backend/wells/management/commands/export.py b/app/backend/wells/management/commands/export.py\nnew file mode 100644\n--- /dev/null\n+++ b/app/backend/wells/management/commands/export.py\n@@ -0,0 +1,228 @@\n+import csv\n+import zipfile\n+import os\n+import logging\n+import string\n+\n+from django.core.management.base import BaseCommand\n+from django.db import models\n+from django.db import connection\n+\n+from minio import Minio\n+from openpyxl import Workbook\n+\n+from gwells.settings.base import get_env_variable\n+\n+# Run from command line :\n+# python manage.py export\n+\n+logger = logging.getLogger(__name__)\n+\n+\n+class Command(BaseCommand):\n+\n+ def handle(self, *args, **options):\n+ logger.info('starting export')\n+ zip_filename = 'gwells.zip'\n+ spreadsheet_filename = 'gwells.xlsx'\n+ self.generate_files(zip_filename, spreadsheet_filename)\n+ self.upload_files(zip_filename, spreadsheet_filename)\n+ logger.info('cleaning up')\n+ for filename in (zip_filename, spreadsheet_filename):\n+ if os.path.exists(filename):\n+ os.remove(filename)\n+ logger.info('export complete')\n+\n+ def upload_files(self, zip_filename, spreadsheet_filename):\n+ minioClient = Minio(get_env_variable('S3_HOST'),\n+ access_key=get_env_variable('S3_PUBLIC_ACCESS_KEY'),\n+ secret_key=get_env_variable('S3_PUBLIC_SECRET_KEY'),\n+ secure=True)\n+ for filename in (zip_filename, spreadsheet_filename):\n+ logger.info('uploading {}'.format(filename))\n+ with open(filename, 'rb') as file_data:\n+ file_stat = os.stat(filename)\n+ # Do we need to remove the existing files 1st?\n+ minioClient.put_object(get_env_variable('S3_WELL_EXPORT_BUCKET'),\n+ filename,\n+ file_data,\n+ file_stat.st_size)\n+\n+ def export(self, workbook, gwells_zip, worksheet_name, cursor):\n+ logger.info('exporting {}'.format(worksheet_name))\n+ worksheet = workbook.create_sheet(worksheet_name)\n+ csv_file = '{}.csv'.format(worksheet_name)\n+ if os.path.exists(csv_file):\n+ os.remove(csv_file)\n+ with open(csv_file, 'w') as csvfile:\n+ csvwriter = csv.writer(csvfile, dialect='excel')\n+\n+ values = []\n+ # Write the headings\n+ for index, field in enumerate(cursor.description):\n+ values.append(field.name)\n+ worksheet.append(values)\n+ csvwriter.writerow(values)\n+\n+ # Write the values\n+ row_index = 0\n+ for row, record in enumerate(cursor.fetchall()):\n+ values = []\n+ num_values = 0\n+ for col, value in enumerate(record):\n+ if not (value == \"\" or value is None):\n+ num_values += 1\n+ if type(value) is str:\n+ # There are lots of non-printable characters in the source data that can cause\n+ # issues in the export, so we have to clear them out.\n+ v = ''.join([s for s in value if s in string.printable])\n+ # We can't have something starting with an = sign,\n+ # it would be interpreted as a formula in excel.\n+ if v.startswith('='):\n+ v = '\\'{}'.format(v)\n+ values.append(v)\n+ else:\n+ values.append(value)\n+ if num_values > 1:\n+ csvwriter.writerow(values)\n+ worksheet.append(values)\n+ gwells_zip.write(csv_file)\n+ if os.path.exists(csv_file):\n+ os.remove(csv_file)\n+\n+ def generate_files(self, zip_filename, spreadsheet_filename):\n+ #######\n+ # WELL\n+ #######\n+ well_sql = (\"\"\"select well_tag_number, identification_plate_number,\n+ well_identification_plate_attached,\n+ well_status_code, well.well_class_code,\n+ wsc.well_class_code as well_subclass,\n+ intended_water_use_code, licenced_status_code,\n+ observation_well_number, obs_well_status_code, water_supply_system_name,\n+ water_supply_system_well_name,\n+ street_address, city, legal_lot, legal_plan, legal_district_lot, legal_block,\n+ legal_section, legal_township, legal_range,\n+ land_district_code,\n+ legal_pid,\n+ well_location_description,\n+ latitude, longitude, utm_zone_code, utm_northing, utm_easting,\n+ utm_accuracy_code, bcgs_id,\n+ construction_start_date, construction_end_date, alteration_start_date,\n+ alteration_end_date, decommission_start_date, decommission_end_date,\n+ driller_name, consultant_name, consultant_company,\n+ diameter, total_depth_drilled, finished_well_depth, final_casing_stick_up,\n+ bedrock_depth, ground_elevation, ground_elevation_method_code, static_water_level,\n+ well_yield,\n+ well_yield_unit_code,\n+ artesian_flow, artesian_pressure, well_cap_type, well_disinfected,\n+ drilling_method_code, other_drilling_method, well_orientation,\n+ alternative_specs_submitted,\n+ surface_seal_material_code, surface_seal_method_code, surface_seal_length,\n+ backfill_type,\n+ backfill_depth,\n+ liner_material_code, liner_diameter, liner_thickness, surface_seal_thickness,\n+ liner_from, liner_to,\n+ screen_intake_method_code, screen_type_code, screen_material_code,\n+ other_screen_material,\n+ screen_opening_code, screen_bottom_code, other_screen_bottom, development_method_code,\n+ filter_pack_from,\n+ filter_pack_to, filter_pack_material_code,\n+ filter_pack_thickness,\n+ filter_pack_material_size_code,\n+ development_hours, development_notes,\n+ water_quality_colour, water_quality_odour, ems_id,\n+ decommission_reason, decommission_method_code, decommission_details, sealant_material,\n+ backfill_material,\n+ comments, aquifer_id,\n+ drilling_company.drilling_company_code,\n+ ems,\n+ aquifer_id,\n+ registries_person.surname as driller_responsible\n+ from well\n+ left join well_subclass_code as wsc on wsc.well_subclass_guid = well.well_subclass_guid\n+ left join drilling_company on\n+ drilling_company.drilling_company_guid = well.drilling_company_guid\n+ left join registries_person on\n+ registries_person.person_guid = well.driller_responsible_guid\n+ order by well_tag_number\"\"\")\n+ ###########\n+ # LITHOLOGY\n+ ###########\n+ lithology_sql = (\"\"\"select well_tag_number, lithology_from, lithology_to, lithology_raw_data,\n+ ldc.description as lithology_description_code,\n+ lmc.description as lithology_material_code,\n+ lhc.description as lithology_hardness_code,\n+ lcc.description as lithology_colour_code,\n+ water_bearing_estimated_flow,\n+ well_yield_unit_code, lithology_observation\n+ from lithology_description\n+ left join lithology_description_code as ldc on\n+ ldc.lithology_description_code = lithology_description.lithology_description_code\n+ left join lithology_material_code as lmc on\n+ lmc.lithology_material_code = lithology_description.lithology_material_code\n+ left join lithology_hardness_code as lhc on\n+ lhc.lithology_hardness_code = lithology_description.lithology_hardness_code\n+ left join lithology_colour_code as lcc on\n+ lcc.lithology_colour_code = lithology_description.lithology_colour_code\n+ order by well_tag_number\"\"\")\n+ ########\n+ # CASING\n+ ########\n+ casing_sql = (\"\"\"select well_tag_number, casing_from, casing_to, diameter, casing_code,\n+ casing_material_code, wall_thickness, drive_shoe from casing\n+ order by well_tag_number\"\"\")\n+ ########\n+ # SCREEN\n+ ########\n+ screen_sql = (\"\"\"select well_tag_number, screen_from, screen_to, internal_diameter,\n+ screen_assembly_type_code, slot_size from screen\n+ order by well_tag_number\"\"\")\n+ ############\n+ # PRODUCTION\n+ ############\n+ production_sql = (\"\"\"select well_tag_number, yield_estimation_method_code, well_yield_unit_code,\n+ yield_estimation_rate,\n+ yield_estimation_duration, static_level, drawdown,\n+ hydro_fracturing_performed, hydro_fracturing_yield_increase from production_data\n+ order by well_tag_number\"\"\")\n+ ##############\n+ # PERFORATIONS\n+ ##############\n+ perforation_sql = (\"\"\"select well_tag_number, liner_from, liner_to, liner_diameter,\n+ liner_perforation_from, liner_perforation_to, liner_thickness\n+ from\n+ perforation\n+ order by well_tag_number\"\"\")\n+\n+ if os.path.exists(zip_filename):\n+ os.remove(zip_filename)\n+ with zipfile.ZipFile(zip_filename, 'w') as gwells_zip:\n+ if os.path.exists(spreadsheet_filename):\n+ os.remove(spreadsheet_filename)\n+ workbook = Workbook(write_only=True)\n+ # Well\n+ with connection.cursor() as cursor:\n+ cursor.execute(well_sql)\n+ self.export(workbook, gwells_zip, 'well', cursor)\n+ # Lithology\n+ with connection.cursor() as cursor:\n+ cursor.execute(lithology_sql)\n+ self.export(workbook, gwells_zip, 'lithology', cursor)\n+ # Casing\n+ with connection.cursor() as cursor:\n+ cursor.execute(casing_sql)\n+ self.export(workbook, gwells_zip, 'casing', cursor)\n+ # Screen\n+ with connection.cursor() as cursor:\n+ cursor.execute(screen_sql)\n+ self.export(workbook, gwells_zip, 'screen', cursor)\n+ # Production\n+ with connection.cursor() as cursor:\n+ cursor.execute(production_sql)\n+ self.export(workbook, gwells_zip, 'production', cursor)\n+ # Perforation\n+ with connection.cursor() as cursor:\n+ cursor.execute(perforation_sql)\n+ self.export(workbook, gwells_zip, 'perforation', cursor)\n+ workbook.save(filename=spreadsheet_filename)\ndiff --git a/app/backend/wells/urls.py b/app/backend/wells/urls.py\n--- a/app/backend/wells/urls.py\n+++ b/app/backend/wells/urls.py\n@@ -36,6 +36,9 @@\n url(r'^api/v1/wells/(?P<tag>[0-9]+)/files$',\n never_cache(views.ListFiles.as_view()), name='file-list'),\n \n+ # Extract files\n+ url(r'^api/v1/wells/extracts$', views.ListExtracts.as_view(), name='extract-list'),\n+\n # Well list\n url(r'^api/v1/wells/$',\n never_cache(views.WellListAPIView.as_view()), name='well-list'),\ndiff --git a/app/backend/wells/views.py b/app/backend/wells/views.py\n--- a/app/backend/wells/views.py\n+++ b/app/backend/wells/views.py\n@@ -11,6 +11,7 @@\n See the License for the specific language governing permissions and\n limitations under the License.\n \"\"\"\n+from urllib.parse import quote\n \n from django.db.models import Prefetch\n from django.http import Http404\n@@ -24,10 +25,13 @@\n \n from drf_yasg.utils import swagger_auto_schema\n \n+from minio import Minio\n+\n from gwells import settings\n from gwells.models import Survey\n from gwells.roles import WELLS_VIEWER_ROLE, WELLS_EDIT_ROLE\n from gwells.pagination import APILimitOffsetPagination\n+from gwells.settings.base import get_env_variable\n \n from wells.models import Well\n from wells.documents import MinioClient\n@@ -65,6 +69,45 @@ def get_serializer(self, data):\n lookup_field = 'well_tag_number'\n \n \n+class ListExtracts(APIView):\n+ \"\"\"\n+ List well extracts\n+\n+ get: list well extracts\n+ \"\"\"\n+ @swagger_auto_schema(auto_schema=None)\n+ def get(self, request):\n+ host = get_env_variable('S3_HOST')\n+ minioClient = Minio(host,\n+ access_key=get_env_variable('S3_PUBLIC_ACCESS_KEY'),\n+ secret_key=get_env_variable('S3_PUBLIC_SECRET_KEY'),\n+ secure=True)\n+ objects = minioClient.list_objects(get_env_variable('S3_WELL_EXPORT_BUCKET'))\n+ urls = list(\n+ map(\n+ lambda document: {\n+ 'url': 'https://{}/{}/{}'.format(host,\n+ quote(document.bucket_name),\n+ quote(document.object_name)),\n+ 'name': document.object_name,\n+ 'size': document.size,\n+ 'last_modified': document.last_modified,\n+ 'description': self.create_description(document.object_name)\n+ }, objects)\n+ )\n+ return Response(urls)\n+\n+ def create_description(self, name):\n+ extension = name[name.rfind('.')+1:]\n+ print(extension)\n+ if extension == 'zip':\n+ return 'ZIP, CSV'\n+ elif extension == 'xlsx':\n+ return 'XLSX'\n+ else:\n+ return None\n+\n+\n class ListFiles(APIView):\n \"\"\"\n List documents associated with a well (e.g. well construction report)\n", "test_patch": "", "problem_statement": "", "hints_text": "", "created_at": "2018-11-20T23:25:57Z"}