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


Python Serializer.deserialize方法代码示例

本文整理汇总了Python中tastypie.serializers.Serializer.deserialize方法的典型用法代码示例。如果您正苦于以下问题:Python Serializer.deserialize方法的具体用法?Python Serializer.deserialize怎么用?Python Serializer.deserialize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tastypie.serializers.Serializer的用法示例。


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

示例1: obj_update

# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import deserialize [as 别名]
 def obj_update(self, bundle, skip_errors=False, **kwargs):
     """
     Could be an intentional action that the default obj_update treats DoesNotExist and MultipleObjectReturned
     as acceptable exceptions which get transformed into a CREATE operation.
     We don't want such a behavior. So we catch does exceptions and throw an BadRequest message
     """ 
     from tastypie.serializers import Serializer
        
     try:
         serdes = Serializer()
         deserialized = None
         try:
             deserialized = serdes.deserialize(bundle.request.raw_post_data, 
                                 format=bundle.request.META.get('CONTENT_TYPE', 'application/json'))
         except Exception:
             deserialized = None
         del serdes
                 
         if deserialized is None:
             return ImmediateHttpResponse(response = http.HttpBadRequest())
         
         if 'unregister_c2dm' in deserialized and deserialized['unregister_c2dm'] == True:
             bundle.data['c2dm_id'] = None
         
         updated_bundle = super(UserResource, self).obj_update(bundle, skip_errors=skip_errors, **kwargs)
         return updated_bundle
     except (NotFound, MultipleObjectsReturned):
         raise ImmediateHttpResponse(response = http.HttpBadRequest())
开发者ID:asorici,项目名称:envived,代码行数:30,代码来源:api.py

示例2: send_invitation

# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import deserialize [as 别名]
def send_invitation(request):
    """
        Send an invitation to another person via email. NOT TESTED YET
    """
    if request.user.is_authenticated() and request.user.is_active:
        if 'email' in request.POST:
            email = request.POST['email']
        else:
            return HttpResponseBadRequest('Mandatory email parameter not provided.')

        if 'message' in request.POST:
            message = request.POST['message']
        else:
            message = 'Tritt score.it bei und sehe deine Handballergebnisse online!'

        profile = None
        if 'profile' in request.POST:
            serializer = Serializer()
            profile = serializer.deserialize(request.POST['profile'])

        subject = '{0} {1} lädt dich zu Score.it ein!'.format(request.user.first_name, request.user.last_name)

        if profile:
            profile_link = 'http://score-it.de/?a=invite&p={0}'.format(profile.id)
            body = '{0} {1} hat ein Spielerprofil bei Score.it für dich erstellt. Melde dich jetzt bei Score.it an, um deine Handballergebnisse online abzurufen! Zum anmelden, klicke einfach folgenden Link: {3}'.format(request.user.first_name, request.user.last_name, profile_link)
        else:
            body = '{0} {1} hat dir eine Einladung zu der Sportplatform Score.it geschickt:<br>{2}Um dich anzumelden, besuche einfach http://score-it.de/!'.format(request.user.first_name, request.user.last_name, message)

        sender = '[email protected]'
        recipients = [email]
        send_mail(subject, body, sender, recipients)
        return HttpResponse('')
    else:
        return HttpUnauthorized('Authentication through active user required.')
开发者ID:Engaginglab,项目名称:scoreit-handball,代码行数:36,代码来源:api.py

示例3: obj_update

# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import deserialize [as 别名]
 def obj_update(self, bundle, skip_errors=False, **kwargs):
     from tastypie.serializers import Serializer
     from models import ProgramFeature
     
     serdes = Serializer()
     deserialized = None
     
     try:
         deserialized = serdes.deserialize(bundle.request.body, format=bundle.request.META.get('CONTENT_TYPE', 'application/json'))
     except Exception:
         deserialized = None
     
     if deserialized is None:
         return ImmediateHttpResponse(response = http.HttpBadRequest('Empty update data'))
     
     time_difference = datetime.strptime(deserialized['new_end_time'], "%Y-%m-%d %H:%M:%S") - datetime.strptime(deserialized['old_end_time'], "%Y-%m-%d %H:%M:%S")
     
     Presentation.objects.filter(startTime__gte=deserialized['old_end_time']).update(startTime=F('startTime') + time_difference)
     Presentation.objects.filter(startTime__gte=deserialized['old_end_time']).update(endTime=F('endTime') + time_difference)
     
     later_presentations = Presentation.objects.filter(startTime__gte=deserialized['old_end_time'])
     
     changed_presentation = Presentation.objects.get(startTime=deserialized['old_start_time'])
     changed_presentation.startTime = deserialized['new_start_time']
     changed_presentation.endTime = deserialized['new_end_time']
     changed_presentation.save()
开发者ID:asorici,项目名称:envived,代码行数:28,代码来源:api.py

示例4: ProjectResourceTest

# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import deserialize [as 别名]
class ProjectResourceTest(TestCase):
    fixtures = ['data.json']
    def setUp(self):
        super(ProjectResourceTest, self).setUp()
        self.username = 'marcos'
        self.password = 'test'
        #self.user = User.objects.create_user(self.username, '[email protected]', self.password)
        #self.api = slumber.API("http://localhost:5000/api/v1/", auth=(self.username, self.password))
        self.post_data = {
            'title': 'testTitle',
            'description': 'testDescription',
            'user' : '/api/v1/user/4ea9c4fdbb69337f8e000002/',
            'tasks': []
        }
        self.serializer = Serializer()

    def test_post_project(self):
        format = self.serializer.content_types.get('json')
        serialized_data = self.serializer.serialize(self.post_data, format='application/json')
        self.assertEqual(Project.objects.count(), 1)
        resp = self.client.post('/api/v1/project/', data = serialized_data, content_type='application/json')
        self.assertEqual(resp.status_code, 201)
        self.assertEqual(Project.objects.count(), 2)


    def test_put_project(self):
        format = self.serializer.content_types.get('json')
        project_data = self.post_data
        project_data['title'] = 'changedTitle'
        serialized_data = self.serializer.serialize(project_data, format='application/json')
        resp = self.client.put('/api/v1/project/4ea9c4fdbb69337f8e000001/', data = serialized_data, content_type='application/json')
        self.assertEqual(resp.status_code, 204)
        resp = self.client.get('/api/v1/project/')
        self.assertEqual("changedTitle", self.serializer.deserialize(resp.content)['objects'][0]['title'])

    def test_get_projects(self):
        resp = self.client.get('/api/v1/project/')
        self.assertEqual(resp.status_code, 200)
        self.assertTrue(resp['Content-Type'].startswith('application/json'))
        self.serializer.from_json(resp.content)
        self.assertEqual(len(self.serializer.deserialize(resp.content)['objects']), 1)
        assert True

    """def test_get_tasks(self):
开发者ID:Markinhos,项目名称:Drawer,代码行数:46,代码来源:tests.py

示例5: update_detail

# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import deserialize [as 别名]
 def update_detail(self, object_list, bundle):
     from features.conference_role.models import ChairRoleCredential
     
     if hasattr(bundle.request, 'user') and not bundle.request.user.is_anonymous():
         ''' User must be checked in at environment for which this feature is defined '''
         confrole_obj = bundle.obj
         if confrole_obj is None:
             raise Unauthorized("Non-existent conference role resource access.")
         
         env_obj = confrole_obj.environment
         area_obj = confrole_obj.area
         
         user_profile = bundle.request.user.get_profile()  # # will be an instance of UserProfile => available context
         if not is_checked_in(user_profile, env_obj, area_obj):
             raise Unauthorized("Users not checked-in cannot delete their conference role.")
         
         ''' Deserialize data payload and check if trying to set role to `session_chair` value. 
             In that case, a chair_password is required '''
         serdes = Serializer()
         deserialized = None
         
         try:
             deserialized = serdes.deserialize(bundle.request.body, format=bundle.request.META.get('CONTENT_TYPE', 'application/json'))
         except Exception:
             raise Unauthorized("Update data unreadable.")
             
         if deserialized is None:
             raise Unauthorized("Empty update data not allowed.")
         
         if "role" in deserialized and deserialized['role'] == "session_chair":
             print "Attempting to become session_chair",
             
             chair_password = deserialized.get("chair_password", None)
             if not chair_password:
                 raise Unauthorized("Cannot alter conference role to `session_chair` without credentials.")
             
             ''' check with the chair password recorded for this user '''
             try:
                 chair = ChairRoleCredential.objects.get(user_profile=user_profile)
                 if not chair.check_password(chair_password):
                     raise Unauthorized("Incorrect credentials for attempt to set `session_chair` conference role.")
             except Exception, ex:
                 print ex
                 raise Unauthorized("User is not listed as a `session_chair`.")
         
         return True
开发者ID:asorici,项目名称:envived,代码行数:48,代码来源:authorization.py

示例6: ResourceTestCase

# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import deserialize [as 别名]

#.........这里部分代码省略.........
        can be loaded properly.
        """
        # Just try the load. If it throws an exception, the test case will fail.
        self.serializer.from_xml(data)

    def assertValidYAML(self, data):
        """
        Given the provided ``data`` as a string, ensures that it is valid YAML &
        can be loaded properly.
        """
        # Just try the load. If it throws an exception, the test case will fail.
        self.serializer.from_yaml(data)

    def assertValidPlist(self, data):
        """
        Given the provided ``data`` as a string, ensures that it is valid
        binary plist & can be loaded properly.
        """
        # Just try the load. If it throws an exception, the test case will fail.
        self.serializer.from_plist(data)

    def assertValidJSONResponse(self, resp):
        """
        Given a ``HttpResponse`` coming back from using the ``client``, assert that
        you get back:

        * An HTTP 200
        * The correct content-type (``application/json``)
        * The content is valid JSON
        """
        self.assertHttpOK(resp)
        self.assertTrue(resp['Content-Type'].startswith('application/json'))
        self.assertValidJSON(resp.content)

    def assertValidXMLResponse(self, resp):
        """
        Given a ``HttpResponse`` coming back from using the ``client``, assert that
        you get back:

        * An HTTP 200
        * The correct content-type (``application/xml``)
        * The content is valid XML
        """
        self.assertHttpOK(resp)
        self.assertTrue(resp['Content-Type'].startswith('application/xml'))
        self.assertValidXML(resp.content)

    def assertValidYAMLResponse(self, resp):
        """
        Given a ``HttpResponse`` coming back from using the ``client``, assert that
        you get back:

        * An HTTP 200
        * The correct content-type (``text/yaml``)
        * The content is valid YAML
        """
        self.assertHttpOK(resp)
        self.assertTrue(resp['Content-Type'].startswith('text/yaml'))
        self.assertValidYAML(resp.content)

    def assertValidPlistResponse(self, resp):
        """
        Given a ``HttpResponse`` coming back from using the ``client``, assert that
        you get back:

        * An HTTP 200
        * The correct content-type (``application/x-plist``)
        * The content is valid binary plist data
        """
        self.assertHttpOK(resp)
        self.assertTrue(resp['Content-Type'].startswith('application/x-plist'))
        self.assertValidPlist(resp.content)

    def deserialize(self, resp):
        """
        Given a ``HttpResponse`` coming back from using the ``client``, this method
        checks the ``Content-Type`` header & attempts to deserialize the data based on
        that.

        It returns a Python datastructure (typically a ``dict``) of the serialized data.
        """
        return self.serializer.deserialize(resp.content, format=resp['Content-Type'])

    def serialize(self, data, format='application/json'):
        """
        Given a Python datastructure (typically a ``dict``) & a desired content-type,
        this method will return a serialized string of that data.
        """
        return self.serializer.serialize(data, format=format)

    def assertKeys(self, data, expected):
        """
        This method ensures that the keys of the ``data`` match up to the keys of
        ``expected``.

        It covers the (extremely) common case where you want to make sure the keys of
        a response match up to what is expected. This is typically less fragile than
        testing the full structure, which can be prone to data changes.
        """
        self.assertEqual(sorted(data.keys()), sorted(expected))
开发者ID:grunskis,项目名称:django-tastypie,代码行数:104,代码来源:test.py

示例7: process_response

# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import deserialize [as 别名]
    def process_response(self, request, response):
        if hasattr(request, 'user') and request.user.is_authenticated():
            credentials = request.user.pk
        else:
            credentials = -1
        serializer = Serializer()
        format = determine_format(
            request, serializer, default_format='application/json')
        # clean POST received from client
        if request.method in ['POST', 'PUT']:
            try:
                cleansed = serializer.deserialize(
                    request.body,
                    format=format)
            except ValueError:
                cleansed = request.POST.dict()
            except UnsupportedFormat:
                cleansed = 'UNSUPPORTED_FORMAT'
            except AttributeError:
                cleansed = 'UNSUPPORTED_STRING'
            except Exception as e:
                logger.warning(
                    u"[RESPONSE] %(c)s: %(e)s",
                    {'c': e.__class__, 'e': e})
                cleansed = 'STRING'
            finally:
                if hasattr(cleansed, 'keys'):
                    cleansed.update(
                        dict(
                            (param, CLEANSED_SUBSTITUTE)
                            for param in SENSITIVE_PARAMS
                            if param in cleansed))
        else:
            cleansed = 'STRING'
        # clean response sent to client
        if response.content and settings.FULL_RESPONSE_LOGGING:
            try:
                content = response.content
                    
            except AttributeError:
                content = 'UNSUPPORTED_STRING'
            except (UnsupportedFormat, ValueError):
                content = 'UNSUPPORTED_FORMAT'
        else:
            content = 'HIDDEN'
        # clean headers from client
        if settings.FULL_HEADER_LOGGING:
                cleansed_headers = getattr(request, 'META', {})
                cleansed_headers.update(
                    dict(
                        (param, CLEANSED_SUBSTITUTE)
                        for param in SENSITIVE_HEADERS
                        if param in cleansed_headers))
        else:
            cleansed_headers = ''

        if 'HTTP_X_FORWARDED_FOR' in request.META:
            ip = request.META['HTTP_X_FORWARDED_FOR'].split(",")[0]
        else:
            ip = request.META['REMOTE_ADDR']

        logger.info(
            u"[ACCESS] %(h)s %(l)s user=%(u)s - %(t)s \"%(r)s\" status=%(s)s "
            u"%(b)s - \"%(f)s\" - \"%(a)s\" - data=%(i)s - headers=%(j)s -"
            u"content=%(o)s",
            {
                'h': ip,
                'l': '-',
                'u': credentials,
                't': datetime.datetime.now(),
                'r': '%s %s' % (request.method, request.get_full_path()),
                's': response.status_code,
                'b': request.META.get('CONTENT_LENGTH', ''),
                'f': request.META.get('HTTP_REFERER', ''),
                'a': request.META.get(
                    'HTTP_USER_AGENT', '').decode('utf-8', 'replace'),
                'i': cleansed,
                'o': content,
                'j': cleansed_headers}
        )
        return response
开发者ID:thesgc,项目名称:chembiohub_ws,代码行数:83,代码来源:middleware.py

示例8: ApiTestCase

# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import deserialize [as 别名]
class ApiTestCase(DirectSEOTestCase):
    fixtures = ['seo_views_testdata.json']
    def setUp(self):
        super(ApiTestCase, self).setUp()
        # Create a test user and an API key for that user.
        self.user, created = User.objects.create_user(email='[email protected]',
                                                      password='password')
        self.username = self.user.email
        self.user.save()
        self.key = ApiKey(user=self.user)
        self.key.save()
        self.api_key = self.key.key
        self.auth_qs = '?&username=%s&api_key=%s' % (self.username,
                                                     self.api_key)
        self.entry_1 = SeoSite.objects.get(group=1)
        self.detail_url = '/api/v1/seosite/{0}/'.format(self.entry_1.pk)
        self.serializer = Serializer()

    def deserialize(self, resp):
        return self.serializer.deserialize(resp.content, format=resp['Content-Type'])

    def test_not_authorized(self):
        """
        Test if a user can gain access without an API key
        """
        user, created = User.objects.create_user(email='[email protected]',
                                                 password='password')
        self.username = self.user.email
        user.save()
        resp = self.client.get("api/v1/jobsearch/?format=xml")
        self.assertEqual(resp.status_code, 404)
        resp = self.client.get("api/v1/seosite/?format=xml")
        self.assertEqual(resp.status_code, 404)
        key = ApiKey(user=self.user)

    def test_list_xml(self):
        resp = self.client.get("/api/v1/seosite/?%s&format=xml" % (self.auth_qs))
        self.assertEqual(resp.status_code, 200)
        self.serializer.from_xml(resp.content)

    def test_list_json(self):
        resp = self.client.get("/api/v1/seosite/?%s&format=json" % (self.auth_qs))
        self.assertEqual(len(self.deserialize(resp)['objects']), 1)
        self.assertEqual(resp.status_code, 200)
        self.serializer.from_json(resp.content)

    def test_get_detail_xml(self):
        resp = self.client.get("/api/v1/seosite/1/%s&format=xml" % (self.auth_qs))
        self.assertEqual(resp.status_code, 200)
        self.serializer.from_xml(resp.content)

    def test_nopost(self):
        """
        Ensure that POST requests are rejected. This test can be removed
        if/when we allow other methods besides GET to our resources.

        """
        jobjson = ("""{"buid": 13543, "city": "Chester",\
                   "company": "Edward Jones", "country": "United States",\
                   "date_new": "2012-05-31T11:49:23",\
                   "mocs": "[\'021\', \'0193\', \'2820\', \'2G000\', \'2G091\',\
                   \'2R000\', \'2R071\', \'2R090\', \'2R171\', \'2S000\',\
                   \'2S071\', \'2S091\', \'2T000\', \'2T071\', \'2T091\',\
                   \'3A000\', \'3A071\', \'3A091\', \'3C000\', \'3C071\',\
                   \'3C090\', \'3C171\', \'3C191\', \'4A000\', \'4A091\',\
                   \'4A100\', \'4A191\', \'6F000\', \'6F091\', \'8M000\']",\
                   "onet": "43101100",\
                   "resource_uri": "/seo/v1/jobposting/29068157/",\
                   "state": "Virginia", "title": "Branch Office Administrator -\
                   Chester, VA - Branch 48113", "uid": "29068157"}""")
        resp = self.client.post("/api/v1/jobsearch/%s" % self.auth_qs,
                                data=jobjson, content_type="application/json")
        # HTTP 405 == 'Method Not Allowed'
        self.assertEqual(resp.status_code, 405)
开发者ID:DirectEmployers,项目名称:MyJobs,代码行数:76,代码来源:test_api.py

示例9: is_authorized

# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import deserialize [as 别名]
 def is_authorized(self, request, object=None):
     from client.api import EnvironmentResource, AreaResource, AnnotationResource
     from coresql.models import Environment, Area
     from coresql.utils import str2bool
     
     if hasattr(request, 'user') and not request.user.is_anonymous():
         env_obj = None
         area_obj = None
         
         
         if request.method.upper() == "GET":
             if 'environment' in request.GET:
                 try:
                     env_obj = Environment.objects.get(pk=request.GET['environment'])
                 except:
                     env_obj = None
                     
             if 'area' in request.GET:
                 try:
                     area_obj = Area.objects.get(pk=request.GET['area'])
                 except:
                     area_obj = None
             
             ''' For GET requests we check if there is a virtual access flag set in the request.
                 If the flag is not set, the default behavior is to assume physical check-in '''
             if 'virtual' in request.GET:
                 try:
                     virtual = str2bool(request.GET['virtual'])
                     if virtual and (area_obj or env_obj):
                         ''' if the virtual flag is set to TRUE, then allow access, otherwise, check that 
                         the user is actually checked-in where he says he is '''
                         return True
                 except ValueError:
                     return False
                 
          
         elif request.method.upper() == "POST":
             ''' for the rest of the methods check that the requesting user is actually checked in '''
             serdes = Serializer()
             deserialized = None
             try:
                 deserialized = serdes.deserialize(request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
             except Exception:
                 return False
                 
             if deserialized is None:
                 return False
                 
             if 'environment' in deserialized:
                 try:
                     #env_pk = int(deserialized['env'])
                     env_obj = EnvironmentResource().get_via_uri(deserialized['environment'], request=request) 
                 except:
                     env_obj = None
                         
             if 'area' in deserialized:
                 try:
                     #area_pk = int(deserialized['area'])
                     area_obj = AreaResource().get_via_uri(deserialized['area'], request=request)
                 except:
                     area_obj = None
         
         
         elif request.method.upper() in ["DELETE", "PUT"]:
             ann_res_uri = request.path
             try:
                 ann_obj = AnnotationResource().get_via_uri(ann_res_uri, request=request)
                 env_obj = ann_obj.environment
                 area_obj = ann_obj.area
                 
                 #print "[authorization] env_obj: ", env_obj
                 #print "[authorization] area_obj: ", area_obj
             except Exception:
                 #print "[authorization] exception in getting annotation resource for deletion: ", ex
                 env_obj = None
                 area_obj = None
         
         user_profile = request.user.get_profile()   ## will be an instance of UserProfile => available context
         return is_checked_in(user_profile, env_obj, area_obj)
     
     return False
开发者ID:asorici,项目名称:envived,代码行数:83,代码来源:authorization.py


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