Exemple #1
0
 def encode_one(k, v):
     if isinstance(v, cls.FileUpload):
         return MultipartParam(k,
                               value=v.data,
                               filename=v.filename,
                               filetype=v.content_type)
     else:
         k = cls._to_data(k, "encode_one k")
         v = cls._to_data(v, "encode_one v")
         return MultipartParam(k, value=v)
Exemple #2
0
    def MultiPartPost(cls, url, data, file_name):
        from poster.encode import multipart_encode
        from poster.encode import MultipartParam
        from poster.streaminghttp import register_openers

        register_openers()
        if hasattr(data, 'read'):
            p = MultipartParam("file", fileobj=data, filename=file_name)
        else:
            p = MultipartParam("file", value=data, filename=file_name)
        datagen, headers = multipart_encode([p])
        return cls.request(url, datagen, headers)
Exemple #3
0
    def test_post_new_attachment(self):
        content_type = 'text/plain'
        filename = 'filename.txt'
        data = 'pretend to be binary attachment data'
        file = MultipartParam('attachment',
                              value=data,
                              filename=filename,
                              filetype=content_type)
        datagen, headers = multipart_encode([file])
        post_data = "".join(datagen)

        _, req = yield self.post_attachment(post_data, headers)

        self.assertEqual(201, req.code)
        self.assertEqual(
            '/attachment/B5B4ED80AC3B894523D72E375DACAA2FC6606C18EDF680FE95903086C8B5E14A',
            req.headers['Location'])
        response_json = {
            'ident':
            'B5B4ED80AC3B894523D72E375DACAA2FC6606C18EDF680FE95903086C8B5E14A',
            'content-type': content_type,
            'name': filename,
            'size': len(data),
            'encoding': 'base64'
        }
        self.assertEqual(response_json, json.loads(req.written[0]))
Exemple #4
0
    def add_attachment(self,
                       project_id,
                       story_id,
                       filename,
                       file_obj,
                       filetype,
                       filesize=None):
        if isinstance(file_obj, basestring):
            file_obj = open(file_obj, 'rb')
        file_data = MultipartParam(name='Filedata',
                                   filename=filename,
                                   filetype=filetype,
                                   fileobj=file_obj,
                                   filesize=filesize)

        params = {'Filedata': file_data}
        data, mp_headers = multipart_encode(params)

        if 'Content-Length' in mp_headers:
            mp_headers['Content-Length'] = str(mp_headers['Content-Length'])

        return self._post("projects/%s/stories/%s/attachments" %
                          (project_id, story_id),
                          body="".join(list(data)),
                          headers=mp_headers)
def poster_multipart(url, additionalParams, filename):
    # Register the streaming http handlers with urllib2
    #register_openers()
    username = ConfigSectionMap("Mascot")['username']
    password = ConfigSectionMap("Mascot")['password']
    login_url = MASCOT_CGI + '/login.pl'  #ConfigSectionMap("Mascot")['login_url']
    #To include cookie handling
    #opener = register_openers()
    #opener.add_handler(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))

    cookiejar = cookielib.CookieJar()
    loginOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))

    params = urllib.urlencode({
        'username': username,
        'password': password,
        'action': 'login'
    })

    request = urllib2.Request(login_url, params)
    login = loginOpener.open(request)
    #print login.read()

    # Upload File
    # use the login cookie for file upload
    register_openers(cookiejar=cookiejar)
    # Start the multipart/form-data encoding of the file "DSC0001.jpg"
    # "image1" is the name of the parameter, which is normally set
    # via the "name" parameter of the HTML <input> tag.
    # headers contains the necessary Content-Type and Content-Length
    # datagen is a generator object that yields the encoded parameters
    items = []
    #wrap post parameters
    for name, value in additionalParams.items():
        items.append(MultipartParam(name, value))
    #add file
    #fileobj=open(filename, "rb")
    #MultipartParam(name, value=None, filename=None, filetype=None, filesize=None, fileobj=None, cb=None)
    items.append(MultipartParam.from_file('FILE', filename))
    #items.append(MultipartParam('infile', open(filename, "r"),filetype='text/plain; charset=utf8'))
    # Data for MS/MS ion searches must be supplied as an ASCII file
    #items.append(MultipartParam('FILE',fileobj ,filetype='application/octet-stream'))

    datagen, headers = multipart_encode(items)
    user_agent = 'Mozilla/5.0'
    headers['User-Agent'] = user_agent
    #headers['Content-Transfer-Encoding']= 'base64'

    #s = "".join(datagen)
    # Create the Request object
    #request = urllib2.Request(url, b2a_base64(s), headers)
    request = urllib2.Request(url, datagen, headers)

    #To add basic authentication to the request
    #auth = base64.encodestring('%s:%s' % (username, password))[:-1] # This is just standard un/pw encoding
    #request.add_header('Authorization', 'Basic %s' % auth ) # Add Auth header to request

    # Actually do the request, and get the response

    return urllib2.urlopen(request)
Exemple #6
0
def reply_with_selfie_drafts(recipient_id, img):
    badge = Image.open("assets/" + user_db[recipient_id]["template"] + ".png")
    badge.thumbnail(img.size)

    # pasting badge on bottom right edge
    img.paste(badge,
              (img.size[0] - badge.size[0], img.size[1] - badge.size[1]),
              badge)

    temp_filepath = 'assets/selfie-' + str(uuid.uuid4()) + '.png'
    img.save(temp_filepath)

    params = {"access_token": access_token}

    data = {
        "recipient[id]": recipient_id,
        "message[attachment][type]": "image",
        "message[attachment][payload][]": ""
    }
    items = []

    for name, value in data.items():
        items.append(MultipartParam(name, value))
    items.append(MultipartParam.from_file("file", temp_filepath))

    url = "https://graph.facebook.com/v2.6/me/messages?" + urllib.urlencode(
        params)

    datagen, headers = multipart_encode(items)
    request = urllib2.Request(url, datagen, headers)
    print "#### REQUEST"
    response = urllib2.urlopen(request)

    print response.read()
    os.remove(temp_filepath)
Exemple #7
0
def post_file(url,
              file_name,
              file_type,
              file_size,
              file_obj,
              options=dict(),
              username=None,
              password=None):

    # Input checks
    if url is None:
        raise ValueError('url')

    if file_name is None:
        raise ValueError('file_name')

    if file_type is None:
        raise ValueError('file_type')

    if file_size is None:
        raise ValueError('file_size')

    if file_obj is None:
        raise ValueError('file_obj')

    if options is None:
        raise ValueError('options')

    logging.debug('Preparing file {0}'.format(file_name))

    # This is the post arguments section
    options['file'] = MultipartParam('file',
                                     filename=file_name,
                                     filetype=file_type,
                                     filesize=file_size,
                                     fileobj=file_obj)

    data, headers = multipart_encode(options)

    logging.debug('Submitting the file to {0}'.format(url))

    # For authorization (optional)
    if username is not None and password is not None:
        headers['Authorization'] = generate_authorization_header(
            username, password)

    fetch = urlfetch.fetch(url=url,
                           payload="".join(data),
                           method=urlfetch.POST,
                           headers=headers)
    response = fetch.content

    return response
 def testRun():
     response = ''
     try:
         register_openers()
         p = MultipartParam("file", "0123456789abcdef", "test.txt", "text/plain; charset=utf8")
         datagen, headers = multipart_encode( [("var4", "val with spaces"), p] )
         request = urllib2.Request('http://etd.local/upload', datagen, headers)
         response = urllib2.urlopen(request, None, 2).read()
     except:
         return 1
     if response != 'test.txt:16&var4=val with spaces':
         return 1
     return 0
Exemple #9
0
def send_photo(data, filename, caption):
    logging.info("Sending photo: %s", filename)
    payload = {}
    payload['userId'] = 'test'
    payload['caption'] = caption
    payload['photoFile'] = MultipartParam('photoFile',
                                          filename=filename,
                                          filetype='image/jpeg',
                                          fileobj=cStringIO.StringIO(data))

    data, headers = multipart_encode(payload)
    urlfetch.fetch(url='https://friggr.unlessquit.com/inbox',
                   method=urlfetch.POST,
                   payload="".join(data),
                   headers=headers)
Exemple #10
0
def postFileRequest(url,
                    paramName,
                    fileObj,
                    additionalHeaders={},
                    additionalParams={}):
    items = []
    # wrap post parameters
    for name, value in additionalParams.items():
        items.append(MultipartParam(name, value))
    # add file
    items.append(MultipartParam.from_file(paramName, fileObj))
    datagen, headers = multipart_encode(items)
    # add headers
    for item, value in additionalHeaders.iteritems():
        headers[item] = value
    return urllib2.Request(url, datagen, headers)
Exemple #11
0
def voice(file_path, apikey):
    time.sleep(5)
    url = "https://api.webempath.net/v2/analyzeWav"
    register_openers()
    items = [MultipartParam('apikey', apikey),
             MultipartParam.from_file('wav', file_path)]
    datagen, headers = multipart_encode(items)
    request = urllib2.Request(url, datagen, headers)
    readObject = urllib2.urlopen(request)  # type: object

    if readObject.getcode() != 200:
        print("HTTP status %d" % (readObject.getcode()))

    response = json.load(readObject)
    print(response)
    if response["error"] > 0:
        print(response["error"])
Exemple #12
0
    def query(self,
              endpoint,
              parameters={},
              method='GET',
              postdata='',
              mimetype=None):
        parameters['access_token'] = self.token
        parameters['appsecret_proof'] = hmac.new(self.secret, self.token,
                                                 hashlib.sha256).hexdigest()

        #       print parameters
        f = None
        resstr = None

        datagen = ''
        headers = {}

        if method == 'POST' and postdata is not '':
            register_openers()
            mp_param = MultipartParam('source',
                                      value=postdata,
                                      filename='upload.png',
                                      filetype=mimetype)
            datagen, headers = multipart_encode([mp_param])

        try:
            data = urllib.urlencode(parameters)
            url = 'https://graph.facebook.com/' + self.apiver + '/' + endpoint + '?' + data
            #print url
            if method == 'POST':
                req = urllib2.Request(url, datagen, headers)
            else:
                req = urllib2.Request(url)

            f = urllib2.urlopen(req)
        except urllib2.HTTPError as e:
            print dir(e)
            #print e.message
            print parameters
            return json.loads(e.read(), object_pairs_hook=objdict)

        if f != None:
            resstr = f.read()
            return json.loads(resstr, object_pairs_hook=objdict)
Exemple #13
0
def cmd_upload(dist, *pack_files):
    """Upload a package to the repo.

    upload DISTRIBUTION FILE1 [FILE2 ... FILEN]
    """

    if not pack_files:
        raise ArgumentError("No packfiles specified.")

    buf = ""
    for file_ in pack_files:
        print file_
        sys.stdout.flush()
        if file_.endswith(".changes"):
            (file_, pack) = create_pack(file_)
        else:
            pack = open(file_, 'r')

        print "Uploading %s" % file_
        try:
            (data, headers) = multipart_encode(
                (MultipartParam('package', filename=file_, fileobj=pack), ))

            output = request(dist,
                             method="POST",
                             body="".join(data),
                             headers=dict(
                                 (key, str(val))
                                 for (key, val) in headers.iteritems()))

            if isinstance(output, str):
                buf += "While uploading %s: %s" % (file_, output)
                continue

            try:
                buf += "\n\n".join(format_dict(pkg[0]) for pkg in output)
            except IndexError:
                buf += "While uploading %s: %s" % (file_, output)
                continue
        finally:
            pack.close()

    return buf