Ejemplo n.º 1
0
def api_request(url, data=None):
    if data:
        data = json.dumps(data).encode('utf-8')
    r = Request(url, data=data)
    r.add_header('Authorization', 'Basic %s' % get_basic_auth())
    r.add_header('Accept', 'application/json')
    r.add_header('Content-type', 'application/json')
    r.add_header('User-Agent', 'Floobits Sublime Plugin %s %s py-%s.%s' % (G.__PLUGIN_VERSION__, sublime.platform(), sys.version_info[0], sys.version_info[1]))
    return urlopen(r, timeout=5)
Ejemplo n.º 2
0
    def __send_api_request(self, api_call, params={}, data=None):
        url = self.__urlBuilder.buildUrl(api_call, params)

        # if data is none, then we send a GET request, if not, then we send a POST request
        if data is None:
            response = urlopen(url, timeout=10).read()
        else:
            if isinstance(data, str):
                request = Request(url,
                                  data=bytes(data, "utf8"),
                                  headers={'Content-Type': 'application/xml'})
                response = urlopen(request, timeout=10).read()
            else:
                response = urlopen(url,
                                   timeout=10,
                                   data=urlencode(data).encode()).read()

        try:
            rawXml = parse(response)["response"]
        except Exception as e:
            raise BBBException("XMLSyntaxError", e.message)

        # get default config xml request will simply return the xml file without
        # returncode, so it will cause an error when try to check the return code
        if api_call != ApiMethod.GET_DEFAULT_CONFIG_XML:
            if rawXml["returncode"] == "FAILED":
                raise BBBException(rawXml["messageKey"], rawXml["message"])

        return rawXml
Ejemplo n.º 3
0
    def request(self):
        try:
            query = urlencode({
                "search_query": self.keyword,
                "page": self.offset,
                "sp": self.searchPreferences,
                "persist_gl": 1,
                "gl": self.region
            })
            request = Request(
                "https://www.youtube.com/results" + "?" + query,
                headers={"Accept-Language": f"{self.language},en;q=0.9"})
            response = urlopen(request).read()
            self.page = response.decode('utf_8')

            if self.page[0:29] == '  <!DOCTYPE html><html lang="':
                self.validResponse = True

        except:
            self.networkError = True
Ejemplo n.º 4
0
def downloadFileUrl(url,  saveFilename=None):
    """Download a file, given a URL.

    The URL is used to download a file, to the saveFilename specified.
    If no saveFilename is given, the basename of the URL is used.
    Before doownloading, first test to see if the file already exists.

    Args:
        | url (string): the url to be accessed.
        | saveFilename (string): path to where the file must be saved (optional).

    Returns:
        | (string): Filename saved, or None if failed.

    Raises:
        | Exceptions are handled internally and signaled by return value.
    """

    if saveFilename is None:
        filename = os.path.basename(url)
    else:
        filename = saveFilename

    if os.path.exists(filename):
        pass
    else:

        if sys.version_info[0] > 2:
            #python 3
            import urllib
            from urllib import Request
            import urllib.error 
            from urllib.error import HTTPError 

            try:
                #get file handle
                f = Request.urlopen(url)
                # Open file for writing
                with open(filename, "wb") as file:
                    file.write(f.read())
            #handle errors
            except urllib.error.HTTPError as e:
               print('HTTP Error: {} for {}'.format(e.code, url))
               return None
            except urllib.error.URLError as e:
               print('URL Error: {} for {}'.format(e.reason, url))
               return None
        else:
            #python 2.7
            import urllib2
            from urllib2 import HTTPError

            try:
                #get file handle
                f = urllib2.urlopen(url)
                # Open file for writing
                with open(filename, "wb") as file:
                    file.write(f.read())
            #handle errors
            except urllib2.HTTPError as e:
               print('HTTP Error: {} for {}'.format(e.code, url))
               return None
            except urllib2. URLError as e:
               print('URL Error: {} for {}'.format(e.reason, url))
               return None

    return filename
def loadURL(url):
    req = Request(url, headers=hdrs)
    f = urlopen(req)
    l = parse(f.read().decode("utf-8"))
    f.close()
    return l
import asana
# import pycurl
import urllib
from urllib import Request

# Personal access token
personal_access_token = '0/22905d2cc4fed64d634ee62d980737c4'

# CONSTRUCT ASANA CLIENT
client = asana.Client.access_token(personal_access_token)

url = "https://app.asana.com/api/1.0/projects"
request = Request(url)
request.add_header('personal_access_token', personal_access_token)
response = urlopen(Request)
print(response.read())

# Set things up to send the name of this script to us to show that you succeeded! This is optional.
# client.options['client_name'] = "hello_world_python"

# project = client.projects
# print(dir(project))
# print(project)

# Get your user info
me = client.users.me()
print(me)
print("Hello,  " + me["name"])
Ejemplo n.º 7
0
from urllib import Request, urlopen, URLError

request = Request('http://placekitten.com/')

try:
    response = urlopen(request)
    kittens = response.read()
    print(kittens[559:1000])
except URLError as e:
    print('No kittez. Got an error code:', e)