コード例 #1
0
ファイル: tasks.py プロジェクト: noviluni/django-bima-back
def upload_photo(form_data, user_id, user_token, lang, create=True):
    api_url = join(settings.WS_BASE_URL, PRIVATE_API_SCHEMA_URL)
    chunk_size = config.PHOTO_UPLOAD_CHUNK_SIZE

    # request headers
    authorization = {'Authorization': 'Token {}'.format(user_token)}
    headers = dict(authorization)
    headers.update({
        'Accept-Language': lang,
        'content_type': MULTIPART_CONTENT
    })

    transports = HTTPTransport(credentials=authorization, headers=headers)
    client = Client(transports=[transports])

    # get api schema
    schema_cache_key = "{}_{}".format(CACHE_SCHEMA_PREFIX_KEY, user_id)
    schema = cache.get(schema_cache_key)
    if not schema:
        schema = client.get(api_url)
        cache_set(schema_cache_key, schema)

    # get image to upload
    upload_id = form_data.pop('upload_id')
    image = MyChunkedUpload.objects.get(upload_id=upload_id)
    image_file = image.file
    filename = image.filename

    # request parameters
    data = {'filename': filename}
    offset, chunks = 0, image_file.chunks(chunk_size)
    request_path = ['photos', 'upload', 'update']
    img_id = 0

    for chunk_file in chunks:
        data.update(**{'file': ContentFile(chunk_file)})
        client.transports[0].headers._data[
            'Content-Range'] = 'bytes {}-{}/{}'.format(
                offset, offset + len(chunk_file), image_file.size)
        response = client.action(schema, request_path, params=data)
        offset = response['offset']
        img_id = response['id']
        data.update({'id': img_id})
        request_path = ['photos', 'upload', 'chunk', 'update']

    request_path = ['photos', 'upload', 'chunk', 'create']
    data.update({'md5': _checksum_file(image_file, chunk_size)})
    client.action(schema, request_path, params=data)

    # Request is not multipart, so we remove the header, otherwise uwsgi doesn't works
    client.transports[0].headers._data.pop('content_type', None)

    # upload photo information
    form_data['image'] = img_id
    form_data['original_file_name'] = filename
    if create:
        form_data['owner'] = user_id
        client.action(schema, ['photos', 'create'], params=form_data)
    else:
        client.action(schema, ['photos', 'partial_update'], params=form_data)
コード例 #2
0
ファイル: service.py プロジェクト: morenosan/django-bima-back
    def __init__(self, request):
        super(DAMWebService, self).__init__()
        api_url = join(settings.WS_BASE_URL, PRIVATE_API_SCHEMA_URL)

        self.request = request
        self.user_id = request.user.id

        # initialize api client with user token
        user_params = cache.get("{}_{}".format(CACHE_USER_PROFILE_PREFIX_KEY,
                                               self.user_id))
        authorization = {}
        if user_params and user_params.get('token'):
            authorization = {
                'Authorization': 'Token {}'.format(user_params.get('token'))
            }
        headers = dict(authorization)
        headers.update({
            'Accept-Language':
            request.META.get('HTTP_ACCEPT_LANGUAGE', request.LANGUAGE_CODE)
        })

        transports = HTTPTransport(
            credentials=authorization,
            headers=headers,
            response_callback=self._callback_client_transport)
        self.client = Client(transports=[transports])

        # get api schema
        schema_cache_key = "{}_{}".format(CACHE_SCHEMA_PREFIX_KEY,
                                          self.user_id)
        self.schema = cache.get(schema_cache_key)
        if not self.schema:
            self.schema = self.get_or_logout(api_url)
            cache.set(schema_cache_key, self.schema)
コード例 #3
0
ファイル: base.py プロジェクト: ryo-ma/fiware-meteoroid-cli
 def _action(self,
             fiware_service,
             fiware_service_path,
             keys,
             params=None,
             validate=True):
     headers = {
         'Fiware-Service': fiware_service,
         'Fiware-ServicePath': fiware_service_path
     }
     transport = HTTPTransport(headers=headers)
     client = Client(transports=[transport])
     document = client.get(self.schema_endpoint)
     return client.action(document, keys, params, validate)
コード例 #4
0
def http():
    return HTTPTransport()
コード例 #5
0
# coding: utf-8
from coreapi import Document, Link, Field
from coreapi.codecs import CoreJSONCodec
from coreapi.compat import force_text
from coreapi.exceptions import NetworkError
from coreapi.transports import HTTPTransport
from coreapi.utils import determine_transport
import pytest
import requests
import json

decoders = [CoreJSONCodec()]
transports = [HTTPTransport()]


@pytest.fixture
def http():
    return HTTPTransport()


class MockResponse(object):
    def __init__(self, content):
        self.content = content
        self.headers = {}
        self.url = 'http://example.org'
        self.status_code = 200


# Test transport errors.