• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python mime.determine_format函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: test_determine_format

    def test_determine_format(self):
        serializer = Serializer()
        full_serializer = Serializer(formats=['json', 'jsonp', 'xml', 'yaml', 'html', 'plist'])
        request = HttpRequest()
        
        # Default.
        self.assertEqual(determine_format(request, serializer), 'application/json')
        
        # Test forcing the ``format`` parameter.
        request.GET = {'format': 'json'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        # Disabled by default.
        request.GET = {'format': 'jsonp'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        # Explicitly enabled.
        request.GET = {'format': 'jsonp'}
        self.assertEqual(determine_format(request, full_serializer), 'text/javascript')

        request.GET = {'format': 'xml'}
        self.assertEqual(determine_format(request, serializer), 'application/xml')
        
        request.GET = {'format': 'yaml'}
        self.assertEqual(determine_format(request, serializer), 'text/yaml')
        
        request.GET = {'format': 'plist'}
        self.assertEqual(determine_format(request, serializer), 'application/x-plist')
        
        request.GET = {'format': 'foo'}
        self.assertEqual(determine_format(request, serializer), 'application/json')
        
        # Test the ``Accept`` header.
        request.META = {'HTTP_ACCEPT': 'application/json'}
        self.assertEqual(determine_format(request, serializer), 'application/json')
开发者ID:sbnoemi,项目名称:django-tastypie,代码行数:35,代码来源:utils.py


示例2: top_level

    def top_level(self, request, api_name=None):
        serializer = Serializer()
        available_resources = {}

        if api_name is None:
            api_name = self.api_name

        for name in sorted(self._registry.keys()):
            available_resources[name] = {
                'list_endpoint': self._build_reverse_url('api_dispatch_list', kwargs={
                    'api_name': api_name,
                    'resource_name': name,
                }),
                'schema': self._build_reverse_url('api_get_schema', kwargs={
                    'api_name': api_name,
                    'resource_name': name,
                }),
            }

            if request.GET.get('include_schemas', False) is not False:
                available_resources[name]['schema_detailed'] = self._registry[name].build_schema()

        desired_format = determine_format(request, serializer)
        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')
            
            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = serializer.serialize(available_resources, desired_format, options)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:BradZzz,项目名称:TastyBone,代码行数:35,代码来源:api.py


示例3: top_level

    def top_level(self, request, api_name=None):
        """
        A view that returns a serialized list of all resources registers
        to the ``Api``. Useful for discovery.
        """
        available_resources = {}

        if api_name is None:
            api_name = self.api_name

        for name in sorted(self._registry.keys()):
            available_resources[name] = {
                "list_endpoint": self._build_reverse_url(
                    "api_dispatch_list", kwargs={"api_name": api_name, "resource_name": name}
                ),
                "schema": self._build_reverse_url(
                    "api_get_schema", kwargs={"api_name": api_name, "resource_name": name}
                ),
            }

        desired_format = determine_format(request, self.serializer)

        options = {}

        if "text/javascript" in desired_format:
            callback = request.GET.get("callback", "callback")

            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest("JSONP callback name is invalid.")

            options["callback"] = callback

        serialized = self.serializer.serialize(available_resources, desired_format, options)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:dirn,项目名称:django-tastypie,代码行数:34,代码来源:api.py


示例4: top_level

    def top_level(self, request, api_name=None):
        """
        A view that returns a serialized list of all resources registers
        to the ``Api``. Useful for discovery.
        """
        serializer = Serializer()

        if api_name is None:
            api_name = self.api_name

        available_resources = dict((name, {
            'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs={
                'api_name': api_name,
                'resource_name': name,
            }),
            'schema': self._build_reverse_url("api_get_schema", kwargs={
                'api_name': api_name,
                'resource_name': name,
            }),
        }) for name in self._registry.iterkeys())

        desired_format = determine_format(request, serializer)
        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')

            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = serializer.serialize(available_resources, desired_format, options)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:georgemarshall,项目名称:django-tastypie,代码行数:34,代码来源:api.py


示例5: top_level

 def top_level(self, request, api_name=None):
     """
     A view that returns a serialized list of all resources registers
     to the ``Api``. Useful for discovery.
     """
     serializer = Serializer()
     available_resources = {}
     
     if api_name is None:
         api_name = self.api_name
     
     for name in sorted(self._registry.keys()):
         available_resources[name] = {
             'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
             'schema': self._build_reverse_url("api_get_schema", kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
         }
     
     desired_format = determine_format(request, serializer)
     serialized = serializer.serialize(available_resources, desired_format)
     return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:bmihelac,项目名称:django-tastypie,代码行数:26,代码来源:api.py


示例6: top_level

def top_level(request):
    available_resources = {}

    apitop = reverse('ietf.api.top_level')

    for name in sorted([ name for name, api in _api_list if len(api._registry) > 0 ]):
        available_resources[name] = {
            'list_endpoint': '%s/%s/' % (apitop, name),
        }

    serializer = Serializer()
    desired_format = determine_format(request, serializer)

    options = {}

    if 'text/javascript' in desired_format:
        callback = request.GET.get('callback', 'callback')

        if not is_valid_jsonp_callback_value(callback):
            raise BadRequest('JSONP callback name is invalid.')

        options['callback'] = callback

    serialized = serializer.serialize(available_resources, desired_format, options)
    return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:wpjesus,项目名称:codematch,代码行数:25,代码来源:__init__.py


示例7: login

def login(request, **kwargs):
    # self.method_check(request, allowed=['post'])
    # self.is_authenticated(request)
    # self.throttle_check(request)

    developer_key = request.GET.get('developer_key')
    username = request.GET.get('username')
    password = request.GET.get('password')

    if not developer_key or not username or not password:
        return HttpUnauthorized()

    try:
        dev_key = DeveloperApiKey.objects.get(key=developer_key, approved=True)
    except DeveloperApiKey.DoesNotExist:
        return HttpUnauthorized()

    user = authenticate(username=username, password=password)

    if user:
        try:
            key = UserApiKey.objects.get(user=user, developer_key=dev_key)
        except  UserApiKey.DoesNotExist:
            key = UserApiKey(user=user, developer_key=dev_key)
            key.save()

        # self.log_throttled_access(request)
        serializer = Serializer()
        desired_format = determine_format(request, serializer)
        serialized = serializer.serialize({'key' : key.key}, desired_format)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
    else:
        return HttpUnauthorized()
开发者ID:MarcBehrens,项目名称:ScrumDo,代码行数:33,代码来源:views.py


示例8: top_level

 def top_level(self, request, api_name=None):
     """This is the same method in the Api model with the execption
     of the serializer used. This uses the SafeSerializer.
     """
     serializer = SafeSerializer()
     available_resources = {}
     
     if api_name is None:
         api_name = self.api_name
     
     for name in sorted(self._registry.keys()):
         available_resources[name] = {
             'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
             'schema': self._build_reverse_url("api_get_schema", kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
         }
     
     desired_format = determine_format(request, serializer)
     options = {}
     
     if 'text/javascript' in desired_format:
         callback = request.GET.get('callback', 'callback')
     
         if not is_valid_jsonp_callback_value(callback):
             raise BadRequest('JSONP callback name is invalid.')
     
         options['callback'] = callback
     
     serialized = serializer.serialize(available_resources, desired_format, options)
     return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:DeepInTheCode,项目名称:tendenci,代码行数:35,代码来源:api.py


示例9: serialized

 def serialized(self, request, api_name=None, desired_format=None):
     """
     Nabbed from top_level of the parent class
     Would be nice if this was abstracted as it's good for auto discovery
     to be rendered as json on initial page load
     """
     serializer = Serializer()
     available_resources = {}
     
     if api_name is None:
         api_name = self.api_name
         
     if desired_format is None:
         desired_format = determine_format(request, serializer)
     
     for name in sorted(self._registry.keys()):
         available_resources[name] = {
             'list_endpoint': self._build_reverse_url("api_dispatch_list", 
             kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
             'schema': self._build_reverse_url("api_get_schema", kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
         }
     
     return serializer.serialize(available_resources, desired_format)
开发者ID:bne,项目名称:hortee,代码行数:29,代码来源:utils.py


示例10: error_response

def error_response(request, error_code=None, message=None, status_code=403, serializer_class=HTMLSerializer, **kwargs):
    context = {}
    if error_code:
        context['error_code'] = error_code

        if not message:
            message = ERRORS[error_code].format(**kwargs)
    if message:
        context['error_message'] = message

    context.update(kwargs)

    serializer = serializer_class()

    desired_format = determine_format(request, serializer)
    options = {}

    if 'text/javascript' in desired_format:
        callback = request.GET.get('callback', 'callback')

        if not is_valid_jsonp_callback_value(callback):
            raise BadRequest('JSONP callback name is invalid.')

        options['callback'] = callback

    serialized = serializer.serialize(context, desired_format, options)
    return HttpResponse(content=serialized, content_type=build_content_type(desired_format), status=status_code)
开发者ID:gannetson,项目名称:poc,代码行数:27,代码来源:functions.py


示例11: determine_format

 def determine_format(self, request):
     """return application/json as the default format """
     fmt = determine_format(request, self._meta.serializer,\
                            default_format=self._meta.default_format)
     if fmt == 'text/html' and 'format' not in request:
         fmt = 'application/json'
     return fmt
开发者ID:anuragjain67,项目名称:govdata,代码行数:7,代码来源:api.py


示例12: determine_format

 def determine_format(self, request):
     """
     return application/json as the default format
     """
     fmt = determine_format(request, self._meta.serializer, default_format=self._meta.default_format)
     if fmt == "text/html" and "format" not in request:
         fmt = "application/json"
     return fmt
开发者ID:khozaif,项目名称:DO-IT-Seed,代码行数:8,代码来源:api.py


示例13: determine_format

 def determine_format(self, request):
     """
     Used to determine the desired format.
     
     Largely relies on ``tastypie.utils.mime.determine_format`` but here
     as a point of extension.
     """
     return determine_format(request, self._meta.serializer, default_format=self._meta.default_format)
开发者ID:whiteblack,项目名称:django-tastypie,代码行数:8,代码来源:resources.py


示例14: determine_format

    def determine_format(self, request):
        '''
            Overriding this to by pass text/html format when accessing ``API
            directly through browser.
        '''
        req_format = determine_format(request, self._meta.serializer,
                                      default_format=self._meta.default_format)
        if req_format == "text/html":
            req_format = self._meta.default_format

        return req_format
开发者ID:tanwanirahul,项目名称:rest-on-sets,代码行数:11,代码来源:resources.py


示例15: is_key_valid

def is_key_valid(request, **kwargs):
    user_key = request.GET.get('user_key')
    try:
        user_key = UserApiKey.objects.get(key=user_key)
        key_valid = True
    except UserApiKey.DoesNotExist:
        key_valid = False
        # self.log_throttled_access(request)
    serializer = Serializer()
    desired_format = determine_format(request, serializer)
    serialized = serializer.serialize({'valid' : key_valid}, desired_format)
    return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:MarcBehrens,项目名称:ScrumDo,代码行数:12,代码来源:views.py


示例16: view_response

def view_response(request, response, code):
    from django.http import HttpResponse
    from tastypie.serializers import Serializer
    from tastypie.utils.mime import determine_format

    serdes = Serializer(formats=["json", "xml"])
    mimetype = determine_format(request, serdes)
    response = serdes.serialize(response, mimetype)
    del serdes

    http_response = HttpResponse(response, mimetype=mimetype)
    http_response.status_code = code
    return http_response
开发者ID:asorici,项目名称:envsmth,代码行数:13,代码来源:views.py


示例17: top_level

    def top_level(self, request, api_name=None):
        serializer = PrettyJSONSerializer()
        available_resources = {}

        if api_name is None:
            api_name = self.api_name

        def render_resource(name, resource):
            dct = {
                'apidoc': self._build_reverse_url("api_get_doc", kwargs={
                    'api_name': api_name,
                    'resource_name': name,
                }),
                'relativePath': resource.get_relative_uri(),
                'schema': self._build_reverse_url("api_get_schema", kwargs={
                    'api_name': api_name,
                    'resource_name': name,
                }),
                'views': {}
            }

            for _, viewmeta in resource.viewregistry.get_all():
                view_name = viewmeta.name
                dct['views'][view_name] = viewmeta.get_template_uri(resource)

            if resource.children:
                dct['children'] = {}
                for child in resource.children:
                    n = child._meta.resource_name
                    dct['children'][n] = render_resource(n, child)

            return dct

        for name, resource in self._registry.items():
            if not resource.parent:
                available_resources[name] = render_resource(name, resource)

        desired_format = determine_format(request, serializer)
        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')

            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = serializer.serialize(available_resources, desired_format, options)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:oxilion,项目名称:zarafa-zsm,代码行数:50,代码来源:api.py


示例18: sign_up

def sign_up(request):
    """
        Create a new user including profile and send email with activation link.
    """
    form = SignUpForm(request.POST)
    serializer = Serializer()
    format = determine_format(request, serializer,
        default_format='application/json')

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

        # Create new user (profile is automatically created)
        user = User.objects.create(username=username, first_name=first_name,
            last_name=last_name, email=email, is_active=False)
        user.set_password(password)
        user.save()

        auth_profile = user.get_profile()

        # Build the activation key
        salt = sha.new(str(random())).hexdigest()[:5]
        activation_key = sha.new(salt + user.username).hexdigest()
        key_expires = datetime.datetime.now(pytz.utc) + datetime.timedelta(2)

        # User is unactive until visiting activation link
        auth_profile.activation_key = activation_key
        auth_profile.key_expires = key_expires
        activation_link = 'http://127.0.0.1:8000/auth/v1/activate/' + activation_key  # TODO: replace with actual actication link (http://api.score-it.de/auth/v1/activate/)

        auth_profile.save()

        # TODO: Design better email
        subject = _('Welcome to ScoreIt!')
        message = _('To activate, please click the following link:\n' + activation_link)
        sender = _('[email protected]')
        recipients = [email]
        send_mail(subject, message, sender, recipients)

        user_resource = UserResource()
        bundle = user_resource.build_bundle(obj=user, request=request)
        user_resource.full_dehydrate(bundle)

        return HttpResponse(user_resource.serialize(None, bundle, 'application/json'))
    else:
        return HttpResponseBadRequest(serializer.serialize(form.errors, format, {}))
开发者ID:Engaginglab,项目名称:scoreit,代码行数:50,代码来源:api.py


示例19: top_level

    def top_level(self, request, api_name=None):
        """
        Overriding top_level method to serialize only resources
        that user has rights to use.
        """
        serializer = Serializer()
        available_resources = {}

        if api_name is None:
            api_name = self.api_name

        for resource_name in sorted(self._registry.keys()):
            available_resources[resource_name] = {
                'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs={
                    'api_name': api_name,
                    'resource_name': resource_name,
                }),
                'schema': self._build_reverse_url("api_get_schema", kwargs={
                    'api_name': api_name,
                    'resource_name': resource_name,
                }),
            }

        if not available_resources:
            return HttpResponseForbidden()

        desired_format = determine_format(request, serializer)
        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')

            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = serializer.serialize(available_resources, desired_format, options)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:SanomaCZ,项目名称:ella-hub,代码行数:39,代码来源:api.py


示例20: top_level

    def top_level(self, request, api_name=None, **kwargs):
        """
        A view that returns a serialized list of all resources registers
        to the ``Api``. Useful for discovery.
        """
        # TODO: Limit visibility of API to valid site IDs only.
        # TODO: Potentially, we could only give pieces of the API out based on site ID.

        serializer = Serializer()
        available_resources = {}

        if api_name is None:
            api_name = self.api_name

        for name in sorted(self._registry.keys()):
            kw_bru = {
                'api_name': api_name,
                'resource_name': name,
                }
            kw_bru.update(self._registry[name].api_additional_parameters())
            kw_bru.update(kwargs)
            available_resources[name] = {
                'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs=kw_bru),
                'schema': self._build_reverse_url("api_get_schema", kwargs=kw_bru),
                }

        desired_format = determine_format(request, serializer)
        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')

            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = serializer.serialize(available_resources, desired_format, options)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:xealot,项目名称:hp3,代码行数:39,代码来源:tastypie_extras.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python urls.trailing_slash函数代码示例发布时间:2022-05-27
下一篇:
Python mime.build_content_type函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap