Exemple #1
0
def upload(picPath):
    # Create the form
    form = MultiPartForm()

    # Add the image and required fields
    mimeType = mimetypes.guess_type(picPath)[0]
    form.add_file("encoded_image", picPath, StringIO(""), mimeType)
    form.add_field("image_content", "")

    # Build the request
    request = urllib2.Request("http://www.google.fr/searchbyimage/upload")
    body = str(form)
    request.add_header("Content-type", "%s;boundary=----WebKitFormBoundaryB6DC4larUvuT5gBS" % (form.get_content_type()))
    request.add_header("Content-length", len(body))
    request.add_header(
        "User-Agent",
        "User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36",
    )
    request.add_data(body)

    print
    print "REQUEST:"
    print request.get_data()

    print
    print "SERVER RESPONSE:"
    # print urllib2.urlopen(request).read()
    print urllib2.urlopen(request).info()
 def __init__(self,repo, command, callback=None):
     KillableThread.__init__(self)
     self.repo = repo
     self.callback=callback
     global cookiejar
     self.cookiejar = cookiejar
     
     assert SkarphedRepository.COMMANDS.has_key(command['c'])
     
     url = str(repo.getUrl())
     
     json_enc = json.JSONEncoder()
     
     form = MultiPartForm()
     form.add_field('j',json_enc.encode(command))
     
     post = str(form)
     
     self.request = urllib2.Request(url)
     self.request.add_header('User-agent','SkarphedAdmin')
     self.request.add_header('Content-type',form.get_content_type())
     self.request.add_header('Body-length',len(post))
     self.request.add_data(post)
     
     Tracker().addThread(self)
Exemple #3
0
    def request(self, method, path, data=None, file=None, timeout=60):
        base64string = base64.encodestring(
            ('%s:%s' %
             (self.__application.token, self.__application.private_key)
             ).encode()).decode().replace('\n', '')
        headers = {"Authorization": "Basic %s" % base64string}

        if method == "GET":
            result = requests.get(self.__baseuri + path,
                                  params=data,
                                  headers=headers,
                                  timeout=timeout)
        else:
            data = {} if data is None else data
            if file is None:
                result = requests.request(method=method,
                                          url=self.__baseuri + path,
                                          data=data,
                                          headers=headers,
                                          timeout=timeout)
            else:
                form_file = [('file', ntpath.basename(file), open(file, "rb"))]
                content_type, body = MultiPartForm().encode(data, form_file)

                headers.update({'Content-type': content_type})
                headers.update({'Content-length': len(body)})

                result = requests.request(method=method,
                                          url=self.__baseuri + path,
                                          data=body,
                                          headers=headers,
                                          timeout=timeout)

        return result
Exemple #4
0
 def request(self, method, path, data=None, file=None):
     path = path.encode("ascii", "ignore")
     if (method == "GET" and data != None):
         path = path + "?" + urllib.urlencode(data)
     if (method != "GET" and method != "POST"):
         path = path + "?_method=" + method
     request = urllib2.Request(self.__application.config.server_api_url +
                               "/v1" + path)
     base64string = base64.encodestring(
         '%s:%s' % (self.__application.token,
                    self.__application.private_key)).replace('\n', '')
     request.add_header("Authorization", "Basic %s" % base64string)
     if (method == "GET"):
         result = urllib2.urlopen(request)
     else:
         if (data == None):
             data = {}
         if (file == None):
             result = urllib2.urlopen(request, urllib.urlencode(data))
         else:
             form = MultiPartForm()
             for k, v in data.iteritems():
                 form.add_field(k, v)
             form.add_file('file',
                           ntpath.basename(file),
                           fileHandle=open(file))
             body = str(form)
             request.add_header('Content-type', form.get_content_type())
             request.add_header('Content-length', len(body))
             result = urllib2.urlopen(request, body)
     return result.read()
Exemple #5
0
def upload(picPath):
    # Create the form
    form = MultiPartForm()

    # Add the image and required fields
    mimeType = mimetypes.guess_type(picPath)[0]
    form.add_file('encoded_image', picPath, StringIO(''), mimeType)
    form.add_field('image_content', '')

    # Build the request
    request = urllib2.Request('http://www.google.fr/searchbyimage/upload')
    body = str(form)
    request.add_header(
        'Content-type', '%s;boundary=----WebKitFormBoundaryB6DC4larUvuT5gBS' %
        (form.get_content_type()))
    request.add_header('Content-length', len(body))
    request.add_header(
        'User-Agent',
        'User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36'
    )
    request.add_data(body)

    print
    print 'REQUEST:'
    print request.get_data()

    print
    print 'SERVER RESPONSE:'
    #print urllib2.urlopen(request).read()
    print urllib2.urlopen(request).info()
Exemple #6
0
 def request(self, method, path, data = None, file = None):
     path = path.encode("ascii", "ignore")
     if (method == "GET" and data != None):
         path = path + "?" + urllib.urlencode(data)        
     if (method != "GET" and method != "POST"):
         path = path + "?_method=" + method
     request = urllib2.Request(self.__application.config.server_api_url + "/v1" + path)
     base64string = base64.encodestring('%s:%s' % (self.__application.token, self.__application.private_key)).replace('\n', '')
     request.add_header("Authorization", "Basic %s" % base64string)
     if (method == "GET"):   
         result = urllib2.urlopen(request)
     else:
         if (data == None):
             data = {}
         if (file == None):
             result = urllib2.urlopen(request, urllib.urlencode(data))
         else:
             form = MultiPartForm()
             for k, v in data.iteritems():
                 form.add_field(k, v)
             form.add_file('file', ntpath.basename(file), fileHandle=open(file)) 
             body = str(form)
             request.add_header('Content-type', form.get_content_type())
             request.add_header('Content-length', len(body))
             result = urllib2.urlopen(request, body)
     return result.read()
    def request(self, method, path, data=None, file=None, timeout=60):
        path = path.encode("ascii", "ignore")
        if (method == "GET" and data != None):
            path = path.decode('ascii',
                               'ignore') + "?" + urllib.urlencode(data)
        if (method != "GET" and method != "POST"):
            path = path.decode('ascii', 'ignore') + "?_method=" + method
        server_api_url = self.__application.config.server_api_url
        for k, v in self.__application.config.regions.items():
            if (self.__application.token.startswith(k)):
                server_api_url = v

        if not isinstance(path, basestring):
            path = path.decode("ascii", "ignore")

        request = urllib2.Request(server_api_url + "/v1" + path)

        base64string = base64.encodestring(
            ('%s:%s' %
             (self.__application.token, self.__application.private_key)
             ).encode()).decode().replace('\n', '')

        request.add_header("Authorization", "Basic %s" % base64string)
        if (method == "GET"):
            result = urllib2.urlopen(request, None, timeout)
        else:
            if (data == None):
                data = {}
            if (file == None):
                data = urllib.urlencode(data)
                binary_data = data.encode("ascii")
                result = urllib2.urlopen(request, binary_data, timeout)
            else:
                form_file = [('file', ntpath.basename(file), open(file, "rb"))]
                content_type, body = MultiPartForm().encode(data, form_file)

                request.add_header('Content-type', content_type)
                request.add_header('Content-length', len(body))
                result = urllib2.urlopen(request, body, timeout)

        try:
            accept_ranges = result.getheader('Accept-Ranges')
            if (accept_ranges == 'bytes'):
                return result.read()
            else:
                return result.read().decode('ascii')
        except AttributeError as e:
            return result.read()
authGroup.add_option("-P", "--password", help="password")
plugin.parser.add_option_group(authGroup)

try:
    plugin.begin()
    verbose = plugin.options.verbose

    # Validate arguments
    if (plugin.options.httphost is None):
        plugin.parser.error("-H/--httphost is required")

    if (plugin.options.password is None):
        plugin.parser.error("-P/--password option is required")

    # Prepare login
    form = MultiPartForm()
    form.add_field('username', plugin.options.username)
    form.add_field('password', plugin.options.password)
    form.add_field('Submit', 'Login')
    # We need session cookies
    cj = cookielib.LWPCookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    urllib2.install_opener(opener)
    # Shortcuts...
    urlopen = urllib2.urlopen
    Request = urllib2.Request
    # Set timeout for requests
    socket.setdefaulttimeout(10)

    # Must get a session cookie first
    req = Request(plugin.options.httphost + '/login.cgi')
authGroup.add_option("-P", "--password", help="password")
plugin.parser.add_option_group(authGroup)

try:
    plugin.begin()
    verbose = plugin.options.verbose

    # Validate arguments
    if plugin.options.httphost is None:
        plugin.parser.error("-H/--httphost is required")

    if plugin.options.password is None:
        plugin.parser.error("-P/--password option is required")

        # Prepare login
    form = MultiPartForm()
    form.add_field("username", plugin.options.username)
    form.add_field("password", plugin.options.password)
    form.add_field("Submit", "Login")
    # We need session cookies
    cj = cookielib.LWPCookieJar()

    if plugin.options.httphost.startswith("https"):
        # We typically can not verify peer certificates
        # (self-signed, pre-installed on monitored devices)
        import ssl

        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), urllib2.HTTPSHandler(context=ctx))
authGroup.add_option ("-P", "--password", help="password")
plugin.parser.add_option_group (authGroup)

try:
	plugin.begin()
	verbose = plugin.options.verbose

	# Validate arguments
	if (plugin.options.httphost is None):
		plugin.parser.error ("-H/--httphost is required")

	if (plugin.options.password is None):
		plugin.parser.error ("-P/--password option is required")

	# Prepare login
	form = MultiPartForm()
	form.add_field('username', plugin.options.username)
	form.add_field('password', plugin.options.password)
	form.add_field('Submit', 'Login')
	# We need session cookies
	cj = cookielib.LWPCookieJar()

	if plugin.options.httphost.startswith('https'):
		# We typically can not verify peer certificates
		# (self-signed, pre-installed on monitored devices)
		import ssl
		ctx = ssl.create_default_context()
		ctx.check_hostname = False
		ctx.verify_mode = ssl.CERT_NONE
		opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj),
                                      urllib2.HTTPSHandler(context=ctx))
Exemple #11
0
    for file_to_publish in []:#['checklink_building.html','checklink_output.html']:
    
        url = bt_url + "/biomed_town/City_Hall/Planning/broken_links/createObject?type_name=File"
        req = urllib2.Request(url)
        
        response = opener.open(req)
        response.read()
        
        # we have created a new file
        
        url = response.url #portal_factory url    
        print url
        
        headers = { 'Content-Type' :'application/x-www-form-urlencoded'}
        
        form = MultiPartForm()
        if file_to_publish.count("building"):
            form.add_field('id', 'interna_broken_link_%s' % timestamp)
            form.add_field('title', 'Internal Broken Link Report %s-%s-%s' % (now.year, now.month, now.day) )
        else:
            form.add_field('id', 'total_broken_link_%s' % timestamp)
            form.add_field('title', 'Total Broken Link Report %s-%s-%s' % (now.year, now.month, now.day) )
            
        form.add_field('form_submit', 'Save')
        form.add_field('form.submitted','1')
        
        # Add the file
        f = open(file_to_publish,'r')
        form.add_file('file_file', 'checklink_output.html', fileHandle = f )
        f.close()
Exemple #12
0
    for file_to_publish in []:  #['checklink_building.html','checklink_output.html']:

        url = bt_url + "/biomed_town/City_Hall/Planning/broken_links/createObject?type_name=File"
        req = urllib2.Request(url)

        response = opener.open(req)
        response.read()

        # we have created a new file

        url = response.url  #portal_factory url
        print url

        headers = {'Content-Type': 'application/x-www-form-urlencoded'}

        form = MultiPartForm()
        if file_to_publish.count("building"):
            form.add_field('id', 'interna_broken_link_%s' % timestamp)
            form.add_field(
                'title', 'Internal Broken Link Report %s-%s-%s' %
                (now.year, now.month, now.day))
        else:
            form.add_field('id', 'total_broken_link_%s' % timestamp)
            form.add_field(
                'title', 'Total Broken Link Report %s-%s-%s' %
                (now.year, now.month, now.day))

        form.add_field('form_submit', 'Save')
        form.add_field('form.submitted', '1')

        # Add the file