Example #1
0
    def handle(self, *args, **options):
        data_source, model_name = options.pop('data_source'), options.pop('model_name')

        # Getting the OGR DataSource from the string parameter.
        try:
            ds = gdal.DataSource(data_source)
        except gdal.GDALException as msg:
            raise CommandError(msg)

        # Returning the output of ogrinspect with the given arguments
        # and options.
        from django.contrib.gis.utils.ogrinspect import _ogrinspect, mapping
        # Filter options to params accepted by `_ogrinspect`
        ogr_options = {k: v for k, v in options.items()
                       if k in get_func_args(_ogrinspect) and v is not None}
        output = [s for s in _ogrinspect(ds, model_name, **ogr_options)]

        if options['mapping']:
            # Constructing the keyword arguments for `mapping`, and
            # calling it on the data source.
            kwargs = {
                'geom_name': options['geom_name'],
                'layer_key': options['layer_key'],
                'multi_geom': options['multi_geom'],
            }
            mapping_dict = mapping(ds, **kwargs)
            # This extra legwork is so that the dictionary definition comes
            # out in the same order as the fields in the model definition.
            rev_mapping = {v: k for k, v in mapping_dict.items()}
Example #2
0
    def get_readonly_fields(self, request, obj=None):
        args = get_func_args(self.has_add_permission)
        if 'obj' in args:
            has_add_permission = self.has_add_permission(request, obj)
        else:
            has_add_permission = self.has_add_permission(request)

        if obj is None and has_add_permission:
            return super().get_readonly_fields(request, obj)

        if self.fields or self.fieldsets:
            fields = flatten_fieldsets(self.get_fieldsets(request, obj))
        else:
            opts = self.model._meta
            sortable_private_fields = [f for f in opts.private_fields if isinstance(f, Field)]

            fields = [
                field.name for field in
                sorted(chain(opts.concrete_fields, sortable_private_fields, opts.many_to_many))
                if field.editable and not field.auto_created
            ]

        exclude = self.get_exclude(request, obj)
        editable_fields = self.get_editable_fields(request, obj)
        return [
            field for field in fields
            if field not in editable_fields and field not in exclude
        ]
Example #3
0
    def handle(self, *args, **options):
        data_source, model_name = options.pop("data_source"), options.pop("model_name")

        # Getting the OGR DataSource from the string parameter.
        try:
            ds = gdal.DataSource(data_source)
        except gdal.GDALException as msg:
            raise CommandError(msg)

        # Returning the output of ogrinspect with the given arguments
        # and options.
        from django.contrib.gis.utils.ogrinspect import _ogrinspect, mapping

        # Filter options to params accepted by `_ogrinspect`
        ogr_options = {
            k: v
            for k, v in options.items()
            if k in get_func_args(_ogrinspect) and v is not None
        }
        output = [s for s in _ogrinspect(ds, model_name, **ogr_options)]

        if options["mapping"]:
            # Constructing the keyword arguments for `mapping`, and
            # calling it on the data source.
            kwargs = {
                "geom_name": options["geom_name"],
                "layer_key": options["layer_key"],
                "multi_geom": options["multi_geom"],
            }
            mapping_dict = mapping(ds, **kwargs)
            # This extra legwork is so that the dictionary definition comes
            # out in the same order as the fields in the model definition.
            rev_mapping = {v: k for k, v in mapping_dict.items()}
            output.extend(
                [
                    "",
                    "",
                    "# Auto-generated `LayerMapping` dictionary for %s model"
                    % model_name,
                    "%s_mapping = {" % model_name.lower(),
                ]
            )
            output.extend(
                "    '%s': '%s'," % (rev_mapping[ogr_fld], ogr_fld)
                for ogr_fld in ds[options["layer_key"]].fields
            )
            output.extend(
                [
                    "    '%s': '%s',"
                    % (options["geom_name"], mapping_dict[options["geom_name"]]),
                    "}",
                ]
            )
        return "\n".join(output) + "\n"
Example #4
0
 def _check_has_add_permission(self, obj):
     cls = obj.__class__
     try:
         func = cls.has_add_permission
     except AttributeError:
         pass
     else:
         args = get_func_args(func)
         if 'obj' not in args:
             warnings.warn(
                 "Update %s.has_add_permission() to accept a positional "
                 "`obj` argument." % cls.__name__, RemovedInDjango30Warning)
Example #5
0
 def _check_has_add_permission(self, obj):
     cls = obj.__class__
     try:
         func = cls.has_add_permission
     except AttributeError:
         pass
     else:
         args = get_func_args(func)
         if 'obj' not in args:
             warnings.warn(
                 "Update %s.has_add_permission() to accept a positional "
                 "`obj` argument." % cls.__name__, RemovedInDjango30Warning
             )
Example #6
0
    def handle(self, *args, **options):
        data_source, model_name = options.pop('data_source'), options.pop(
            'model_name')
        if not gdal.HAS_GDAL:
            raise CommandError(
                'GDAL is required to inspect geospatial data sources.')

        # Getting the OGR DataSource from the string parameter.
        try:
            ds = gdal.DataSource(data_source)
        except gdal.GDALException as msg:
            raise CommandError(msg)

        # Returning the output of ogrinspect with the given arguments
        # and options.
        from django.contrib.gis.utils.ogrinspect import _ogrinspect, mapping
        # Filter options to params accepted by `_ogrinspect`
        ogr_options = {
            k: v
            for k, v in options.items()
            if k in get_func_args(_ogrinspect) and v is not None
        }
        output = [s for s in _ogrinspect(ds, model_name, **ogr_options)]

        if options['mapping']:
            # Constructing the keyword arguments for `mapping`, and
            # calling it on the data source.
            kwargs = {
                'geom_name': options['geom_name'],
                'layer_key': options['layer_key'],
                'multi_geom': options['multi_geom'],
            }
            mapping_dict = mapping(ds, **kwargs)
            # This extra legwork is so that the dictionary definition comes
            # out in the same order as the fields in the model definition.
            rev_mapping = {v: k for k, v in mapping_dict.items()}
            output.extend([
                '',
                '# Auto-generated `LayerMapping` dictionary for %s model' %
                model_name,
                '%s_mapping = {' % model_name.lower()
            ])
            output.extend("    '%s' : '%s'," % (rev_mapping[ogr_fld], ogr_fld)
                          for ogr_fld in ds[options['layer_key']].fields)
            output.extend([
                "    '%s' : '%s'," %
                (options['geom_name'], mapping_dict[options['geom_name']]), '}'
            ])
        return '\n'.join(output) + '\n'
    def __init__(self, func):

        # Store the reference to the registered function
        self.function = func

        # @rpc_method decorator parameters
        self._external_name = getattr(func, 'modernrpc_name', func.__name__)
        self.entry_point = getattr(func, 'modernrpc_entry_point')
        self.protocol = getattr(func, 'modernrpc_protocol')
        self.str_standardization = getattr(func, 'str_standardization')
        self.str_std_encoding = getattr(func, 'str_standardization_encoding')
        # Authentication related attributes
        self.predicates = getattr(func, 'modernrpc_auth_predicates', None)
        self.predicates_params = getattr(func,
                                         'modernrpc_auth_predicates_params',
                                         ())

        # List method's positional arguments
        # We can't use django.utils.inspect.get_func_args() with Python 2, because this function remove the first
        # argument in returned list. This is supposed to remove the first 'self' argument, but doesn't fork well
        # for global functions.
        # For Python 2, we will prefer django.utils.inspect.getargspec(func)[0]. This will work as expected, even if
        # the function has been removed in Django 2.0, since Django 2 doesn't work with Python 2
        self.args = inspect.get_func_args(
            func) if six.PY3 else inspect.getargspec(func)[0]
        # Does the method accept additional kwargs dict?
        self.accept_kwargs = inspect.func_accepts_kwargs(func)

        # Contains the signature of the method, as returned by "system.methodSignature"
        self.signature = []
        # Contains the method's docstring, in HTML form
        self.html_doc = ''
        # Contains doc about arguments and their type. We store this in an ordered dict, so the args documentation
        # keep the order defined in docstring
        self.args_doc = collections.OrderedDict()
        # Contains doc about return type and return value
        self.return_doc = {}

        # Docstring parsing
        self.raw_docstring = self.parse_docstring(func.__doc__)
        self.html_doc = self.raw_docstring_to_html(self.raw_docstring)
Example #8
0
    def handle(self, *args, **options):
        data_source, model_name = options.pop('data_source'), options.pop('model_name')
        if not gdal.HAS_GDAL:
            raise CommandError('GDAL is required to inspect geospatial data sources.')

        # Getting the OGR DataSource from the string parameter.
        try:
            ds = gdal.DataSource(data_source)
        except gdal.GDALException as msg:
            raise CommandError(msg)

        # Returning the output of ogrinspect with the given arguments
        # and options.
        from django.contrib.gis.utils.ogrinspect import _ogrinspect, mapping
        # Filter options to params accepted by `_ogrinspect`
        ogr_options = {k: v for k, v in options.items()
                       if k in get_func_args(_ogrinspect) and v is not None}
        output = [s for s in _ogrinspect(ds, model_name, **ogr_options)]

        if options['mapping']:
            # Constructing the keyword arguments for `mapping`, and
            # calling it on the data source.
            kwargs = {
                'geom_name': options['geom_name'],
                'layer_key': options['layer_key'],
                'multi_geom': options['multi_geom'],
            }
            mapping_dict = mapping(ds, **kwargs)
            # This extra legwork is so that the dictionary definition comes
            # out in the same order as the fields in the model definition.
            rev_mapping = {v: k for k, v in mapping_dict.items()}
            output.extend(['', '# Auto-generated `LayerMapping` dictionary for %s model' % model_name,
                           '%s_mapping = {' % model_name.lower()])
            output.extend("    '%s' : '%s'," % (
                rev_mapping[ogr_fld], ogr_fld) for ogr_fld in ds[options['layer_key']].fields
            )
            output.extend(["    '%s' : '%s'," % (options['geom_name'], mapping_dict[options['geom_name']]), '}'])
        return '\n'.join(output) + '\n'
Example #9
0
    def serialize(self):

        def _write(_arg_name, _arg_value):
            if (_arg_name in self.operation.serialization_expand_args and
                    isinstance(_arg_value, (list, tuple, dict))):
                if isinstance(_arg_value, dict):
                    self.feed('%s={' % _arg_name)
                    self.indent()
                    for key, value in _arg_value.items():
                        key_string, key_imports = MigrationWriter.serialize(key)
                        arg_string, arg_imports = MigrationWriter.serialize(value)
                        args = arg_string.splitlines()
                        if len(args) > 1:
                            self.feed('%s: %s' % (key_string, args[0]))
                            for arg in args[1:-1]:
                                self.feed(arg)
                            self.feed('%s,' % args[-1])
                        else:
                            self.feed('%s: %s,' % (key_string, arg_string))
                        imports.update(key_imports)
                        imports.update(arg_imports)
                    self.unindent()
                    self.feed('},')
                else:
                    self.feed('%s=[' % _arg_name)
                    self.indent()
                    for item in _arg_value:
                        arg_string, arg_imports = MigrationWriter.serialize(item)
                        args = arg_string.splitlines()
                        if len(args) > 1:
                            for arg in args[:-1]:
                                self.feed(arg)
                            self.feed('%s,' % args[-1])
                        else:
                            self.feed('%s,' % arg_string)
                        imports.update(arg_imports)
                    self.unindent()
                    self.feed('],')
            else:
                arg_string, arg_imports = MigrationWriter.serialize(_arg_value)
                args = arg_string.splitlines()
                if len(args) > 1:
                    self.feed('%s=%s' % (_arg_name, args[0]))
                    for arg in args[1:-1]:
                        self.feed(arg)
                    self.feed('%s,' % args[-1])
                else:
                    self.feed('%s=%s,' % (_arg_name, arg_string))
                imports.update(arg_imports)

        imports = set()
        name, args, kwargs = self.operation.deconstruct()
        operation_args = get_func_args(self.operation.__init__)

        # See if this operation is in django.db.migrations. If it is,
        # We can just use the fact we already have that imported,
        # otherwise, we need to add an import for the operation class.
        if getattr(migrations, name, None) == self.operation.__class__:
            self.feed('migrations.%s(' % name)
        else:
            imports.add('import %s' % (self.operation.__class__.__module__))
            self.feed('%s.%s(' % (self.operation.__class__.__module__, name))

        self.indent()

        for i, arg in enumerate(args):
            arg_value = arg
            arg_name = operation_args[i]
            _write(arg_name, arg_value)

        i = len(args)
        # Only iterate over remaining arguments
        for arg_name in operation_args[i:]:
            if arg_name in kwargs:  # Don't sort to maintain signature order
                arg_value = kwargs[arg_name]
                _write(arg_name, arg_value)

        self.unindent()
        self.feed('),')
        return self.render(), imports
Example #10
0
    def serialize(self):
        def _write(_arg_name, _arg_value):
            if (_arg_name in self.operation.serialization_expand_args
                    and isinstance(_arg_value, (list, tuple, dict))):
                if isinstance(_arg_value, dict):
                    self.feed('%s={' % _arg_name)
                    self.indent()
                    for key, value in _arg_value.items():
                        key_string, key_imports = MigrationWriter.serialize(
                            key)
                        arg_string, arg_imports = MigrationWriter.serialize(
                            value)
                        args = arg_string.splitlines()
                        if len(args) > 1:
                            self.feed('%s: %s' % (key_string, args[0]))
                            for arg in args[1:-1]:
                                self.feed(arg)
                            self.feed('%s,' % args[-1])
                        else:
                            self.feed('%s: %s,' % (key_string, arg_string))
                        imports.update(key_imports)
                        imports.update(arg_imports)
                    self.unindent()
                    self.feed('},')
                else:
                    self.feed('%s=[' % _arg_name)
                    self.indent()
                    for item in _arg_value:
                        arg_string, arg_imports = MigrationWriter.serialize(
                            item)
                        args = arg_string.splitlines()
                        if len(args) > 1:
                            for arg in args[:-1]:
                                self.feed(arg)
                            self.feed('%s,' % args[-1])
                        else:
                            self.feed('%s,' % arg_string)
                        imports.update(arg_imports)
                    self.unindent()
                    self.feed('],')
            else:
                arg_string, arg_imports = MigrationWriter.serialize(_arg_value)
                args = arg_string.splitlines()
                if len(args) > 1:
                    self.feed('%s=%s' % (_arg_name, args[0]))
                    for arg in args[1:-1]:
                        self.feed(arg)
                    self.feed('%s,' % args[-1])
                else:
                    self.feed('%s=%s,' % (_arg_name, arg_string))
                imports.update(arg_imports)

        imports = set()
        name, args, kwargs = self.operation.deconstruct()
        operation_args = get_func_args(self.operation.__init__)

        # See if this operation is in django.db.migrations. If it is,
        # We can just use the fact we already have that imported,
        # otherwise, we need to add an import for the operation class.
        if getattr(migrations, name, None) == self.operation.__class__:
            self.feed('migrations.%s(' % name)
        else:
            imports.add('import %s' % (self.operation.__class__.__module__))
            self.feed('%s.%s(' % (self.operation.__class__.__module__, name))

        self.indent()

        for i, arg in enumerate(args):
            arg_value = arg
            arg_name = operation_args[i]
            _write(arg_name, arg_value)

        i = len(args)
        # Only iterate over remaining arguments
        for arg_name in operation_args[i:]:
            if arg_name in kwargs:  # Don't sort to maintain signature order
                arg_value = kwargs[arg_name]
                _write(arg_name, arg_value)

        self.unindent()
        self.feed('),')
        return self.render(), imports
Example #11
0
def _basename_or_base_name(basename):
    # freaking DRF... TODO: remove when dropping support for DRF 3.8
    if 'basename' in get_func_args(routers.BaseRouter.register):
        return {'basename': basename}
    else:
        return {'base_name': basename}
Example #12
0
    def serialize(self, app):
        d = {}

        def _write(_arg_name, _arg_value):
            if (_arg_name in self.operation.serialization_expand_args and
                    isinstance(_arg_value, (list, tuple, dict))):
                if isinstance(_arg_value, dict):
                    ds = {}
                    for a, b in _arg_value.items():
                        if any([isinstance(b, str), isinstance(b, list), isinstance(b, dict), isinstance(b, bool), isinstance(b, float), isinstance(b, int)]) or b is not None:
                            ds[a] = b
                        else:
                            ds[a] = str(b)
                    d[_arg_name] = ds
                else:
                    f = []
                    for item in _arg_value:
                        if isinstance(item, tuple):
                            if len(item) == 2:
                                props = {}
                                i = item[1].__dict__
                                props["type_name"] = fullname(item[1])
                                props["choices"] = i.get("choices", None)
                                props["blank"] = i.get("blank", True)
                                props["is_null"] = i.get("null", True)
                                props["primary_key"] = i.get("primary_key", False)
                                props["help_text"] = i.get("help_text", '')
                                props["max_length"] = i.get("max_length", None)
                                props["verbose_name"] = i.get("verbose_name", None)
                                if "default" in i:
                                    props["default"] = str(i["default"]) if type(i["default"]) not in [set, list, dict,
                                                                                                       int, float, bool, type(None)] else \
                                    i["default"]
                                else:
                                    props["default"] = None

                                f.append({'name': str(item[0]), 'props': props})
                            else:
                                f.append(list(item))
                        elif any([isinstance(item, str), isinstance(item, list),
                                  isinstance(item, dict), isinstance(item, bool),
                                  isinstance(item, float),
                                  isinstance(item, int)]) or item is None:
                            f.append(item)
                        else:
                            f.append(str(item))
                    d[_arg_name] = f
            elif isinstance(_arg_value, ForeignKey):
                ab = {
                    "many_to_many": bool(_arg_value.many_to_many),
                    "many_to_one": bool(_arg_value.many_to_one),
                    "one_to_many": bool(_arg_value.one_to_many),
                    "one_to_one": bool(_arg_value.one_to_one),
                    "field_str": str(_arg_value),
                    "to": str(_arg_value.remote_field.model).replace("__fake__.", "").replace("<class", "").replace("'", "").replace(">", "").replace(" ", ""),
                }
                d[_arg_name] = ab
                d["related"] = True
            elif isinstance(_arg_value, ManyToManyField):
                ab = {
                    "many_to_many": bool(_arg_value.many_to_many),
                    "many_to_one": bool(_arg_value.many_to_one),
                    "one_to_many": bool(_arg_value.one_to_many),
                    "one_to_one": bool(_arg_value.one_to_one),
                    "field_str": str(_arg_value),
                    "to": str(_arg_value.remote_field.model).replace("__fake__.", "").replace("<class", "").replace("'", "").replace(">", "").replace(" ", ""),
                }
                d[_arg_name] = ab
                d["related"] = True
            elif any([isinstance(_arg_value, str), isinstance(_arg_value, list), isinstance(_arg_value, dict), isinstance(_arg_value, bool), isinstance(_arg_value, float), isinstance(_arg_value, int)]) or _arg_value is None:
                d[_arg_name] = _arg_value
            else:
                d[_arg_name] = str(_arg_value)
        name, args, kwargs = self.operation.deconstruct()
        operation_args = get_func_args(self.operation.__init__)

        for i, arg in enumerate(args):
            arg_value = arg
            arg_name = operation_args[i]
            _write(arg_name, arg_value)

        i = len(args)
        for arg_name in operation_args[i:]:
            if arg_name in kwargs:
                arg_value = kwargs[arg_name]
                _write(arg_name, arg_value)
        if "name" in d:
            d["name"] = app + "." + d["name"]
        return d
Example #13
0
from __future__ import unicode_literals
import argparse