예제 #1
0
파일: views.py 프로젝트: demiurg/geokit
def populate_table_handler(tenant, table_id):
    connection.close()
    connection.set_schema(tenant)

    table = GeoKitTable.objects.get(pk=table_id)
    table.status = 2  # Bad
    table.save()
예제 #2
0
    def handle(self, *args, **options):
        # Connection needs first to be at the public schema, as this is where
        # the database needs to be set before creating a new tenant. If this is
        # not done then django-tenants will raise a "Can't create tenant outside
        # the public schema." error.
        connection.set_schema_to_public()  # Switch to Public.

        # Get the user inputs.
        schema_name = options['schema_name'][0]
        length = options['length'][0]

        try:
            organization = SharedOrganization.objects.get(
                schema_name=schema_name)
        except SharedOrganization.DoesNotExist:
            raise CommandError(_('Organization does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(organization.schema_name,
                              True)  # Switch to Tenant.

        watches = Watch.seed(length)

        # For debugging purposes.
        self.stdout.write(
            self.style.SUCCESS(_('Successfully seed the following watch(s):')))

        for watch in watches:
            self.stdout.write(
                self.style.SUCCESS(
                    _('Slug %(slug)s.') % {
                        'slug': watch.slug,
                    }))
예제 #3
0
    def handle(self, *args, **options):
        # Connection needs first to be at the public schema, as this is where
        # the database needs to be set before creating a new tenant. If this is
        # not done then django-tenants will raise a "Can't create tenant outside
        # the public schema." error.
        connection.set_schema_to_public() # Switch to Public.
        # Get the user inputs.
        schema_name = options['schema_name'][0]

        try:
            franchise = SharedFranchise.objects.get(schema_name=schema_name)
        except SharedFranchise.DoesNotExist:
            raise CommandError(_('Franchise does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(franchise.schema_name, True) # Switch to Tenant.

        #----------------------------------------------------------------------#
        # ALGORITHM:
        # WE WANT TO FREEZE TIME TO THE `LAST_MODIFIED` DATETIME SO THE RECORD
        # DOES NOT LOOKED LIKE IT WAS MODIFIED. SPECIAL THANKS TO LINK:
        # https://stackoverflow.com/a/40423482
        #----------------------------------------------------------------------#

        # (1) PROCESS CUSTOMERS
        for customer in Customer.objects.filter(gender=None).iterator(chunk_size=250):
            try:
                with freeze_time(customer.last_modified):
                    self.fix_gender(customer)
            except Exception as e:
                print(e)
 def run_migrations(self, schema_name, included_apps):
     if int(self.options.get('verbosity', 1)) >= 1:
         self._notice("=== Running migrate for schema %s" % schema_name)
     connection.set_schema(schema_name)
     command = MigrateCommand()
     command.execute(*self.args, **self.options)
     connection.set_schema_to_public()
예제 #5
0
    def handle(self, *args, **options):
        # Connection needs first to be at the public schema, as this is where
        # the database needs to be set before creating a new tenant. If this is
        # not done then django-tenants will raise a "Can't create tenant outside
        # the public schema." error.
        connection.set_schema_to_public()  # Switch to Public.
        # Get the user inputs.
        schema_name = options['schema_name'][0]

        try:
            franchise = SharedFranchise.objects.get(schema_name=schema_name)
        except SharedFranchise.DoesNotExist:
            raise CommandError(_('Franchise does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(franchise.schema_name, True)  # Switch to Tenant.

        work_orders = WorkOrder.objects.filter(
            Q(
                Q(state=WORK_ORDER_STATE.IN_PROGRESS)
                | Q(state=WORK_ORDER_STATE.ONGOING)
                | Q(state=WORK_ORDER_STATE.NEW)) & Q(is_ongoing=True)
            & Q(ongoing_work_order__isnull=True))
        for work_order in work_orders:
            print(work_order.id)
            work_order.ongoing_work_order = OngoingWorkOrder.objects.create(
                customer=work_order.customer,
                associate=work_order.associate,
                state=ONGOING_WORK_ORDER_STATE.RUNNING)
            work_order.save()

        # For debugging purposes.
        self.stdout.write(self.style.SUCCESS(_('Successfully updated.')))
예제 #6
0
    def export_to_file(self, tenant):
        connection.close()
        connection.set_schema(tenant)

        try:
            table_file = GeoKitTableFile(table=self)
            table_file.save()

            path = "%s/downloads/csv/%s/%s" % (settings.MEDIA_ROOT, tenant,
                                               self.pk)

            if not os.path.exists(os.path.dirname(path)):
                os.makedirs(os.path.dirname(path))

            with open(path + '.csv', 'w') as csvfile:
                writer = csv.DictWriter(csvfile, fieldnames=self.field_names)

                writer.writeheader()
                for r in self.record_set.all():
                    writer.writerow(r.properties)

            table_file.file = "downloads/csv/%s/%s.csv" % (tenant, self.pk)
            table_file.save()

        except IntegrityError:
            # Race condition where two requests for a GeoKitTable
            # occur at the same time.
            pass
예제 #7
0
파일: views.py 프로젝트: demiurg/geokit
def process_shapefile(tenant, layer_id, srs):
    connection.close()
    connection.set_schema(tenant)

    l = Layer.objects.get(pk=layer_id)

    shape_path = "%s/uploads/shapefile/%s/%s.shp" % (settings.MEDIA_ROOT,
                                                     tenant, l.pk)
    try:
        with fiona.open(shape_path, 'r') as collection:
            count = 0

            min_bounds = OGRGeometry('POINT ({} {})'.format(
                collection.bounds[0], collection.bounds[1]),
                                     srs=srs).transform(4326, clone=True)
            max_bounds = OGRGeometry('POINT ({} {})'.format(
                collection.bounds[2], collection.bounds[3]),
                                     srs=srs).transform(4326, clone=True)

            l.bounds = min_bounds.coords + max_bounds.coords

            features = []
            for index, record in enumerate(collection):
                try:
                    geom = shape(record['geometry'])
                    transformed_geom = OGRGeometry(
                        geom.wkt, srs=srs).transform(3857, clone=True)
                    transformed_geom_collection = GeometryCollection(
                        transformed_geom.geos)

                    s = hashlib.sha1()
                    s.update(transformed_geom_collection.ewkb)

                    properties = record['properties']
                    properties['fid'] = index
                    properties['shaid'] = s.hexdigest()
                    features.append(
                        Feature(layer=l,
                                geometry=transformed_geom_collection,
                                properties=properties))
                    count += 1
                except Exception as e:
                    print "Feature excepton", e

            if count == 0:
                raise Exception("Layer needs to have at least one feature")

            Feature.objects.bulk_create(features)

            field_names = collection.schema['properties'].keys()
            field_names.append("fid")
            l.field_names = field_names
            l.properties = collection.schema['properties']
            l.schema = collection.schema
            l.status = 0
            l.save()
    finally:
        for path in glob.glob("%s/uploads/shapefile/%s/%s.*" %
                              (settings.MEDIA_ROOT, tenant, l.pk)):
            os.remove(path)
예제 #8
0
파일: views.py 프로젝트: demiurg/geokit
def vector_catalog_save_layer(tenant, layer, vector_layer, features):
    connection.close()
    connection.set_schema(tenant)

    features = VECTOR_LAYERS[vector_layer]['geometries_by_id'](features)

    with transaction.atomic():
        union = GEOSGeometry('POINT EMPTY')
        keys = None
        for g, props in features:
            if not keys:
                keys = props.keys()

            union = union.union(g)
            g.transform(3857)

            s = hashlib.sha1()
            s.update(GeometryCollection(g).ewkb)
            props['shaid'] = s.hexdigest()
            f = Feature(layer=layer,
                        geometry=GeometryCollection(g),
                        properties=props)
            f.save()

        envelope = union.envelope.coords[0]
        layer.bounds = envelope[2] + envelope[0]
        layer.status = 0
        layer.field_names = list(set(layer.field_names).union(set(keys)))
        layer.schema['properties'] = {n: "str" for n in layer.field_names}
        layer.save()
예제 #9
0
    def handle(self, *args, **options):
        # Connection needs first to be at the public schema, as this is where
        # the database needs to be set before creating a new tenant. If this is
        # not done then django-tenants will raise a "Can't create tenant outside
        # the public schema." error.
        connection.set_schema_to_public()  # Switch to Public.
        # Get the user inputs.
        schema_name = options['schema_name'][0]

        try:
            franchise = SharedFranchise.objects.get(schema_name=schema_name)
        except SharedFranchise.DoesNotExist:
            raise CommandError(_('Franchise does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(franchise.schema_name, True)  # Switch to Tenant.

        for customer in Customer.objects.all():
            country = customer.address_country
            if country == "CA":
                customer.address_country = "Canada"
                customer.save()

        for associate in Associate.objects.all():
            country = associate.address_country
            if country == "CA":
                associate.address_country = "Canada"
                associate.save()

        # For debugging purposes.
        self.stdout.write(self.style.SUCCESS(_('Successfully updated.')))
예제 #10
0
def tenant_context(tenant):
    previous_schema = connection.get_schema()
    try:
        connection.set_tenant(tenant)
        yield
    finally:
        connection.set_schema(previous_schema)
예제 #11
0
    def handle(self, *args, **options):
        # Connection needs first to be at the public schema, as this is where
        # the database needs to be set before creating a new tenant. If this is
        # not done then django-tenants will raise a "Can't create tenant outside
        # the public schema." error.
        connection.set_schema_to_public() # Switch to Public.
        # Get the user inputs.
        schema_name = options['schema_name'][0]
        slug = options['slug'][0]

        try:
            organization = SharedOrganization.objects.get(schema_name=schema_name)
        except SharedOrganization.DoesNotExist:
            raise CommandError(_('Organization does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(organization.schema_name, True) # Switch to Tenant.

        watch = Watch.objects.filter(user__slug=slug).first()
        if watch:
            self.process(watch)

            # For debugging purposes.
            self.stdout.write(
                self.style.SUCCESS(_('Successfully processed watch with slug %(slug)s.') %{
                    'slug': slug,
                })
            )
        else:
            raise CommandError(_('Watch does not exist with slug %(slug)s.')%{
                'slug': slug
            })
예제 #12
0
    def handle(self, *args, **options):
        # Get the user inputs.
        schema_name = options['schema_name'][0]
        email = options['email'][0]

        try:
            franchise = SharedFranchise.objects.get(schema_name=schema_name)
        except SharedFranchise.DoesNotExist:
            raise CommandError(_('Franchise does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(schema_name, True)  # Switch to Tenant.

        # Defensive Code: Prevent continuing if the email already exists.
        if not SharedUser.objects.filter(email=email).exists():
            raise CommandError(
                _('Email does not exists, please pick another email.'))

        # Create the user.
        user = SharedUser.objects.get(email=email)
        user.delete()
        self.stdout.write(self.style.SUCCESS(_('Deleted "User" object.')))

        # For debugging purposes.
        self.stdout.write(
            self.style.SUCCESS(_('Successfully deleted a tenant account.')))
예제 #13
0
    def handle(self, *args, **options):
        # Get the user inputs.
        schema_name = options['schema_name']
        work_order_id = options['work_order_id']
        user_id = options['user_id']
        from_ip = options['from_ip']
        from_ip_is_public = options['from_ip_is_public']

        # print("INPUT")
        # print(schema_name)
        # print(work_order_id)
        # print(user_id)
        # print(from_ip)
        # print(from_ip_is_public)

        # Connection needs first to be at the public schema, as this is where
        # the database needs to be set before creating a new tenant. If this is
        # not done then django-tenants will raise a "Can't create tenant outside
        # the public schema." error.
        connection.set_schema_to_public()  # Switch to Public.

        try:
            franchise = SharedFranchise.objects.get(schema_name=schema_name)
        except SharedFranchise.DoesNotExist:
            raise CommandError(_('Franchise does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(franchise.schema_name, True)  # Switch to Tenant.

        try:
            order = WorkOrder.objects.get(id=work_order_id)
            if order.state == WORK_ORDER_STATE.COMPLETED_AND_PAID:
                self.process(order, user_id, from_ip, from_ip_is_public)
        except SharedFranchise.DoesNotExist:
            raise CommandError(_('Franchise does not exist!'))
    def handle(self, *args, **options):
        # Connection needs first to be at the public schema, as this is where
        # the database needs to be set before creating a new tenant. If this is
        # not done then django-tenants will raise a "Can't create tenant outside
        # the public schema." error.
        connection.set_schema_to_public()  # Switch to Public.
        # Get the user inputs.
        schema_name = options['schema_name'][0]

        try:
            franchise = SharedFranchise.objects.get(schema_name=schema_name)
        except SharedFranchise.DoesNotExist:
            raise CommandError(_('Franchise does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(franchise.schema_name, True)  # Switch to Tenant.

        # Update content.
        self.begin_populating_insurance_requirements()
        self.begin_populating_skill_sets()
        self.begin_populating_resource_categories()
        self.begin_populating_resource_items()
        self.begin_populating_resource_item_sort_orders()
        self.begin_populating_vehicle_types()
        self.begin_populating_order_service_fees()
        self.being_populating_how_hear_about_us_items()

        # For debugging purposes.
        self.stdout.write(
            self.style.SUCCESS(_('Successfully populated tenant content.')))
예제 #15
0
def schema_context(schema_name):
    previous_schema = connection.get_schema()
    try:
        connection.set_schema(schema_name)
        yield
    finally:
        connection.set_schema(previous_schema)
예제 #16
0
def tenant_context(tenant):
    previous_schema = connection.get_schema()
    try:
        connection.set_tenant(tenant)
        yield
    finally:
        connection.set_schema(previous_schema)
예제 #17
0
    def handle(self, *args, **options):
        # Connection needs first to be at the public schema, as this is where
        # the database needs to be set before creating a new tenant. If this is
        # not done then django-tenants will raise a "Can't create tenant outside
        # the public schema." error.
        connection.set_schema_to_public() # Switch to Public.
        # Get the user inputs.
        schema_name = options['schema_name'][0]
        worker_order_id = options['id'][0]
        state = options['state'][0]

        try:
            franchise = SharedFranchise.objects.get(schema_name=schema_name)
        except SharedFranchise.DoesNotExist:
            raise CommandError(_('Franchise does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(franchise.schema_name, True) # Switch to Tenant.

        try:
            work_order = WorkOrder.objects.get(id=worker_order_id)
        except WorkOrder.DoesNotExist:
            raise CommandError(_('Work order does not exist!'))

        # Change state.
        work_order.state = state
        work_order.save()

        # For debugging purposes.
        self.stdout.write(
            self.style.SUCCESS(_('Successfully changed work order.'))
        )
예제 #18
0
    def begin_processing(self, schema_name, prefix):
        # Load up the following historic data from CSV files...
        full_file_path = self.find_filepath_containing(
            CSV_FILENAME, prefix)  # Personal Customers
        print(full_file_path)

        # Connection needs first to be at the public schema, as this is where
        # the database needs to be set before creating a new tenant. If this is
        # not done then django-tenants will raise a "Can't create tenant outside
        # the public schema." error.
        connection.set_schema_to_public()  # Switch to Public.

        try:
            franchise = SharedOrganization.objects.get(schema_name=schema_name)
        except SharedOrganization.DoesNotExist:
            raise CommandError(_('Org does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(franchise.schema_name, True)  # Switch to Tenant.

        # Begin importing...
        with open(full_file_path, newline='', encoding='utf-8') as csvfile:
            csvreader = csv.reader(csvfile, delimiter=',', quotechar='"')
            for i, row_dict in enumerate(csvreader):
                if i > 0:

                    # # Used for debugging purposes only.
                    # self.stdout.write(
                    #     self.style.SUCCESS(_('Importing WorkOrder #%(id)s') % {
                    #         'id': i
                    #     })
                    # )

                    # Begin importing...
                    self.run_import_from_dict(row_dict, i)
예제 #19
0
def schema_context(schema_name):
    previous_tenant = connection.tenant
    try:
        connection.set_schema(schema_name)
        yield
    finally:
        connection.set_tenant(previous_tenant)
예제 #20
0
def switch_schema(task, kwargs, **kw):
    """ Switches schema of the task, before it has been run. """
    # Lazily load needed functions, as they import django model functions which
    # in turn load modules that need settings to be loaded and we can't
    # guarantee this module was loaded when the settings were ready.
    from .compat import get_public_schema_name, get_tenant_model

    old_schema = (connection.schema_name, connection.include_public_schema)
    setattr(task, '_old_schema', old_schema)

    schema = (
        get_schema_name_from_task(task, kwargs) or
        get_public_schema_name()
    )

    # If the schema has not changed, don't do anything.
    if connection.schema_name == schema:
        return

    if connection.schema_name != get_public_schema_name():
        connection.set_schema_to_public()

    if schema == get_public_schema_name():
        return

    #tenant = get_tenant_model().objects.get(schema_name=schema)
    connection.set_schema(schema, include_public=True)
예제 #21
0
    def handle(self, *args, **options):
        # Connection needs first to be at the public schema, as this is where
        # the database needs to be set before creating a new tenant. If this is
        # not done then django-tenants will raise a "Can't create tenant outside
        # the public schema." error.
        connection.set_schema_to_public()  # Switch to Public.
        # Get the user inputs.
        schema_name = options['schema_name'][0]

        try:
            franchise = SharedFranchise.objects.get(schema_name=schema_name)
        except SharedFranchise.DoesNotExist:
            raise CommandError(_('Franchise does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(franchise.schema_name, True)  # Switch to Tenant.

        # Delete this bad tasks.
        TaskItem.objects.filter(
            job__state=WORK_ORDER_STATE.COMPLETED_BUT_UNPAID,
            is_closed=False).delete()
        TaskItem.objects.filter(job__state=WORK_ORDER_STATE.COMPLETED_AND_PAID,
                                is_closed=False).delete()

        # For debugging purposes.
        self.stdout.write(self.style.SUCCESS(_('Successfully updated.')))
    def handle(self, *args, **options):
        # Get the user inputs.
        schema_name = options['schema_name'][0]
        id = options['id'][0]

        try:
            franchise = SharedFranchise.objects.get(schema_name=schema_name)
        except SharedFranchise.DoesNotExist:
            raise CommandError(_('Franchise does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(schema_name, True)  # Switch to Tenant.

        # Defensive Code: Prevent continuing if the email already exists.
        user = None
        if Customer.objects.filter(id=id).exists():
            # Create the user.
            customer = Customer.objects.get(id=id)
            user = customer.owner
            customer.delete()
            self.stdout.write(
                self.style.SUCCESS(_('Deleted "Customer" object.')))

            if user:
                user.delete()
                self.stdout.write(
                    self.style.SUCCESS(_('Deleted "SharedUser" object.')))

        # For debugging purposes.
        self.stdout.write(
            self.style.SUCCESS(_('Successfully deleted a tenant customer.')))
예제 #23
0
    def run_migrations(self, schema_name, included_apps, options):
        self._notice("=== Running migrate for schema %s" % schema_name)
        connection.set_schema(schema_name)
        command = MigrateCommand()

        command.execute(*self.args, **options)
        connection.set_schema_to_public()
예제 #24
0
    def handle(self, *args, **options):
        # Connection needs first to be at the public schema, as this is where
        # the database needs to be set before creating a new tenant. If this is
        # not done then django-tenants will raise a "Can't create tenant outside
        # the public schema." error.
        connection.set_schema_to_public() # Switch to Public.
        # Get the user inputs.
        schema_name = options['schema_name'][0]

        try:
            franchise = SharedFranchise.objects.get(schema_name=schema_name)
        except SharedFranchise.DoesNotExist:
            raise CommandError(_('Franchise does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(franchise.schema_name, True) # Switch to Tenant.

        self.delete_old_tasks()
        self.update_task_names()
        self.standardization_customer_province_and_country()
        self.standardization_associate_province_and_country()
        self.standardization_staff_province_and_country()
        self.customer_blacklist()

        # For debugging purposes.
        self.stdout.write(
            self.style.SUCCESS(_('Successfully updated.'))
        )
예제 #25
0
파일: tasks.py 프로젝트: fafcrumb/etools
def import_docs(**kwargs):
    """
    Imports docs from couch base
    """
    from partners.models import DistributionPlan

    data = requests.get(
        os.path.join(settings.COUCHBASE_URL, '_all_docs?include_docs=true'),
        auth=HTTPBasicAuth(settings.COUCHBASE_USER, settings.COUCHBASE_PASS)
    ).json()

    for row in data['rows']:
        if 'distribution_id' in row['doc']:
            distribution_id = row['doc']['distribution_id']
            try:
                connection.set_schema(row['doc']['country'])
                distribution = DistributionPlan.objects.get(
                    id=distribution_id
                )
                distribution.delivered = row['doc']['item_list'][0]['delivered']
                distribution.document = row['doc']
                distribution.save()
            except DistributionPlan.DoesNotExist:
                print 'Distribution ID {} not found for Country {}'.format(
                    distribution_id, row['doc']['country']
                )
            except Exception as exp:
                print exp.message
예제 #26
0
def schema_context(schema_name):
    previous_schema = connection.get_schema()
    try:
        connection.set_schema(schema_name)
        yield
    finally:
        connection.set_schema(previous_schema)
예제 #27
0
    def run_migrations(self, schema_name, included_apps, options):
        self._notice("=== Running migrate for schema %s" % schema_name)
        connection.set_schema(schema_name)
        command = MigrateCommand()

        command.execute(*self.args, **options)
        connection.set_schema_to_public()
예제 #28
0
파일: views.py 프로젝트: demiurg/geokit
def process_shapefile_handler(tenant, layer_id, *args):
    connection.close()
    connection.set_schema(tenant)

    layer = Layer.objects.get(pk=layer_id)
    layer.status = 2
    layer.save()
예제 #29
0
    def handle(self, *args, **options):
        # Connection needs first to be at the public schema, as this is where
        # the database needs to be set before creating a new tenant. If this is
        # not done then django-tenants will raise a "Can't create tenant outside
        # the public schema." error.
        connection.set_schema_to_public()  # Switch to Public.
        # Get the user inputs.
        schema_name = options['schema_name'][0]

        try:
            franchise = SharedFranchise.objects.get(schema_name=schema_name)
        except SharedFranchise.DoesNotExist:
            raise CommandError(_('Franchise does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(franchise.schema_name, True)  # Switch to Tenant.

        for ongoing_job in OngoingWorkOrder.objects.all().order_by(
                'id').iterator():
            jobs = WorkOrder.objects.filter(associate=ongoing_job.associate,
                                            customer=ongoing_job.customer,
                                            is_ongoing=True)

            for job in jobs.iterator():
                job.ongoing_work_order = ongoing_job
                job.save()

                ongoing_job.closed_orders.add(job)

        # For debugging purposes.
        self.stdout.write(self.style.SUCCESS(_('Successfully updated.')))
예제 #30
0
파일: views.py 프로젝트: demiurg/geokit
def vector_catalog_save_layer_handler(tenant, layer, *args):
    connection.close()
    connection.set_schema(tenant)

    layer = Layer.objects.get(pk=layer.id)
    layer.status = 2
    layer.save()
예제 #31
0
    def handle(self, *args, **options):
        # Connection needs first to be at the public schema, as this is where
        # the database needs to be set before creating a new tenant. If this is
        # not done then django-tenants will raise a "Can't create tenant outside
        # the public schema." error.
        connection.set_schema_to_public() # Switch to Public.
        # Get the user inputs.
        schema_name = options['schema_name'][0]

        try:
            franchise = SharedFranchise.objects.get(schema_name=schema_name)

            # Get the current date for this particular franchise.
            now_dt = franchise.get_todays_date_plus_days()
            now_d = now_dt.date()
        except SharedFranchise.DoesNotExist:
            raise CommandError(_('Franchise does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(franchise.schema_name, True) # Switch to Tenant.

        #----------------------------------------------------------------------#
        # ALGORITHM:
        # WE WANT TO FREEZE TIME TO THE `LAST_MODIFIED` DATETIME SO THE RECORD
        # DOES NOT LOOKED LIKE IT WAS MODIFIED. SPECIAL THANKS TO LINK:
        # https://stackoverflow.com/a/40423482
        #----------------------------------------------------------------------#
        start_dt = parser.parse("2019-06-22")
        for away_log in AwayLog.objects.filter(reason=4, start_date__gte=start_dt).iterator(chunk_size=250):
            self.process_away_log(away_log, now_d);

        # For debugging purposes.
        self.stdout.write(
            self.style.SUCCESS(_('Successfully updated.'))
        )
예제 #32
0
    def handle(self, *args, **options):
        """
        Function will get the inputted tenant name and doc_id and
        set the database to the tenant schema and begin processing
        for the particular document.
        """
        schema_name = options['id'][0]
        workspace_id = int_or_none(options['id'][1])

        # the tenant metadata is stored.
        from django.db import connection

        # Connection will set it back to our tenant.
        connection.set_schema(schema_name, True)  # Switch to Tenant.

        api = BizmulaAPI(settings.DOCXPRESSO_PUBLIC_KEY,
                         settings.DOCXPRESSO_PRIVATE_KEY,
                         settings.DOCXPRESSO_URL)

        self.begin_processing(workspace_id, api)

        # Return a success message to the console.
        self.stdout.write(
            self.style.SUCCESS(
                _('Finished processing stage 8 for workspace_id #%s.') %
                str(workspace_id)))
예제 #33
0
def run_migrations(args, options, executor_codename, schema_name, allow_atomic=True):
    from django.core.management import color
    from django.core.management.base import OutputWrapper
    from django.db import connection

    style = color.color_style()

    def style_func(msg):
        return '[%s:%s] %s' % (
            style.NOTICE(executor_codename),
            style.NOTICE(schema_name),
            msg
        )

    connection.set_schema(schema_name)
    stdout = OutputWrapper(sys.stdout)
    stdout.style_func = style_func
    stderr = OutputWrapper(sys.stderr)
    stderr.style_func = style_func
    if int(options.get('verbosity', 1)) >= 1:
        stdout.write(style.NOTICE("=== Starting migration"))
    MigrateCommand(stdout=stdout, stderr=stderr).execute(*args, **options)

    try:
        transaction.commit()
        connection.close()
        connection.connection = None
    except transaction.TransactionManagementError:
        if not allow_atomic:
            raise

        # We are in atomic transaction, don't close connections
        pass

    connection.set_schema_to_public()
예제 #34
0
    def handle(self, *args, **options):
        # Connection needs first to be at the public schema, as this is where
        # the database needs to be set before creating a new tenant. If this is
        # not done then django-tenants will raise a "Can't create tenant outside
        # the public schema." error.
        connection.set_schema_to_public()  # Switch to Public.
        # Get the user inputs.
        schema_name = options['schema_name'][0]

        try:
            franchise = SharedFranchise.objects.get(schema_name=schema_name)
        except SharedFranchise.DoesNotExist:
            raise CommandError(_('Franchise does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(franchise.schema_name, True)  # Switch to Tenant.

        customers = Customer.objects.all()
        for customer in customers.all():
            how_hear_text = customer.how_hear
            if how_hear_text is None or how_hear_text == "":
                customer.how_hear = 1
                customer.how_hear_other = "Did not answer"
                customer.save()

        # For debugging purposes.
        self.stdout.write(self.style.SUCCESS(_('Successfully updated.')))
예제 #35
0
    def handle(self, *args, **options):
        # Get the user inputs.
        schema_name = options['schema_name'][0]
        order_id = int_or_none(options['id'][0])

        try:
            franchise = SharedFranchise.objects.get(schema_name=schema_name)
        except SharedFranchise.DoesNotExist:
            raise CommandError(_('Franchise does not exist!'))

        # Connection will set it back to our tenant.
        connection.set_schema(schema_name, True)  # Switch to Tenant.

        # Defensive Code: Prevent continuing if the ID# does not exist.
        if not WorkOrder.objects.filter(id=order_id).exists():
            raise CommandError(
                _('ID # does not exists, please pick another ID #.'))

        # Create the user.
        work_order = WorkOrder.objects.get(id=order_id)
        work_order.delete()
        self.stdout.write(self.style.SUCCESS(_('Deleted "WorkOrder" object.')))

        # For debugging purposes.
        self.stdout.write(
            self.style.SUCCESS(_('Successfully deleted a tenant account.')))
예제 #36
0
def schema_context(schema_name):
    previous_tenant = connection.tenant
    try:
        connection.set_schema(schema_name)
        yield
    finally:
        if previous_tenant is None:
            connection.set_schema_to_public()
        else:
            connection.set_tenant(previous_tenant)
예제 #37
0
    def execute_command(self, schema, command_name, *args, **options):
        print
        print self.style.NOTICE("=== Switching to schema '")\
              + self.style.SQL_TABLE(schema)\
        + self.style.NOTICE("' then calling %s:" % command_name)

        # sets the schema for the connection
        connection.set_schema(schema)

        # call the original command with the args it knows
        call_command(command_name, *args, **options)
    def run_migrations(self, schema_name, included_apps):
        if int(self.options.get('verbosity', 1)) >= 1:
            self._notice("=== Running migrate for schema %s" % schema_name)

        if not schema_exists(schema_name):
            raise MigrationSchemaMissing('Schema "{}" does not exist'.format(
                schema_name))

        connection.set_schema(schema_name)
        command = MigrateCommand()
        command.execute(*self.args, **self.options)
        connection.set_schema_to_public()
예제 #39
0
def restore_schema(task, **kwargs):
    """ Switches the schema back to the one from before running the task. """
    from tenant_schemas.utils import get_public_schema_name

    schema_name, include_public = getattr(task,
                                          '_old_schema',
                                          (get_public_schema_name(), True))

    # If the schema names match, don't do anything.
    if connection.schema_name == schema_name:
        return

    connection.set_schema(schema_name, include_public=include_public)
예제 #40
0
def restore_schema(task, **kwargs):
    """ Switches the schema back to the one from before running the task. """
    from .compat import get_public_schema_name

    schema_name = get_public_schema_name()
    include_public = True

    if hasattr(task, '_old_schema'):
        schema_name, include_public = task._old_schema

    # If the schema names match, don't do anything.
    if connection.schema_name == schema_name:
        return

    connection.set_schema(schema_name, include_public=include_public)
    def run_migrations(self, schema_name, included_apps):
        self._notice("=== Running migrate for schema %s" % schema_name)
        connection.set_schema(schema_name)
        command = MigrateCommand()

        defaults = {}
        for opt in MigrateCommand.option_list:
            if opt.dest in self.options:
                defaults[opt.dest] = self.options[opt.dest]
            elif opt.default is NO_DEFAULT:
                defaults[opt.dest] = None
            else:
                defaults[opt.dest] = opt.default

        command.execute(*self.args, **defaults)
        connection.set_schema_to_public()
    def run_migrations(self, schema_name, included_apps):
        self._notice("=== Running migrate for schema %s" % schema_name)
        connection.set_schema(schema_name, include_public=False)
        apps.app_configs = OrderedDict()
        apps.clear_cache()
        apps.set_installed_apps(included_apps)

        command = MigrateCommand()

        defaults = {}
        for opt in MigrateCommand.option_list:
            if opt.dest in self.options:
                defaults[opt.dest] = self.options[opt.dest]
            elif opt.default is NO_DEFAULT:
                defaults[opt.dest] = None
            else:
                defaults[opt.dest] = opt.default

        command.execute(*self.args, **defaults)

        connection.set_schema('public', include_public=True)
        apps.app_configs = OrderedDict()
        apps.clear_cache()
        apps.set_installed_apps(settings.SHARED_APPS)
예제 #43
0
 def handle(self, *args, **options):
     schema = options.get('schema')
     connection.set_schema(schema)
     super(Command, self).handle(*args, **options)
     connection.set_schema_to_public()
예제 #44
0
def create_admin(self, request, queryset):
    form = None
    # u = User.objects.get(pk=request.user.pk)

    if 'apply' in request.POST:
        form = CreateAdminForm(request.POST)

        if form.is_valid():
            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']

            for obj in queryset:
                connection.set_schema(obj.schema_name, include_public=False)

                user = User.objects.create_user(username, email, password)

                user.is_staff = True
                user.is_active = True
                user.is_superuser = True
                user.save()

                # adicionando os status
                s = {'Tramitando', 'Arquivado', 'Parado', 'Entregue'}
                status_check = Status.objects.filter(nome__in=s)
                if not status_check:
                    for i in s:
                        new_status = Status(nome=i)
                        new_status.save()

                # adicionando os tipos de instituicao
                ti = {'Externa', 'Interna'}
                tipo_inst_check = TipoInstituicao.objects.filter(nome__in=ti)
                if not tipo_inst_check:
                    for i in ti:
                        new_tipoinst = TipoInstituicao(nome=i)
                        new_tipoinst.save()

                # adicionando os carateres
                c = {'Normal', 'Urgente'}
                carater_check = Carater.objects.filter(nome__in=c)
                if not carater_check:
                    for i in c:
                        new_carater = Carater(nome=i)
                        new_carater.save()

                # adicionando as naturezas
                n = {'Aberto', 'Confidencial'}
                natureza_check = Natureza.objects.filter(nome__in=c)
                if not carater_check:
                    for i in n:
                        new_natureza = Natureza(nome=i)
                        new_natureza.save()

                connection.set_schema_to_public()

                messages.success(request, 'Admin "%s" para Cliente "%s": \
                                 criado com sucesso.' % (username, obj.name))

                return HttpResponseRedirect(request.get_full_path())

    if not form:
        form = CreateAdminForm(initial={'_selected_action':
                               request.POST.getlist(ACTION_CHECKBOX_NAME)})
                               # request=request)

    opts = self.model._meta
    app_label = opts.app_label
    module_name = opts.module_name,

    context = {
        'title': "Criar Administrador",
        'opts': opts,
        'app_label': app_label,
        'module_name': module_name,
        'create_form': form,
    }
    return TemplateResponse(request, 'admin/create_admin.html',
                            context, current_app=self.admin_site.name)