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


Python ProvBundle._decode_JSON_container方法代码示例

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


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

示例1: obj_create

# 需要导入模块: from prov.model import ProvBundle [as 别名]
# 或者: from prov.model.ProvBundle import _decode_JSON_container [as 别名]
    def obj_create(self, bundle, request=None, **kwargs):
        prov_bundle = ProvBundle()
        prov_bundle._decode_JSON_container(bundle.data['content'])
        
        account = PDBundle.create(bundle.data['rec_id'], bundle.data['asserter'], request.user)
        account.save_bundle(prov_bundle)

        bundle.obj = account
        return bundle
开发者ID:,项目名称:,代码行数:11,代码来源:

示例2: BundleForm

# 需要导入模块: from prov.model import ProvBundle [as 别名]
# 或者: from prov.model.ProvBundle import _decode_JSON_container [as 别名]
class BundleForm(Form):
    ''' Form for creating a Bundle '''
    
    rec_id = forms.CharField(label=('Bundle ID'))
    public = forms.BooleanField(label=('Public'), required = False)
    submission = forms.FileField(label=('Original File'), required = False)
    license = LicenseMultipleChoiceField(License.objects, widget=CheckboxSelectMultiple, required=False)
    url = forms.URLField(label='URL to the bundle file:', required=False)
    content = forms.CharField(label=('Content (in JSON format)'), widget=Textarea(attrs={'class': 'span7'}), required=False)
    
    def clean(self):
        self.bundle = ProvBundle()
        ''' Try to parse content or download and parse URL - one at least needed'''
        if self.cleaned_data['content']:
            try:
                self.bundle._decode_JSON_container(loads(self.cleaned_data['content']))
            except ValueError:
                raise forms.ValidationError(u'Wrong syntax in the JSON content.')
        elif self.cleaned_data['url']:
            try:
                source = urlopen(self.cleaned_data['url'], timeout=5)
                url_content = source.read()
                source.close()
            except URLError:
                raise forms.ValidationError(u'There was a problem accessing the URL.')
            try:
                self.bundle._decode_JSON_container(loads(url_content))
            except ValueError:
                raise forms.ValidationError(u'Wrong syntax in the JSON content at the URL.')
        else:
            raise forms.ValidationError(u'No content or URL provided.')
        return self.cleaned_data
    
    def save(self, owner, commit=True):
        if self.errors:
            raise ValueError("The %s could not be %s because the data didn't"
                         " validate." % ('Container', 'created'))
            
        container = Container.create(self.cleaned_data['rec_id'], self.bundle, owner, self.cleaned_data['public'])
        save = False
        
        if 'submission' in self.files:
            file_sub = self.files['submission']
            sub = Submission.objects.create()
            sub.content.save(sub.timestamp.strftime('%Y-%m-%d%H-%M-%S')+file_sub._name, file_sub)
            container.submission = sub
            save = True
            
        for l in self.cleaned_data['license']:
            container.license.add(l)
            save = True
            
        if save:
            container.save()
        return container
开发者ID:YilinHao,项目名称:w3-prov,代码行数:57,代码来源:forms.py

示例3: get_document

# 需要导入模块: from prov.model import ProvBundle [as 别名]
# 或者: from prov.model.ProvBundle import _decode_JSON_container [as 别名]
    def get_document(self, doc_id, format=None, flattened=False, view=None):
        """Returns a ProvBundle object of the document with the ID provided or raises ApiNotFoundError"""

        extension = format if format is not None else 'json'
        view = "/views/%s" % view if view in ['data', 'process', 'responsibility'] else ""
        url = "documents/%d%s%s.%s" % (doc_id, "/flattened" if flattened else "", view, extension)
        response = self.request(url, raw=True)

        if format is None:
            # Try to decode it as a ProvBundle
            prov_document = ProvBundle()
            prov_document._decode_JSON_container(json.loads(response))
            return prov_document
        else:
            # return the raw response
            return response
开发者ID:bachour,项目名称:deptx,代码行数:18,代码来源:wrapper.py

示例4: setUp

# 需要导入模块: from prov.model import ProvBundle [as 别名]
# 或者: from prov.model.ProvBundle import _decode_JSON_container [as 别名]
 def setUp(self):
     logging.debug('Setting up user and checking the URL file...')
     self.check_u = User.objects.get_or_create(username='FileTesting')
     self.user = self.check_u[0]
     self.check_k = ApiKey.objects.get_or_create(user=self.user)
     self.key = self.check_k[0]
     self.auth = 'ApiKey' + self.user.username + ':' + self.key.key
     self.check_u = self.check_u[1]
     self.check_k = self.check_k[1]
     self.url = 'http://users.ecs.soton.ac.uk/ab9g10/test.json'
     source = urlopen(self.url)
     url_content = ProvBundle()
     url_content._decode_JSON_container(json.loads(source.read()))
     source.close()
     self.content = PDBundle.create('url_test')
     self.content.save_bundle(url_content)
     self.content = self.content.get_prov_bundle()
开发者ID:readingr,项目名称:provenance,代码行数:19,代码来源:tests.py

示例5: testOAuthAccess

# 需要导入模块: from prov.model import ProvBundle [as 别名]
# 或者: from prov.model.ProvBundle import _decode_JSON_container [as 别名]
    def testOAuthAccess(self):
        self.user = User.objects.create_user('jane', '[email protected]', 'toto')
        self.resource = Resource.objects.get_or_create(name='api', url='/api/')
        self.CONSUMER_KEY = 'dpf43f3p2l4k3l03'
        self.CONSUMER_SECRET = 'kd94hf93k423kf44'
        self.consumer, _ = Consumer.objects.get_or_create(
            key=self.CONSUMER_KEY, secret=self.CONSUMER_SECRET,
            defaults={
                'name': 'Test',
                'description': 'Testing...'
        })
        pb = ProvBundle()
        pb._decode_JSON_container('')
        self.bundle = Container.create('test_bundle', pb, self.user)
        
        c = Client()
        response = c.get("/oauth/request_token/")
        self.assertEqual(response.status_code, 401)
        import time
        parameters = {
            'oauth_consumer_key': self.CONSUMER_KEY,
            'oauth_signature_method': 'PLAINTEXT',
            'oauth_signature': '%s&' % self.CONSUMER_SECRET,
            'oauth_timestamp': str(int(time.time())),
            'oauth_nonce': 'requestnonce',
            'oauth_version': '1.0',
            'oauth_callback': 'http://test/request_token_ready',
            'scope': 'api',
            }
        response = c.get("/oauth/request_token/", parameters)
        self.assertEqual(response.status_code, 200)
        token = list(Token.objects.all())[-1]
        self.assertIn(token.key, response.content)
        self.assertIn(token.secret, response.content)
        self.assertTrue(token.callback_confirmed)

        parameters = {'oauth_token': token.key,}
        response = c.get("/oauth/authorize/", parameters)
        self.assertEqual(response.status_code, 302)
        self.assertIn(token.key, response['Location'])
        c.login(username='jane', password='toto')
        self.assertFalse(token.is_approved)
        response = c.get("/oauth/authorize/", parameters)
        self.assertEqual(response.status_code, 200)
        
        # fake authorization by the user
        parameters['authorize_access'] = 1
        response = c.post("/oauth/authorize/", parameters)
        self.assertEqual(response.status_code, 302)
        token = Token.objects.get(key=token.key)
        self.assertIn(token.key, response['Location'])
        self.assertTrue(token.is_approved)
        c.logout()
        
        # Exchange the Request token for an Access token
        parameters = {
            'oauth_consumer_key': self.CONSUMER_KEY,
            'oauth_token': token.key,
            'oauth_signature_method': 'PLAINTEXT',
            'oauth_signature': '%s&%s' % (self.CONSUMER_SECRET, token.secret),
            'oauth_timestamp': str(int(time.time())),
            'oauth_nonce': 'accessnonce',
            'oauth_version': '1.0',
            'oauth_verifier': token.verifier,
            'scope': 'api',
            }
        response = c.get("/oauth/access_token/", parameters)
        self.assertEqual(response.status_code, 200)
        access_token = list(Token.objects.filter(token_type=Token.ACCESS))[-1]
        self.assertIn(access_token.key, response.content)
        self.assertIn(access_token.secret, response.content)
        self.assertEqual(access_token.user.username, self.user.username)
        
        # Generating signature base string
        parameters = {
            'oauth_consumer_key': self.CONSUMER_KEY,
            'oauth_token': access_token.key,
            'oauth_signature_method': 'HMAC-SHA1',
            'oauth_timestamp': str(int(time.time())),
            'oauth_nonce': 'accessresourcenonce',
            'oauth_version': '1.0',
        }
        url_path = "/api/v0/bundle/%d/" % self.bundle.id
        oauth_request = oauth.Request.from_token_and_callback(access_token, http_url='http://testserver' + url_path, parameters=parameters)
        signature_method = oauth.SignatureMethod_HMAC_SHA1()
        signature = signature_method.sign(oauth_request, self.consumer, access_token)
        parameters['oauth_signature'] = signature
        response = c.get(url_path + '?format=json', parameters)
        self.assertEqual(response.status_code, 200)
开发者ID:readingr,项目名称:provenance,代码行数:91,代码来源:tests.py

示例6: obj_create

# 需要导入模块: from prov.model import ProvBundle [as 别名]
# 或者: from prov.model.ProvBundle import _decode_JSON_container [as 别名]
    def obj_create(self, bundle, request=None, **kwargs):
        '''
        Function to create a bundle via the API.
        Arguments (in JSON) are as follows:
            rec_id - the name for the Bundle (REQUIRED)
            content - the content in JSON format (or URL REQUIRDE)
            URL - a URL reference to the JSON content of the bundle * (OR content REQUIRED)
            public - indicator whether the Bundle to be made public, False if not provided
            licenses - a list of names corresponding to License objects in the DB
            submission - a file submitted which represents the Bundle **
        
        * - The URL is only opened and it's content parsed if and only if 'content' is empty
        ** - The file content is not parsed at all, it is just saved for later usage and
             if file is submitted the HTTP call should be in 'multipart' encoding format.
        '''
        
        try:
            '''Try to read the content else download and parse the URL file '''
            prov_bundle = ProvBundle()
            if bundle.data['content']:
                prov_bundle._decode_JSON_container(bundle.data['content'])
            else:
                source = urlopen(bundle.data['url'], timeout=5)
                content = source.read()
                source.close()
                prov_bundle._decode_JSON_container(loads(content))
            container = Container.create(bundle.data['rec_id'], prov_bundle, request.user)
        except: 
            raise ImmediateHttpResponse(HttpBadRequest())

        save = False
        if 'public' in bundle.data: 
            container.public = bundle.data['public']
            save = True
            if bundle.data['public']:
                assign('view_container', Group.objects.get(id=PUBLIC_GROUP_ID), container) 
                           
        if 'licenses' in bundle.data:
            for title in bundle.data['licenses']:
                try:
                    lic = License.objects.get(title=title)
                    container.license.add(lic)
                    save = True
                except License.DoesNotExist:
                    pass
        
        if 'submission' in request.FILES:
            file_sub = request.FILES['submission']
            sub = Submission.objects.create()
            sub.content.save(sub.timestamp.strftime('%Y-%m-%d%H-%M-%S')+file_sub._name, file_sub)
            container.submission = sub
            save = True
            
        if 'url' in bundle.data:
            container.url = bundle.data['url']
            save = True
            
        if save:
            container.save()
        bundle.obj = container
        return bundle
开发者ID:YilinHao,项目名称:w3-prov,代码行数:63,代码来源:api.py


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