当前位置: 首页>>代码示例>>Python>>正文


Python http.build_response函数代码示例

本文整理汇总了Python中wstore.store_commons.utils.http.build_response函数的典型用法代码示例。如果您正苦于以下问题:Python build_response函数的具体用法?Python build_response怎么用?Python build_response使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了build_response函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: delete

    def delete(self, request, repository):

        result = _manage_repository(request.user, repository, unregister_repository)
        if result[0]:
            return build_response(request, result[1], result[2])
        else:
            return build_response(request, 204, 'No content')
开发者ID:Fiware,项目名称:apps.Wstore,代码行数:7,代码来源:views.py

示例2: read

    def read(self, request):

        pagination = {
            'start': request.GET.get('start', None),
            'limit': request.GET.get('limit', None)
        }
        if pagination['start'] == None or pagination['limit'] == None:
            pagination = None

        profile = request.user.userprofile
        filter_ = request.GET.get('open', None)

        if filter_ and filter_ != 'true' and filter_ != 'false':
            return build_response(request, 400, 'Invalid open param')

        open_res = None
        if filter_ is not None:
            open_res = False

            if filter_ == 'true':
                open_res = True

        if 'provider' in profile.get_current_roles():
            try:
                response = get_provider_resources(request.user, filter_=open_res, pagination=pagination)
            except Exception, e:
                return build_response(request, 400, e.message)
开发者ID:Fiware,项目名称:apps.Wstore,代码行数:27,代码来源:views.py

示例3: update

    def update(self, request, currency):
        """
        This method is used to change the default currency
       """
        if not request.user.is_staff:
            build_response(request, 403, 'Forbidden')

        # Get the context
        context = Context.objects.all()[0]

        # Check that the currency exist
        if not 'default' in context.allowed_currencies:
            return build_response(request, 404, 'Not found')

        if not currency.lower() == context.allowed_currencies['default'].lower():
            for c in context.allowed_currencies['allowed']:
                if c['currency'].lower() == currency.lower():
                    break
            else:
                return build_response(request, 404, 'Not found')

        # Make the currency the default currency
        context.allowed_currencies['default'] = currency
        context.save()

        # Return response
        return build_response(request, 200, 'OK')
开发者ID:tmforum,项目名称:tmffiware,代码行数:27,代码来源:views.py

示例4: _validate_catalog_element

def _validate_catalog_element(request, element, validator):
    # Validate user permissions
    user = request.user
    if "provider" not in user.userprofile.get_current_roles() and not user.is_staff:
        return build_response(request, 403, "You don't have the seller role")

    # Parse content
    try:
        data = json.loads(request.body)
    except:
        return build_response(request, 400, "The content is not a valid JSON document")

    if "action" not in data:
        return build_response(request, 400, "Missing required field: action")

    if element not in data:
        return build_response(request, 400, "Missing required field: product")

    try:
        validator.validate(data["action"], user.userprofile.current_organization, data[element])
    except ValueError as e:
        return build_response(request, 400, unicode(e))
    except ProductError as e:
        return build_response(request, 400, unicode(e))
    except PluginError as e:
        return build_response(request, 422, unicode(e))
    except PermissionDenied as e:
        return build_response(request, 403, unicode(e))
    except:
        return build_response(request, 500, "An unexpected error has occurred")

    return build_response(request, 200, "OK")
开发者ID:FIWARE-TMForum,项目名称:business-ecosystem-charging-backend,代码行数:32,代码来源:views.py

示例5: create

    def create(self, request):
        if not request.user.is_staff:  # Only an admin could register the store in a marketplace
            return build_response(request, 403, 'Forbidden')

        name = None
        host = None

        # Get contents from the request
        try:
            content = json.loads(request.raw_post_data)
            name = content['name']
            host = content['host']
        except:
            msg = "Request body is not valid JSON data"
            return build_response(request, 400, msg)

        # Check data formats
        if not is_valid_id(name):
            return build_response(request, 400, 'Invalid name format')

        if not is_valid_url(host):
            return build_response(request, 400, 'Invalid URL format')
        
        code = 201
        msg = 'Created'
        try:
            # Register the store in the selected marketplace
            register_on_market(name, host, get_current_site(request).domain)
        except Exception, e:
            if e.message == 'Bad Gateway':
                code = 502
                msg = e.message
            else:
                code = 400
                msg = 'Bad request'
开发者ID:huygun,项目名称:wstore,代码行数:35,代码来源:views.py

示例6: update

    def update(self, request, organization, name, version):

        user = request.user
        # Get the offering
        try:
            offering, org = _get_offering(organization, name, version)
        except ObjectDoesNotExist as e:
            return build_response(request, 404, unicode(e))
        except Exception as e:
            return build_response(request, 400, unicode(e))

        # Update the offering
        try:
            # Check if the user is the owner of the offering or if is a manager of the
            # owner organization
            if user.userprofile.current_organization != org \
                    or (not offering.is_owner(user) and user.pk not in org.managers):

                return build_response(request, 403, 'You are not allowed to edit the current offering')

            data = json.loads(request.raw_post_data)

            update_offering(user, offering, data)
        except Exception, e:
            return build_response(request, 400, e.message)
开发者ID:Fiware,项目名称:apps.Wstore,代码行数:25,代码来源:views.py

示例7: read

    def read(self, request, organization, name, version):
        # Get offering
        try:
            org = Organization.objects.get(name=organization)
            offering = Offering.objects.get(owner_organization=org, name=name, version=version)
        except:
            return build_response(request, 404, 'Not found')

        # Check if is a tagging recommendation or a tags request
        action = request.GET.get('action', None)

        if action:
            if action == 'recommend':
                # Get user tags
                tags = request.GET.get('tags', '')

                # Split tags
                tags = set(tags.split(','))

                # Get recommended tags
                rec_man = RecommendationManager(offering, tags)
                response = { 
                    'tags': [tag for tag, r in rec_man.get_recommended_tags()]
                }
            else:
                return build_response(request, 400, 'Invalid action')

        else:
            response = {
                'tags': offering.tags
            }
        
        # Build response
        return HttpResponse(json.dumps(response), status=200, mimetype='application/json')
开发者ID:huygun,项目名称:wstore,代码行数:34,代码来源:views.py

示例8: create

    def create(self, request):

        user = request.user
        profile = user.userprofile
        content_type = get_content_type(request)[0]

        if 'provider' in profile.get_current_roles():

            try:
                if content_type == 'application/json':
                    data = json.loads(request.raw_post_data)
                    register_resource(user, data)
                else:
                    data = json.loads(request.POST['json'])
                    f = request.FILES['file']
                    register_resource(user, data, file_=f)

            except ConflictError as e:
                return build_response(request, 409, unicode(e))
            except Exception as e:
                return build_response(request, 400, unicode(e))
        else:
            return build_response(request, 403, "You don't have the provider role")

        return build_response(request, 201, 'Created')
开发者ID:Fiware,项目名称:apps.Wstore,代码行数:25,代码来源:views.py

示例9: update

    def update(self, request, organization, name, version):
        logger.debug("OfferingEntry.update()")
        user = request.user
        # Get the offering
        try:
            offering, org = _get_offering(organization, name, version)
        except ObjectDoesNotExist as e:
            return build_response(request, 404, unicode(e))
        except Exception as e:
            return build_response(request, 400, unicode(e))

        # Update the offering
        try:
            # Check if the user is the owner of the offering or if is a manager of the
            # owner organization
            if user.userprofile.current_organization != org\
            or (not offering.is_owner(user) and not user.pk in org.managers):
                return build_response(request, 403, 'You are not allowed to edit the current offering')

            data = json.loads(request.raw_post_data)
            update_offering(offering, data)
        except Exception, e:
            import traceback
            import StringIO
            buff = StringIO.StringIO()
            traceback.print_exc(file=buff)
            print("EXCEPTION: %s %s" % (str(e), buff.getvalue()))
            return build_response(request, 400, e.message)
开发者ID:gberryproject,项目名称:wstore,代码行数:28,代码来源:views.py

示例10: create

    def create(self, request):
        # In case the user cancels the payment is necessary to update
        # the database in order to avoid an inconsistent state
        try:
            data = json.loads(request.body)
            order = Order.objects.get(order_id=data['orderId'])

            # Get the payment client
            # Load payment client
            cln_str = settings.PAYMENT_CLIENT
            client_package, client_class = cln_str.rsplit('.', 1)

            payment_client = getattr(importlib.import_module(client_package), client_class)

            # build the payment client
            client = payment_client(order)

            for sale in order.sales_ids:
                client.refund(sale)

            # Only those orders with all its order items in ack state can be refunded
            # that means that all the contracts have been refunded
            for contract in order.contracts:
                cdr_manager = CDRManager(order, contract)
                charge = contract.charges[-1]

                cdr_manager.refund_cdrs(charge['cost'], charge['duty_free'], charge['date'].isoformat() + 'Z')

            # Create a refund CDR for each contract
            order.delete()
        except:
            return build_response(request, 400, 'Sales cannot be refunded')

        return build_response(request, 200, 'Ok')
开发者ID:FIWARE-TMForum,项目名称:business-ecosystem-charging-backend,代码行数:34,代码来源:views.py

示例11: read

    def read(self, request):
        """
        Retrives the existing digital assets associated with a given seller
        :param request:
        :return: JSON List containing the existing assets
        """

        pagination = {
            'start': request.GET.get('start', None),
            'limit': request.GET.get('limit', None)
        }
        if pagination['start'] is None or pagination['limit'] is None:
            pagination = None

        profile = request.user.userprofile

        if 'provider' not in profile.get_current_roles():
            return build_response(request, 403, 'You are not authorized to retrieve digital asset information')

        try:
            asset_manager = AssetManager()
            response = asset_manager.get_provider_assets_info(request.user, pagination=pagination)
        except Exception as e:
            return build_response(request, 400, unicode(e))

        return HttpResponse(json.dumps(response), status=200, mimetype='application/json; charset=utf-8')
开发者ID:tmforum,项目名称:tmffiware,代码行数:26,代码来源:views.py

示例12: _call_resource_entry_method

def _call_resource_entry_method(request, resource_id_info, method, data=None):

    response = build_response(request, 204, 'No Content')

    if data:
        response = build_response(request, 200, 'OK')

    error = False

    try:
        resource = _get_resource(resource_id_info)
    except:
        error = True
        response = build_response(request, 404, 'Resource not found')

    # Check permissions
    if not error and (not 'provider' in request.user.userprofile.get_current_roles() or\
      not request.user.userprofile.current_organization == resource.provider):
        error = True
        response = build_response(request, 403, 'Forbidden')

    # Try to make the specified action
    if not error:
        try:
            args = (resource, )
            if data:
                args = args + data

            method(*args)
        except Exception as e:
            response = build_response(request, 400, unicode(e))

    # Return the response
    return response
开发者ID:perezdf,项目名称:wstore,代码行数:34,代码来源:views.py

示例13: create

    def create(self, request):
        try:
            # Extract SDR document from the HTTP request
            data = json.loads(request.body)
        except:
            # The usage document is not valid, so the state cannot be changed
            return build_response(request, 400, 'The request does not contain a valid JSON object')

        # Validate usage information
        response = None
        try:
            sdr_manager = SDRManager()
            sdr_manager.validate_sdr(data)
        except PermissionDenied as e:
            response = build_response(request, 403, unicode(e))
        except ValueError as e:
            response = build_response(request, 422, unicode(e))
        except:
            response = build_response(request, 500, 'The SDR document could not be processed due to an unexpected error')

        usage_client = UsageClient()
        if response is not None:
            # The usage document is not valid, change its state to Rejected
            usage_client.update_usage_state('Rejected', data)
        else:
            # The usage document is valid, change its state to Guided
            usage_client.update_usage_state('Guided', data)
            response = build_response(request, 200, 'OK')

        # Update usage document state
        return response
开发者ID:tmforum,项目名称:tmffiware,代码行数:31,代码来源:views.py

示例14: update

    def update(self, request, reference):

        purchase = Purchase.objects.get(ref=reference)

        data = json.loads(request.raw_post_data)

        try:
            if data['method'] == 'paypal':
                charging_engine = ChargingEngine(purchase, payment_method='paypal')
            elif data['method'] == 'credit_card':

                # Get the payment info
                if 'credit_card' in data:
                    credit_card = data['credit_card']
                else:
                    if purchase.organization_owned:
                        credit_card = purchase.owner_organization.payment_info
                    else:
                        credit_card = purchase.customer.userprofile.payment_info
                charging_engine = ChargingEngine(purchase, payment_method='credit_card', credit_card=credit_card)

            charging_engine.resolve_charging()
        except:
            # Refresh the purchase info
            purchase = Purchase.objects.get(ref=reference)
            rollback(purchase)
            return build_response(request, 400, 'Invalid JSON content')

        return build_response(request, 200, 'OK')
开发者ID:jartieda,项目名称:wstore,代码行数:29,代码来源:views.py

示例15: read

    def read(self, request, text):

        index_path = os.path.join(settings.BASEDIR, 'wstore')
        index_path = os.path.join(index_path, 'search')
        index_path = os.path.join(index_path, 'indexes')

        search_engine = SearchEngine(index_path)

        filter_ = request.GET.get('filter', None)
        action = request.GET.get('action', None)
        start = request.GET.get('start', None)
        limit = request.GET.get('limit', None)
        sort = request.GET.get('sort', None)

        # Check the filter value
        if filter_ and filter_ != 'published' and filter_ != 'provided' and filter_ != 'purchased':
            return build_response(request, 400, 'Invalid filter')

        count = False
        pagination = None
        # Check if the action is count
        if action != None:
            if action == 'count':
                count = True
            else:
                return build_response(request, 400, 'Invalid action')
        else:
            # Check pagination params (Only when action is none)
            if start != None and limit != None:
                pagination = {
                    'start': int(start),
                    'limit': int(limit)
                }
            elif (start != None and limit == None) or (start == None and limit != None):
                return build_response(request, 400, 'Missing pagination param')

            # Check sorting values
            if sort != None:
                if sort != 'date' and sort != 'popularity' and sort != 'name':
                    return build_response(request, 400, 'Invalid sorting')

        if not filter_:
            response = search_engine.full_text_search(request.user, text, count=count, pagination=pagination, sort=sort)

        elif filter_ == 'provided':

            state = request.GET.get('state', 'all')
            # Check the state value
            if state != 'all' and state != 'uploaded'\
            and state != 'published' and state != 'deleted':

                return build_response(request, 400, 'Invalid state')

            response = search_engine.full_text_search(request.user, text, state=state, count=count, pagination=pagination, sort=sort)

        elif filter_ == 'purchased':
            response = search_engine.full_text_search(request.user, text, state='purchased', count=count, pagination=pagination, sort=sort)

        return HttpResponse(json.dumps(response), status=200, mimetype='application/json')
开发者ID:jartieda,项目名称:wstore,代码行数:59,代码来源:views.py


注:本文中的wstore.store_commons.utils.http.build_response函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。