Пример #1
0
    async def test_container_specs_consumer(self):
        communicator = WebsocketCommunicator(
            application, f'/ws/sandbox/container-specs/{self.sandbox.pk}/')
        communicator.scope["user"] = self.user
        await communicator.connect()

        _, container_specs = await self.sandbox.poll_specifications()
        data_container_specs = DjangoJSONEncoder().encode(
            await database_sync_to_async(dgeq.serialize)(container_specs))
        await self.channel_layer.group_send(
            f"sandbox_container_specs_{self.sandbox.pk}", {
                'type': 'container_specs',
                'specs': data_container_specs
            })
        result = await communicator.receive_from()
        self.assertEqual(data_container_specs, result)
        await communicator.disconnect()
Пример #2
0
 def handle_object(self, object):
     """ Called to handle everything, looks for the correct handling """
     # print type(object)
     # print inspect.isclass(object)
     # print inspect.ismethod(object)
     # print inspect.isfunction(object)
     # print inspect.isbuiltin(object)
     # print inspect.isroutine(object)
     # print inspect.isabstract(object)
     # print type(object) == 'staticmethod'
     if (inspect.isroutine(object) or inspect.isbuiltin(object)
             or inspect.isclass(object)):
         raise UnableToSerializeMethodTypesError(type(object))
     elif isinstance(object, dict):
         return self.handle_dictionary(object)
     elif (isinstance(object, list) or isinstance(object, tuple)):
         return self.handle_list(object)
     elif isinstance(object, Model):
         #return super(JSONSerializer,self).serialize([object], **self.options.copy())[0]
         return self.handle_object(model_to_dict(object))
         return PythonSerializer().serialize(
             [object], **self.options.copy())[0]['fields']
     elif isinstance(object, QuerySet):
         #return super(JSONSerializer,self).serialize(object, **self.options.copy())[0]
         ret = []
         for item in object:
             ret.append(self.handle_object(item))
         return ret
     elif (isinstance(object, int) or isinstance(object, float)
           or isinstance(object, long) or isinstance(object, basestring)
           or isinstance(object, bool) or object is None):
         return object
     elif (isinstance(object, datetime.datetime)
           or isinstance(object, datetime.date)
           or isinstance(object, datetime.time)
           or isinstance(object, decimal.Decimal)):
         return DjangoJSONEncoder().default(object)
     elif isinstance(object, GEOSGeometry):
         return getattr(object, self.geom_format)
     elif isinstance(object, File):
         return object.name
     elif hasattr(object, '__dict__'):
         return self.handle_dictionary(object.__dict__)
     else:
         raise UnableToSerializeError(type(object))
Пример #3
0
    def create_articles(self, project, articleset, json_data=None, **options):
        """Create one or more articles in the set. Provide the needed arguments using the json_data or with key-value pairs

        json_data can be a dictionary or list of dictionaries. Each dict can contain a 'children' attribute which
        is another list of dictionaries. 
        """
        url = article_url.format(**locals())
        if json_data is None:  #TODO duplicated from create_set, move into requests (or separate post method?)
            # form encoded request
            return self.request(url, method="post", data=options)
        else:
            if not isinstance(json_data, str):
                json_data = DjangoJSONEncoder().encode(json_data)
            headers = {'content-type': 'application/json'}
            return self.request(url,
                                method='post',
                                data=json_data,
                                headers=headers)
Пример #4
0
 def add_run_fields(fields, run, prefix):
     dumped_run = TrackerSerializer(models.SpeedRun, request).serialize([run])[0]
     for key, value in dumped_run['fields'].items():
         if key not in [
             'canonical_url',
             'endtime',
             'name',
             'starttime',
             'display_name',
             'order',
         ]:
             continue
         try:
             value = DjangoJSONEncoder().default(value)
         except TypeError:
             pass
         fields[prefix + '__' + key] = value
     fields[prefix + '__public'] = str(run)
Пример #5
0
def _render_app_html(request, initial_json):
    html = loader.render_to_string('app.html')
    ui_version = re.search('static/app-(.*)\.js', html).group(1)
    initial_json['meta'] = {
        'version': '{}-{}'.format(SEQR_VERSION, ui_version),
        'hijakEnabled': DEBUG or False,
        'googleLoginEnabled': google_auth_enabled(),
    }

    html = html.replace(
        "window.initialJSON=null", "window.initialJSON=" +
        json.dumps(initial_json, default=DjangoJSONEncoder().default))

    if request.get_host() == 'localhost:3000':
        html = re.sub(r'static/app(-.*)js', 'app.js', html)
        html = re.sub(r'<link\s+href="/static/app.*css"[^>]*>', '', html)

    return HttpResponse(html, content_type="text/html")
Пример #6
0
    async def test_usage_consumer(self):
        communicator = WebsocketCommunicator(
            application, f'/ws/sandbox/sandbox-usages/{self.sandbox.pk}/')
        communicator.scope["user"] = self.user
        await communicator.connect()

        usage = await self.sandbox.poll_usage()
        data = DjangoJSONEncoder().encode(await
                                          database_sync_to_async(dgeq.serialize
                                                                 )(usage))
        await self.channel_layer.group_send(f"sandbox_usage_{self.sandbox.pk}",
                                            {
                                                'type': 'sandbox_usage',
                                                'usage': data
                                            })
        result = await communicator.receive_from()
        self.assertEqual(data, result)
        await communicator.disconnect()
Пример #7
0
    def _purchase_to_json(self, purchase):
        from . import utils
        result = {
            'id': utils.get_purchase_number(purchase),
            'pk': purchase.pk,
            'tickets': [],
            'total': purchase.payment_total,
            'currency': 'EUR',
            'status': purchase.state,
            'comments': purchase.comments if purchase.comments else None,
            'date_added': purchase.date_added.replace(microsecond=0),
            'payment_address': {
                'email': purchase.customer.email,
                'first_name': purchase.first_name,
                'last_name': purchase.last_name,
                'company': purchase.company_name,
                'address_line': purchase.street,
                'postal_code': purchase.zip_code,
                'country': purchase.country,
                'city': purchase.city,
                'vat_id': purchase.vat_id if purchase.vat_id else None
            },
            'payment_info': {
                'method': purchase.payment_method,
                'transaction_id': purchase.payment_transaction
            }
        }

        for ticket in models.Ticket.objects.select_related(
                'ticket_type', 'voucher').filter(purchase=purchase).all():
            result['tickets'].append({
                'pk': ticket.pk,
                'first_name': ticket.first_name,
                'last_name': ticket.last_name,
                'voucher': None,
                'type': {
                    'product_number': ticket.ticket_type.product_number,
                    'name': ticket.ticket_type.name,
                    'pk': ticket.ticket_type.pk
                },
                'price': ticket.ticket_type.fee
            })

        return DjangoJSONEncoder(indent=2).encode(result)
Пример #8
0
def json_in_script_tag(serialized_data):
    """Convert serialized data to HTML <script>-safe JSON.

    Example usage:

        <script>
            window.foo = {{foo|json_serialized_data}}
        </script>

    To render, we:

        1. JSON-encode, using Django's default encoder (to encode
           datetime as string, for instance).
        2. Replace `<` with `\u003c`, to prevent injection of `</script>` in
           the JSON.
    """
    raw = DjangoJSONEncoder().encode(serialized_data)
    escaped = potential_hack_chars.sub(escape_potential_hack_char, raw)
    return mark_safe(escaped)
Пример #9
0
def wishlist_add_ajax(request, template="shop/json.html"):
    data = {'errors': []}
    product = None
    contact = None
    formdata = request.POST.copy()
    productslug = formdata['productname']

    log.debug('WISHLIST AJAX: slug=%s', productslug)
    try:
        product, details = product_from_post(productslug, formdata)

    except (Product.DoesNotExist, MultiValueDictKeyError):
        log.warn("Could not find product: %s", productslug)
        product = None

    if not product:
        data['errors'].append(
            ('product', _('The product you have requested does not exist.')))
    else:
        data['id'] = product.id
        data['name'] = product.translated_name()

    try:
        contact = Contact.objects.from_request(request)
    except Contact.DoesNotExist:
        log.warn("Could not find contact")

    if not contact:
        data['errors'].append(
            ('contact',
             _('The contact associated with this request does not exist.')))

    if not data['errors']:
        wish = ProductWish.objects.create_if_new(product, contact, details)
        data['results'] = _('Success')
    else:
        data['results'] = _('Error')

    encoded = DjangoJSONEncoder().encode(data)
    encoded = mark_safe(encoded)
    log.debug('WISHLIST AJAX: %s', data)

    return render_to_response(template, {'json': encoded})
Пример #10
0
def map(request):
    items = OpenStreetMaps.objects.all()
    json_items = [{
        'location': item.location,
        'location_lat': item.location_lat,
        'location_lon': item.location_lon
    } for item in items]
    if request.method == 'POST':
        form = OpenStreetMapsForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse('success!')
    else:
        form = OpenStreetMapsForm()
        context = {
            'form': form,
            'object_json': mark_safe(DjangoJSONEncoder().encode(json_items)),
        }
    return render(request, 'osm.html', context)
Пример #11
0
def _recursive_escape(value, esc=conditional_escape):
    """
    Recursively escapes strings in an object.

    Traverses dict, list and tuples. These are the data structures supported
    by the JSON encoder.
    """
    if isinstance(value, dict):
        return type(value)((esc(k), _recursive_escape(v)) for (k, v) in value.items())
    elif isinstance(value, (list, tuple)):
        return type(value)(_recursive_escape(v) for v in value)
    elif isinstance(value, str):
        return esc(value)
    elif isinstance(value, (int, float)) or value in (True, False, None):
        return value
    # We've exhausted all the types acceptable by the default JSON encoder.
    # Django's improved JSON encoder handles a few other types, all of which
    # are represented by strings. For these types, we apply JSON encoding
    # immediately and then escape the result.
    return esc(DjangoJSONEncoder().default(value))
Пример #12
0
    def __init__(self, verbose_name=None, name=None,
                 encoder=DjangoJSONEncoder(), decoder=simplejson.JSONDecoder(),
                 datatype=dict,
                 **kwargs):
        """
        Create a new JSONField

        :param verbose_name:   The verbose name of the field
        :param name:    The short name of the field.
        :param encoder:   The encoder used to turn native datatypes into JSON.
        :param decoder:   The decoder used to turn JSON into native datatypes.
        :param datatype:  The native datatype to store.
        :param kwargs:    Other arguments to pass to parent constructor.
        """
        blank = kwargs.pop('blank', True)
        models.TextField.__init__(self, verbose_name, name, blank=blank,
                                  **kwargs)
        self.encoder = encoder
        self.decoder = decoder
        self.datatype = datatype
Пример #13
0
def create_json_response(obj, **kwargs):
    """Encodes the give object into json and create a django JsonResponse object with it.

    Args:
        obj (object): json response object
        **kwargs: any addition args to pass to the JsonResponse constructor
    Returns:
        JsonResponse
    """

    dumps_params = {
        'sort_keys': True,
        'indent': 4,
        'default': DjangoJSONEncoder().default
    }

    return JsonResponse(obj,
                        json_dumps_params=dumps_params,
                        encoder=DjangoJSONEncoder,
                        **kwargs)
Пример #14
0
 def add_parent_fields(fields, parent, prefix):
     dumped_bid = TrackerSerializer(models.Bid, request).serialize([parent])[0]
     for key, value in dumped_bid['fields'].items():
         if key not in [
             'canonical_url',
             'name',
             'state',
             'goal',
             'allowuseroptions',
             'option_max_length',
             'total',
             'count',
         ]:
             continue
         try:
             value = DjangoJSONEncoder().default(value)
         except TypeError:
             pass
         fields[prefix + '__' + key] = value
     fields[prefix + '__public'] = str(parent)
Пример #15
0
def default(o):
    if isinstance(o, models.Model):
        return o.pk

    if isinstance(o, models.QuerySet):
        return list(o.values_list('pk', flat=True))

    if isinstance(o, FieldFile):
        return o.url if o else None

    if isinstance(o, (Generator, set)):
        return list(o)

    if hasattr(o, 'geojson'):
        return loads(o.geojson)

    if hasattr(o, '__json__'):
        return o.__json__()

    return DjangoJSONEncoder().default(o)
Пример #16
0
class WebsocketBindingWithMembers(WebsocketBinding):
    """
    Outgoing binding binding subclass based on WebsocketBinding.
    Additionally enables sending of member variables, properties and methods.
    Member methods can only have self as a required argument.
    Just add the name of the member to the send_members-list.
    Example:

    class MyModel(models.Model):
        my_field = models.IntegerField(default=0)
        my_var = 3

        @property
        def my_property(self):
            return self.my_var + self.my_field

        def my_function(self):
            return self.my_var - self.my_vield

    class MyBinding(BindingWithMembersMixin, WebsocketBinding):
        model = MyModel
        stream = 'mystream'

        send_members = ['my_var', 'my_property', 'my_function']
    """

    model = None
    send_members = []

    encoder = DjangoJSONEncoder()

    def serialize_data(self, instance):
        data = super(WebsocketBindingWithMembers,
                     self).serialize_data(instance)
        for m in self.send_members:
            member = getattr(instance, m)
            if callable(member):
                data[m] = self.encoder.encode(member())
            else:
                data[m] = self.encoder.encode(member)
        return data
Пример #17
0
    def save(self, old_record, list_record, detail_record):
        if old_record is not None:
            return

        application_type = self.get_or_create_lookup(
            'application_type', list_record['Application Type'],
            list_record['Application Type'])
        license_types = [
            self.get_or_create_lookup('license_type',
                                      lt,
                                      lt,
                                      make_text_slug=False)
            for lt in list_record['license_types']
        ]
        category = self.get_or_create_lookup('category',
                                             list_record['category'],
                                             list_record['category'],
                                             make_text_slug=False)

        json_data = {
            'business_name': list_record['business_name'],
            'new_business_name': list_record['new_business_name'],
            'new_address': list_record['new_address'],
        }

        attributes = {
            'applicant': list_record['applicant'],
            'new_applicant': list_record['new_applicant'],
            'license_number': list_record['License Number'],
            'category': category.id,
            'application_type': application_type.id,
            'license_type': ','.join([str(lt.id) for lt in license_types]),
            'details': DjangoJSONEncoder().encode(json_data),
        }
        self.create_newsitem(
            attributes,
            title=list_record['title'],
            item_date=list_record['item_date'],
            location_name=list_record['clean_address'],
        )
Пример #18
0
def render_with_initial_json(html_page, initial_json):
    """Uses django template rendering utilities to read in the given html file, and embed the
    given object as json within the page. This way when the browser sends an initial request
    for the page, it comes back with the json bundle already embedded in it.

    Args:
        html_page (string): path of html template
        initial_json (object): the object to be serialized to json
    Returns:
        HttpResponse: django HttpRepsonse object to send back to the client
    """

    initial_json_str = json.dumps(initial_json,
                                  sort_keys=True,
                                  indent=4,
                                  default=DjangoJSONEncoder().default)

    html = loader.render_to_string(html_page)

    html = html.replace("window.initialJSON=null",
                        "window.initialJSON=" + initial_json_str)
    return HttpResponse(html, content_type="text/html")
Пример #19
0
def render_component(path_to_source, props=None, to_static_markup=False, json_encoder=None, timeout=TIMEOUT):
    if not os.path.isabs(path_to_source):
        # If its using the manifest staticfiles storage, to the hashed name.
        # eg. js/hello.js -> js/hello.d0bf07ff5f07.js
        if isinstance(staticfiles_storage, HashedFilesMixin):
            try:
                path_to_source = staticfiles_storage.stored_name(path_to_source)
            except ValueError:
                # Couldn't find it.
                pass

        # first, attempt to resolve at STATIC_ROOT if the file was collected
        abs_path = os.path.join(settings.STATIC_ROOT or '', path_to_source)
        if os.path.exists(abs_path):
            path_to_source = abs_path
        else:
            # Otherwise, resolve it using finders
            path_to_source = find_static(path_to_source) or path_to_source

    if json_encoder is None:
        json_encoder = DjangoJSONEncoder().encode

    try:
        html = render_core(
            path_to_source,
            props,
            to_static_markup,
            json_encoder,
            service_url=SERVICE_URL,
            timeout=timeout,
        )
    except Exception:
        if not FAIL_SAFE:
            raise
        log.exception('Error while rendering %s', path_to_source)
        html = ''

    return RenderedComponent(html, path_to_source, props, json_encoder)
Пример #20
0
 def encode(self, o, *args, **kwargs):
     if isinstance(o, QuerySet):
         return list(o)
     elif isinstance(o, User):
         return {
             'id': o.id,
             'username': o.username,
             'first_name': o.first_name,
             'last_name': o.last_name,
             'fullname': o.get_full_name(),
             'email': o.email,
             'url': o.get_absolute_url(),
         }
     elif isinstance(o, Group):
         return {
             'id': o.id,
             'name': o.name,
         }
     else:
         try:
             return DjangoJSONEncoder().default(o)
         except TypeError:
             return None
Пример #21
0
def ticket_repr(now):
    now_str = json.loads(DjangoJSONEncoder().encode(now))
    return {
        'id': 1,
        'state': 'todo',
        'number': 1,
        'created_at': now_str,
        'updated_at': now_str,
        'purchasables': [
            {
                'id': 2,
                'name': 'Purchasable 1',
                'qty': 99,
                'options': [
                    {
                        'id': 3,
                        'name': 'Purchasable Option 1',
                        'qty': 48
                    }
                ]
            }
        ]
    }
Пример #22
0
def serialize_personal_quiz(microlearning_average):
    json_encoder = DjangoJSONEncoder()
    project = microlearning_average.get_project()

    step_microlearnings = MicroLearning.objects.filter_by_step(
        microlearning_average.step)
    teams = project.teams.all()

    # Old version socket data
    serialized_data = microlearning_average.serialize()

    # Append data for new socket version
    serialized_data['personalRating'] = serialized_data.get('user')
    serialized_data['teamRatings'] = []

    for microlearning in step_microlearnings:
        for team in teams.filter(stream=microlearning.step_stream.stream):
            team_microlearning_avg = MicroLearningAverage(
                step_stream=microlearning.step_stream,
                user=None,
                team=team
            )
            data = team_microlearning_avg.serialize()
            serialized_data['teamRatings'].append(
                json.loads(
                    json_encoder.encode({
                        'pkTeam': team.pk,
                        'nameTeam': team.name,
                        'ratings': data.get('ratings'),
                        'avg': data.get('allTeamAvg'),
                    })
                )
            )
    serialized_data['teamRatings'] = sorted(
        serialized_data['teamRatings'], key=lambda x: x['pkTeam'])
    return serialized_data
Пример #23
0
def dumps(value):
    return DjangoJSONEncoder().encode(value)
Пример #24
0
def serialized_facility_factory(identifier):
    facility = Facility(name="Facility {}".format(identifier), id=identifier)
    return DjangoJSONEncoder().encode(facility.serialize())
Пример #25
0
 def get_rendered_output(self):
     return DjangoJSONEncoder().encode(self.data)
Пример #26
0
class ShopifyResourceModelBase(ChangedFields, models.Model):
    """
    Base class for local Model objects that are to be synchronised with Shopify.
    """

    shopify_resource_class = None
    parent_field = None
    related_fields = []
    child_fields = {}

    objects = ShopifyResourceManager()

    json_encoder = DjangoJSONEncoder()

    @property
    def klass(self):
        return self.__class__

    @property
    def manager(self):
        """
        Appears to return currently instantiated instances of the current Model?
        #todo figure out for sure..
        :return:
        :rtype:
        """
        return self.klass.objects

    @classmethod
    def get_defaults(cls, shopify_resource: ShopifyResource) -> dict:
        """
        Get a hash of attribute: values that can be used to update or create a local instance of the given Shopify
        resource.
        :type shopify_resource: ShopifyResource
        """
        defaults = {}

        # Set simple attributes that we simply need to copy across.
        for field in cls.get_default_fields():
            if hasattr(shopify_resource, field):
                defaults[field] = getattr(shopify_resource, field)

        # Set ID values for foreign key references.
        for related_field in cls.get_related_field_names():
            if hasattr(shopify_resource, related_field):
                defaults[related_field + "_id"] = getattr(
                    getattr(shopify_resource, related_field), "id")
            # sometimes related fields have an _id suffix, as in the case of `customer_id`
            related_field = related_field + "_id"
            if hasattr(shopify_resource, related_field):
                # in this case, we have an id, so no need to get the `id` attribute as above
                defaults[related_field] = getattr(shopify_resource,
                                                  related_field)

        return defaults

    @classmethod
    def get_default_fields(cls) -> list[str]:
        """
        Get a list of field names that should be copied directly from a Shopify resource model when building the
        defaults hash.
        """
        default_fields_excluded = cls.get_default_fields_excluded()
        fields = cls.get_parent_field_names()
        fields += [
            field.name for field in cls._meta.concrete_fields
            if field.name not in default_fields_excluded
        ]
        return fields

    @classmethod
    def get_default_fields_excluded(cls):
        """
        Get a list of field names to be excluded when copying directly from a Shopify resource model and building
        a defaults hash.
        """
        return (cls.get_related_field_names() +
                list(cls.get_child_fields().keys()) +
                ["session", "model"]  # python 3
                )

    @classmethod
    def get_parent_field_names(cls) -> list[str, None]:
        """
        Get a list of the names of parent fields for the current model.
        """
        if cls.parent_field is None:
            return []
        return [cls.parent_field]

    @classmethod
    def get_related_field_names(cls) -> list[Union[str, None]]:
        """
        Get a list of the names of related fields for the current model.
        """
        return cls.related_fields

    @classmethod
    def get_child_fields(cls) -> dict:
        """
        Get a list of child fields for the current model, in a "hash" format with the name of the field as the key
        and the related child model as the value.
        """
        return cls.child_fields

    @classmethod
    def get_r_fields(cls) -> dict:
        """
        Gets the r_fields values for a given model
        :return: r_fields
        :rtype: dict
        """
        return cls.r_fields

    @classmethod
    def shopify_resource_from_json(cls, json: JSONType) -> ShopifyResource:
        """
        Return an instance of the Shopify Resource model for this model,
        built recursively using the given JSON object.
        """
        instance = cls.shopify_resource_class()
        log.debug("Creating shopify reasource '%s'" % str(instance))
        log.debug("Using the following json: %s" % json)

        # Recursively instantiate any child attributes.
        for child_field, child_model in cls.get_child_fields().items():
            if child_field in json:
                json[child_field] = [
                    child_model.shopify_resource_from_json(child_field_json)
                    for child_field_json in json[child_field]
                ]

        # Recursively instantiate any related attributes.
        if hasattr(cls, "r_fields"):
            for r_field, r_model in cls.get_r_fields().items():
                if r_field in json:
                    json[r_field] = r_model.shopify_resource_from_json(
                        json[r_field])
        instance.attributes = json
        return instance

    @staticmethod
    def clean_for_post(shopify_resource: ShopifyResource) -> ShopifyResource:
        """
        When we use POST, we cannot have a 'id' present or else we get this error:

            [Shopify API Errors]: Source name cannot be set to a protected
            value by an untrusted API client.

        Our solution is to return the object with the id removed. We use a static method
        as we want to pass the object and it could be a ShopifyResource or model

        This is a staticmethod of the ShopifyResourceModelBase class that returns a shopify resource
        (shopify_python_api object) that matched the ShopifyResourceModelBase objects attrs with some modifications

        """
        clean_these_lists = ["shipping_lines", "line_items"]
        clean_these_keys = [
            "id", "tax_lines", "order_number", "number", "source_name"
        ]

        shopify_resource.id = None

        for key in clean_these_keys:
            shopify_resource.attributes.pop(key, None)

        for key in clean_these_lists:
            lines = shopify_resource.attributes.pop(key, None)
            if lines:
                for line in lines:
                    if isinstance(line, ShopifyResource):
                        line.attributes.pop("id", None)
                        line.attributes.pop("order_id", None)
                    else:
                        line.pop("id", None)
                shopify_resource.attributes[key] = lines

        if "billing_address" in shopify_resource.attributes:
            # the billing zip can be blank, but when we push we need to have it
            # for some stupid reason. Like there database doesn't require a
            # zip, why should we have to provide it then. This is the shit that
            # makes me get all made at shopify and such...
            if not shopify_resource.attributes["billing_address"]:
                # appreently the billing address can be blank
                shopify_resource.attributes["billing_address"] = {
                    "last_name": "Empty",
                    "first_name": "Billing addr",
                    "zip": None,
                    "city": None,
                    "address1": None,
                    "country": None,
                }
            if not shopify_resource.attributes["billing_address"]["zip"]:
                # yeah this will also happen:
                # 'billing_address Zip is not valid for Canada'
                shopify_resource.attributes["billing_address"][
                    "zip"] = "K0L 2W0"
            if not shopify_resource.attributes["billing_address"]["city"]:
                # apparently PO boxes in Singapore don't need a city
                shopify_resource.attributes["billing_address"][
                    "city"] = "Shopify Sux Eggs"
            if not shopify_resource.attributes["billing_address"]["address1"]:
                # Apprently you only really need the zip.
                shopify_resource.attributes["billing_address"]["address1"] = (
                    "a';DROP TABLE customers; SELECT"
                    "* FROM customers WHERE 't' = 't'")
            if not shopify_resource.attributes["billing_address"]["country"]:
                # Sadly this has to be a county shopify knows
                shopify_resource.attributes["billing_address"][
                    "country"] = "Azerbaijan"

        return shopify_resource

    def to_shopify_resource(self) -> ShopifyResource:
        """
        Convert this ShopifyResource model instance to its equivalent ShopifyResource.
        """
        instance = self.shopify_resource_class()
        # pyactiveresource changes __setattr__ to add attr to the attributes
        # dictionary and that is super annoying in so many ways so this is the
        # hack to undo that shit.
        instance.__dict__["session"] = self.session
        instance.__dict__["model"] = self

        # Copy across attributes.
        for default_field in self.get_default_fields():
            if hasattr(self, default_field):
                attribute = getattr(self, default_field)
                # If the attribute is itself a ShopifyResourceModel, ignore it.
                # The relevant resource will be linked through a '_id' parameter.
                if not isinstance(attribute, ShopifyResourceModel):
                    try:
                        attribute_encoded = self.json_encoder.default(
                            attribute)
                    except TypeError:
                        attribute_encoded = attribute
                    finally:
                        setattr(instance, default_field, attribute_encoded)

        # Recursively instantiate any child attributes.
        for child_field, child_model in self.get_child_fields().items():
            if hasattr(self, child_field):
                setattr(
                    instance,
                    child_field,
                    [
                        child.to_shopify_resource()
                        for child in getattr(self, child_field)
                    ],
                )

        # Get parent models for this model, like customer for an address, and add them to prefix options
        # so we can get a POST url like /customers/1319263371346/addresses/2195309133906.json
        if hasattr(self, "_prefix_options"):
            instance._prefix_options = self._prefix_options

        return instance

    def to_json(self) -> dict:
        """
        Convert this ShopifyResource model instance to a "JSON" (simple Python) object.
        """
        return self.to_shopify_resource().attributes

    def sync(self, sync_meta: bool = False) -> None:
        shopify_resource = self.to_shopify_resource()
        shopify_resource.reload()
        self.manager.sync_one(shopify_resource, sync_meta=sync_meta)
        self.refresh_from_db()

    def save(self, push: bool = False, *args, **kwargs) -> None:
        """

        :param push: True = update shopify to match local changes, default = False
        :type push: bool
        :param args:
        :type args:
        :param kwargs:
        :type kwargs:
        :return:
        :rtype:
        """
        if push:
            session = kwargs.pop("session", None)
            session = session if session else self.session
            log.debug("Pushing '%s' (%s) to %s" %
                      (self, self.id, session.site))
            self = self.manager.push_one(
                self, session=session, *args, **kwargs
            )  # todo typecheck says this should be ShopifyResourceModel
            # have to save so that we can get the id if it is new
            kwargs.pop("sync_children", None)  # remove option field
            super(ShopifyResourceModelBase, self).save(*args, **kwargs)
        super(ShopifyResourceModelBase, self).save(*args, **kwargs)

    class Meta:
        abstract = True
Пример #27
0
 def __init__(self, verbose_name=None, name=None,
              encoder=DjangoJSONEncoder(), **kwargs):
     blank = kwargs.pop('blank', True)
     models.TextField.__init__(self, verbose_name, name, blank=blank,
                               **kwargs)
     self.encoder = encoder
Пример #28
0
 def __init__(self, encoder=None, *args, **kwargs):
     super(JSONFormField, self).__init__(*args, **kwargs)
     self.encoder = encoder or DjangoJSONEncoder()
Пример #29
0
CHUNKED_UPLOAD_ABSTRACT_MODEL = False
CHUNKED_UPLOAD_MIMETYPE = 'text'

# How long after creation the upload will expire
DEFAULT_EXPIRATION_DELTA = timedelta(days=7)
EXPIRATION_DELTA = getattr(settings, 'CHUNKED_UPLOAD_EXPIRATION_DELTA',
                           DEFAULT_EXPIRATION_DELTA)
CHUNKED_UPLOAD_EXPIRATION_DELTA = timedelta(days=7)
# Path where uploading files will be stored until completion
DEFAULT_UPLOAD_PATH = os.path.join(settings.MEDIA_ROOT, 'chunked_uploads')
UPLOAD_PATH = getattr(settings, 'CHUNKED_UPLOAD_PATH', DEFAULT_UPLOAD_PATH)

# Storage system
STORAGE = getattr(settings, 'CHUNKED_UPLOAD_STORAGE_CLASS', lambda: None)()

# Boolean that defines if the ChunkedUpload model is abstract or not
ABSTRACT_MODEL = getattr(settings, 'CHUNKED_UPLOAD_ABSTRACT_MODEL', True)

# Function used to encode response data. Receives a dict and return a string
DEFAULT_ENCODER = DjangoJSONEncoder().encode
ENCODER = getattr(settings, 'CHUNKED_UPLOAD_ENCODER', DEFAULT_ENCODER)

# Mimetype for the response data
DEFAULT_MIMETYPE = 'application/json'
MIMETYPE = getattr(settings, 'CHUNKED_UPLOAD_MIMETYPE', DEFAULT_MIMETYPE)

# Max amount of data (in bytes) that can be uploaded. `None` means no limit
DEFAULT_MAX_BYTES = None
MAX_BYTES = getattr(settings, 'CHUNKED_UPLOAD_MAX_BYTES', DEFAULT_MAX_BYTES)
Пример #30
0
 def test_custom_encoder(self):
     with self.assertRaisesMessage(ValueError, "The encoder parameter must be a callable object."):
         field = JSONField(encoder=DjangoJSONEncoder())
     field = JSONField(encoder=DjangoJSONEncoder)
     self.assertEqual(field.clean(datetime.timedelta(days=1), None), datetime.timedelta(days=1))