Python urllib.quote_plus() Examples

The following are code examples for showing how to use urllib.quote_plus(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_urllib.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_quoting_space(self):
        # Make sure quote() and quote_plus() handle spaces as specified in
        # their unique way
        result = urllib.quote(' ')
        self.assertEqual(result, hexescape(' '),
                         "using quote(): %s != %s" % (result, hexescape(' ')))
        result = urllib.quote_plus(' ')
        self.assertEqual(result, '+',
                         "using quote_plus(): %s != +" % result)
        given = "a b cd e f"
        expect = given.replace(' ', hexescape(' '))
        result = urllib.quote(given)
        self.assertEqual(expect, result,
                         "using quote(): %s != %s" % (expect, result))
        expect = given.replace(' ', '+')
        result = urllib.quote_plus(given)
        self.assertEqual(expect, result,
                         "using quote_plus(): %s != %s" % (expect, result)) 
Example 2
Project: flasky   Author: RoseOu   File: selenium.py    MIT License 6 votes vote down vote up
def do_command(self, verb, args):
        conn = http_client.HTTPConnection(self.host, self.port, timeout=self.http_timeout)
        try:
            body = 'cmd=' + urllib_parse.quote_plus(unicode(verb).encode('utf-8'))
            for i in range(len(args)):
                body += '&' + unicode(i+1) + '=' + \
                        urllib_parse.quote_plus(unicode(args[i]).encode('utf-8'))
            if (None != self.sessionId):
                body += "&sessionId=" + unicode(self.sessionId)
            headers = {
                "Content-Type":
                "application/x-www-form-urlencoded; charset=utf-8"
            }
            conn.request("POST", "/selenium-server/driver/", body, headers)

            response = conn.getresponse()
            data = unicode(response.read(), "UTF-8")
            if (not data.startswith('OK')):
                raise Exception(data)
            return data
        finally:
            conn.close() 
Example 3
Project: plugin.program.steam.streaming   Author: Drakulix   File: utils.py    MIT License 6 votes vote down vote up
def addGame(name, app_id, state, username, hostname, thump=None, fanart=None):
    #non steam games do not have fanart
    if fanart == None:
        fanart = os.path.join(MEDIA_PATH, "background.jpg")
    if thump == None:
        thump = os.path.join(MEDIA_PATH, "game.png")

    context = []
    context.append(("Achievements", 'Container.Update(plugin://plugin.program.steam.streaming/?mode=achievements&hostname=&appid='+str(app_id)+"&username="+urllib.quote_plus(username)+"&hostname="+urllib.quote_plus(hostname)+')',))

    #storefront api is broken
    #context.append(("Trailers", 'Container.Update(plugin://plugin.program.steam.streaming/?mode=movies&hostname=&appid='+str(app_id)+"&username="+urllib.quote_plus(username)+"&hostname="+urllib.quote_plus(hostname)+')',))

    #grey out uninstalled entries
    if state == -1:
        addDir(name, sys.argv[0]+"?mode=game&id="+str(app_id)+"&username="+urllib.quote_plus(username)+"&hostname="+urllib.quote_plus(hostname), thump, fanart, "22FFFFFF", context)
    else:
        addDir(name, sys.argv[0]+"?mode=game&id="+str(app_id)+"&username="+urllib.quote_plus(username)+"&hostname="+urllib.quote_plus(hostname), thump, fanart, contextMenus=context)

#add achievement entry 
Example 4
Project: EDMC-Canonn   Author: canonn-science   File: codex.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, cmdr, is_beta, system, x, y, z, entry, body, lat, lon, client):

        threading.Thread.__init__(self)
        # debug("gSubmitCodex({},{},{},{},{},{},{},{},{},{},{})".format((self,cmdr, is_beta, system, x,y,z,entry, body,lat,lon,client)))
        self.cmdr = quote_plus(cmdr.encode('utf8'))
        self.system = quote_plus(system.encode('utf8'))
        self.x = x
        self.y = y
        self.z = z
        self.body = ""
        self.lat = ""
        self.lon = ""
        if body:
            self.body = quote_plus(body.encode('utf8'))
        if lat:
            self.lat = lat
            self.lon = lon

        if is_beta:
            self.is_beta = 'Y'
        else:
            self.is_beta = 'N'

        self.entry = entry 
Example 5
Project: ngo-addons-backport   Author: camptocamp   File: main.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def import_url(self, req, url):
        modules = webmain.module_boot(req) + ['edi']
        modules_str = ','.join(modules)
        modules_json = simplejson.dumps(modules)
        js = "\n        ".join('<script type="text/javascript" src="%s"></script>' % i for i in webmain.manifest_list(req, modules_str, 'js'))
        css = "\n        ".join('<link rel="stylesheet" href="%s">' % i for i in webmain.manifest_list(req, modules_str, 'css'))

        # `url` may contain a full URL with a valid query string, we basically want to watch out for XML brackets and double-quotes 
        safe_url = urllib.quote_plus(url,':/?&;=')

        return webmain.html_template % {
            'js': js,
            'css': css,
            'modules': modules_json,
            'init': 's.edi.edi_import("%s");' % safe_url,
        } 
Example 6
Project: openhatch   Author: campbe13   File: ClientForm.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def _click(self, form, coord, return_type, request_class=urllib2.Request):
        # Relative URL for ISINDEX submission: instead of "foo=bar+baz",
        # want "bar+baz".
        # This doesn't seem to be specified in HTML 4.01 spec. (ISINDEX is
        # deprecated in 4.01, but it should still say how to submit it).
        # Submission of ISINDEX is explained in the HTML 3.2 spec, though.
        parts = self._urlparse(form.action)
        rest, (query, frag) = parts[:-2], parts[-2:]
        parts = rest + (urllib.quote_plus(self.value), None)
        url = self._urlunparse(parts)
        req_data = url, None, []

        if return_type == "pairs":
            return []
        elif return_type == "request_data":
            return req_data
        else:
            return request_class(url) 
Example 7
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: crash.py    MIT License 6 votes vote down vote up
def __init__(self, location = None, allowRepeatedKeys = True):
        """
        @type  location: str
        @param location: Location of the crash database.
            It must be an ODBC connection string.

        @type  allowRepeatedKeys: bool
        @param allowRepeatedKeys:
            If C{True} all L{Crash} objects are stored.

            If C{False} any L{Crash} object with the same signature as a
            previously existing object will be ignored.
        """
        warnings.warn(
            "The %s class is deprecated since WinAppDbg 1.5." % self.__class__,
            DeprecationWarning)
        import urllib
        url = "mssql+pyodbc:///?odbc_connect=" + urllib.quote_plus(location)
        super(CrashTableMSSQL, self).__init__(url, allowRepeatedKeys) 
Example 8
Project: Pancas   Author: Sup3Roque   File: default.py    GNU General Public License v2.0 6 votes vote down vote up
def addLinkMeta(name,url,mode,iconimage,itemcount,isFolder=False):
        splitName=name.partition('(')
	simplename=""
	simpleyear=""
	if len(splitName)>0:
                simplename=splitName[0]
		simpleyear=splitName[2].partition(')')
	if len(simpleyear)>0:
		simpleyear=simpleyear[0]
	mg = metahandlers.MetaData()
	meta = mg.get_meta('movie', name=simplename ,year=simpleyear)
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage=meta['cover_url'], thumbnailImage=meta['cover_url'])
	liz.setInfo( type="Video", infoLabels= meta )
	contextMenuItems = []
	contextMenuItems.append(('Movie Information', 'XBMC.Action(Info)'))
	liz.addContextMenuItems(contextMenuItems, replaceItems=False)
	if not meta['backdrop_url'] == '': liz.setProperty('fanart_image', meta['backdrop_url'])
	else: liz.setProperty('fanart_image', fanart)
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=isFolder,totalItems=itemcount)
	return ok 
Example 9
Project: Pancas   Author: Sup3Roque   File: trailer.py    GNU General Public License v2.0 6 votes vote down vote up
def search(self, url):
        try:
            query = urlparse.parse_qs(urlparse.urlparse(url).query)['q'][0]

            url = self.search_link % urllib.quote_plus(query) + self.key_link

            result = client.request(url)

            items = json.loads(result)['items']
            items = [(i['id']['videoId']) for i in items]

            for url in items:
                url = self.resolve(url)
                if not url is None: return url
        except:
            return 
Example 10
Project: Pancas   Author: Sup3Roque   File: movies.py    GNU General Public License v2.0 6 votes vote down vote up
def search(self, query=None):
        #try:
            if query == None:
                t = control.lang(30201).encode('utf-8')
                k = control.keyboard('', t) ; k.doModal()
                self.query = k.getText() if k.isConfirmed() else None
            else:
                self.query = query

            if (self.query == None or self.query == ''): return


            url = self.search_link % (urllib.quote_plus(self.query))
            self.list = cache.get(self.trakt_list, 0, url, self.trakt_user)

            self.worker()
            self.movieDirectory(self.list)
            return self.list
        #except:
        #    return 
Example 11
Project: Pancas   Author: Sup3Roque   File: movies.py    GNU General Public License v2.0 6 votes vote down vote up
def person(self, query=None):
        try:
            if query == None:
                t = control.lang(30201).encode('utf-8')
                k = control.keyboard('', t) ; k.doModal()
                self.query = k.getText() if k.isConfirmed() else None
            else:
                self.query = query

            if (self.query == None or self.query == ''): return

            url = self.persons_link % urllib.quote_plus(self.query)
            self.list = cache.get(self.imdb_person_list, 0, url)

            for i in range(0, len(self.list)): self.list[i].update({'action': 'movies'})
            self.addDirectory(self.list)
            return self.list
        except:
            return 
Example 12
Project: Pancas   Author: Sup3Roque   File: tvshows.py    GNU General Public License v2.0 6 votes vote down vote up
def search(self, query=None):
        try:
            if query == None:
                t = control.lang(30231).encode('utf-8')
                k = control.keyboard('', t) ; k.doModal()
                self.query = k.getText() if k.isConfirmed() else None
            else:
                self.query = query

            if (self.query == None or self.query == ''): return

            url = self.search_link % urllib.quote_plus(self.query)
            self.list = cache.get(self.trakt_list, 0, url)

            self.worker()
            self.tvshowDirectory(self.list)
            return self.list
        except:
            return 
Example 13
Project: Pancas   Author: Sup3Roque   File: tvshows.py    GNU General Public License v2.0 6 votes vote down vote up
def person(self, query=None):
        try:
            if query == None:
                t = control.lang(30231).encode('utf-8')
                k = control.keyboard('', t) ; k.doModal()
                self.query = k.getText() if k.isConfirmed() else None
            else:
                self.query = query

            if (self.query == None or self.query == ''): return

            url = self.persons_link % urllib.quote_plus(self.query)
            self.list = cache.get(self.tmdb_person_list, 0, url)

            for i in range(0, len(self.list)): self.list[i].update({'action': 'tvshows'})
            self.addDirectory(self.list)
            return self.list
        except:
            return 
Example 14
Project: Pancas   Author: Sup3Roque   File: p2pcast.py    GNU General Public License v2.0 6 votes vote down vote up
def resolve(url):
    try:
        referer = urlparse.parse_qs(urlparse.urlparse(url).query)['referer'][0]

        page = urlparse.parse_qs(urlparse.urlparse(url).query)['id'][0]
        page = 'http://p2pcast.tv/stream.php?id=%s&live=0&p2p=0&stretching=uniform' % page

        result = client.request(page, referer=referer)


        try:
            swf = re.compile('src\s*=[\'|\"](.+?player.+?\.js)[\'|\"]').findall(result)[0]
            swf = client.request(swf)
            swf = re.compile('flashplayer\s*:\s*[\'|\"](.+?)[\'|\"]').findall(swf)[0]
        except:
            swf = 'http://cdn.p2pcast.tv/jwplayer.flash.swf'


        url = re.compile('url\s*=\s*[\'|\"](.+?)[\'|\"]').findall(result)[0]
        url = base64.b64decode(url)
        url = '%s|User-Agent=%s&Referer=%s' % (url, urllib.quote_plus(client.agent()), urllib.quote_plus(swf))

        return url
    except:
        return 
Example 15
Project: Pancas   Author: Sup3Roque   File: oneclickwatch_mv_tv.py    GNU General Public License v2.0 6 votes vote down vote up
def get_movie(self, imdb, title, year):
        try:
            query = self.search_link % urllib.quote_plus(title +' '+year)
            query = urlparse.urljoin(self.base_link, query)
            result = client2.http_get(query)
            years = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1)]
            result = client.parseDOM(result, 'h2', attrs={'class': 'title'})
            result = [(client.parseDOM(i, 'a', ret='href')[0], client.parseDOM(i, 'a')[0]) for i in result]
            print('R',result)
            result = [i for i in result if cleantitle.movie(title.lower()) in cleantitle.movie(i[1]).lower()]
            print('R',result)
            result = [i for i in result if any(x in i[1] for x in years)]
            print('R',result)
            result2 = [i for i in result if '1080' in i[1]]
            print('R',result)
            result3 = [i for i in result if '720' in i[1].lower()]
            print('R',result)
            if len(result3) > 0: result = result3
            if len(result2) > 0: result = result2
            url = result[0][0]
            return url
        except:
            return 
Example 16
Project: Pancas   Author: Sup3Roque   File: oneclickwatch_mv_tv.py    GNU General Public License v2.0 6 votes vote down vote up
def get_episode(self, url, imdb, tvdb, title, date, season, episode):
        try:
            if url == None: return
            mytitile = url.lower()
            url = '%s S%02dE%02d' % (url, int(season), int(episode))
            url = client.replaceHTMLCodes(url)
            url = url.encode('utf-8')
            url = self.search_link % urllib.quote_plus(url)
            query = urlparse.urljoin(self.base_link, url)
            result = client2.http_get(query)
            result = client.parseDOM(result, 'h2', attrs={'class': 'title'})
            result = [(client.parseDOM(i, 'a', ret='href')[0], client.parseDOM(i, 'a')[0]) for i in result]
            result = [i for i in result if mytitile in i[1].lower()]
            result2 = [i for i in result if '1080' in i[1].lower()]
            result3 = [i for i in result if '720' in i[1].lower()]
            if len(result3) > 0: result = result3
            if len(result2) > 0: result = result2
            url=result[0][0]
            return url
        except:
            return 
Example 17
Project: Pancas   Author: Sup3Roque   File: movieshd_mv.py    GNU General Public License v2.0 6 votes vote down vote up
def get_movie(self, imdb, title, year):
        try:
            query = self.search_link % (urllib.quote_plus(title))
            query = urlparse.urljoin(self.base_link, query)

            result = client.source(query)

            result = client.parseDOM(result, 'ul', attrs = {'class': 'listing-videos.+?'})[0]
            result = client.parseDOM(result, 'li', attrs = {'class': '.+?'})

            title = cleantitle.movie(title)
            years = ['(%s)' % str(year), '(%s)' % str(int(year)+1), '(%s)' % str(int(year)-1)]
            result = [(client.parseDOM(i, 'a', ret='href')[0], client.parseDOM(i, 'a', ret='title')[0]) for i in result]
            result = [i for i in result if title == cleantitle.movie(i[1])]
            result = [i[0] for i in result if any(x in i[1] for x in years)][0]

            try: url = re.compile('//.+?(/.+)').findall(result)[0]
            except: url = result
            url = client.replaceHTMLCodes(url)
            url = url.encode('utf-8')
            return url
        except:
            return 
Example 18
Project: Pancas   Author: Sup3Roque   File: tunemovie_mv_tv.py    GNU General Public License v2.0 6 votes vote down vote up
def get_movie(self, imdb, title, year):
        try:
            query = urlparse.urljoin(self.base_link, self.search_link)
            query = query % urllib.quote_plus(title)

            t = cleantitle.get(title)

            r = client.request(query)

            r = client.parseDOM(r, 'div', attrs = {'id': 'post-\d+'})
            r = [(client.parseDOM(i, 'a', ret='href'), client.parseDOM(i, 'a', ret='title'), re.findall('(\d{4})', i)) for i in r]
            r = [(i[0][0], i[1][0], i[2][0]) for i in r if len(i[0]) > 0 and len(i[1]) > 0 and len(i[2]) > 0]

            r = [i[0] for i in r if t == cleantitle.get(i[1]) and year == i[2]][0]

            url = re.findall('(?://.+?|)(/.+)', r)[0]
            url = client.replaceHTMLCodes(url)
            url = url.encode('utf-8')
            return url
        except:
            return 
Example 19
Project: pyblish-win   Author: pyblish   File: test_urllib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_never_quote(self):
        # Make sure quote() does not quote letters, digits, and "_,.-"
        do_not_quote = '' .join(["ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                                 "abcdefghijklmnopqrstuvwxyz",
                                 "0123456789",
                                 "_.-"])
        result = urllib.quote(do_not_quote)
        self.assertEqual(do_not_quote, result,
                         "using quote(): %s != %s" % (do_not_quote, result))
        result = urllib.quote_plus(do_not_quote)
        self.assertEqual(do_not_quote, result,
                        "using quote_plus(): %s != %s" % (do_not_quote, result)) 
Example 20
Project: pyblish-win   Author: pyblish   File: test_urllib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_safe(self):
        # Test setting 'safe' parameter does what it should do
        quote_by_default = "<>"
        result = urllib.quote(quote_by_default, safe=quote_by_default)
        self.assertEqual(quote_by_default, result,
                         "using quote(): %s != %s" % (quote_by_default, result))
        result = urllib.quote_plus(quote_by_default, safe=quote_by_default)
        self.assertEqual(quote_by_default, result,
                         "using quote_plus(): %s != %s" %
                         (quote_by_default, result)) 
Example 21
Project: pyblish-win   Author: pyblish   File: test_urllib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_default_quoting(self):
        # Make sure all characters that should be quoted are by default sans
        # space (separate test for that).
        should_quote = [chr(num) for num in range(32)] # For 0x00 - 0x1F
        should_quote.append('<>#%"{}|\^[]`')
        should_quote.append(chr(127)) # For 0x7F
        should_quote = ''.join(should_quote)
        for char in should_quote:
            result = urllib.quote(char)
            self.assertEqual(hexescape(char), result,
                             "using quote(): %s should be escaped to %s, not %s" %
                             (char, hexescape(char), result))
            result = urllib.quote_plus(char)
            self.assertEqual(hexescape(char), result,
                             "using quote_plus(): "
                             "%s should be escapes to %s, not %s" %
                             (char, hexescape(char), result))
        del should_quote
        partial_quote = "ab[]cd"
        expected = "ab%5B%5Dcd"
        result = urllib.quote(partial_quote)
        self.assertEqual(expected, result,
                         "using quote(): %s != %s" % (expected, result))
        result = urllib.quote_plus(partial_quote)
        self.assertEqual(expected, result,
                         "using quote_plus(): %s != %s" % (expected, result))
        self.assertRaises(TypeError, urllib.quote, None) 
Example 22
Project: pyblish-win   Author: pyblish   File: test_urllib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_quoting_plus(self):
        self.assertEqual(urllib.quote_plus('alpha+beta gamma'),
                         'alpha%2Bbeta+gamma')
        self.assertEqual(urllib.quote_plus('alpha+beta gamma', '+'),
                         'alpha+beta+gamma') 
Example 23
Project: pyblish-win   Author: pyblish   File: test_urllib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_doseq(self):
        # Test that passing True for 'doseq' parameter works correctly
        given = {'sequence':['1', '2', '3']}
        expect = "sequence=%s" % urllib.quote_plus(str(['1', '2', '3']))
        result = urllib.urlencode(given)
        self.assertEqual(expect, result)
        result = urllib.urlencode(given, True)
        for value in given["sequence"]:
            expect = "sequence=%s" % value
            self.assertIn(expect, result)
        self.assertEqual(result.count('&'), 2,
                         "Expected 2 '&'s, got %s" % result.count('&')) 
Example 24
Project: azure-iot-rest   Author: jongio   File: file-upload.py    MIT License 5 votes vote down vote up
def get_iot_hub_sas_token(uri, key, policy_name, expiry=3600):
    ttl = time() + expiry
    sign_key = "%s\n%d" % ((quote_plus(uri)), int(ttl))
    signature = b64encode(HMAC(b64decode(key), sign_key, sha256).digest())

    rawtoken = {
        'sr' :  uri,
        'sig': signature,
        'se' : str(int(ttl))
    }

    if policy_name is not None:
        rawtoken['skn'] = policy_name

    return 'SharedAccessSignature ' + urlencode(rawtoken) 
Example 25
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get(self, subpath, inner=None):
        userId = self.get_current_user()
        if Options['debug'] and not self.get_argument('reload', ''):
            print >> sys.stderr, 'DEBUG: ActionHandler.get', userId, Options['site_number'], subpath
        if subpath == '_logout':
            self.clear_user_cookie()
            self.render('logout.html')
            return
        root = str(self.get_argument("root", ""))
        token = str(self.get_argument("token", ""))
        if not self.check_admin_access(token=token, root=root):
            if self.previewActive() and subpath.startswith('_preview/') and not self.get_user_cookie():
                next_url = '/' + subpath
                if Options['site_name']:
                    next_url = '/'+Options['site_name']+next_url
                self.redirect(Global.login_url+'?next='+urllib.quote_plus(next_url))
                return
            raise tornado.web.HTTPError(403, log_message='CUSTOM:<a href="/">Login</a> as admin to proceed %s' % self.previewActive())
        try:
            return self.getAction(subpath)
        except Exception, excp:
            msg = str(excp)
            if msg.startswith('CUSTOM:') and not Options['debug']:
                print >> sys.stderr, 'sdserver: '+msg
                self.custom_error(500, '<html><body><h3>%s</h3></body></html>' % msg[len('CUSTOM:'):])
                return
            else:
                raise 
Example 26
Project: flasky   Author: RoseOu   File: test_links.py    MIT License 5 votes vote down vote up
def test_mangle_link():
    """We can muck with the href attribute of the link."""
    def filter_url(attrs, new=False):
        quoted = quote_plus(attrs['href'])
        attrs['href'] = 'http://bouncer/?u={0!s}'.format(quoted)
        return attrs

    in_(('<a href="http://bouncer/?u=http%3A%2F%2Fexample.com" rel="nofollow">'
         'http://example.com</a>',
         '<a rel="nofollow" href="http://bouncer/?u=http%3A%2F%2Fexample.com">'
         'http://example.com</a>'),
        linkify('http://example.com', DC + [filter_url])) 
Example 27
Project: Splunk_CBER_App   Author: MHaggis   File: binding.py    MIT License 5 votes vote down vote up
def __new__(self, val='', skip_encode=False, encode_slash=False):
        if isinstance(val, UrlEncoded):
            # Don't urllib.quote something already URL encoded.
            return val
        elif skip_encode:
            return str.__new__(self, val)
        elif encode_slash:
            return str.__new__(self, urllib.quote_plus(val))
        else:
            # When subclassing str, just call str's __new__ method
            # with your class and the value you want to have in the
            # new string.
            return str.__new__(self, urllib.quote(val)) 
Example 28
Project: plugin.program.steam.streaming   Author: Drakulix   File: utils.py    MIT License 5 votes vote down vote up
def addClient(hostname, username, authenticated=True):
    if authenticated:
        addDir(username + " @ " + hostname, sys.argv[0]+"?mode=games&hostname="+urllib.quote_plus(hostname)+"&username="+urllib.quote_plus(username), os.path.join(MEDIA_PATH, "pc.png"), os.path.join(MEDIA_PATH, "background.jpg"))
    else:
        addDir(username + " @ " + hostname, sys.argv[0]+"?mode=noauth&hostname="+urllib.quote_plus(hostname)+"&username="+urllib.quote_plus(username), os.path.join(MEDIA_PATH, "pc.png"), os.path.join(MEDIA_PATH, "background.jpg"))

#add game entry 
Example 29
Project: plugin.program.steam.streaming   Author: Drakulix   File: utils.py    MIT License 5 votes vote down vote up
def addAchievement(name, desc, unlocked, hostname, username, thump, fanart):
    if unlocked:
        addDir(name, sys.argv[0]+"?mode=games&hostname="+urllib.quote_plus(hostname)+"&username="+urllib.quote_plus(username), thump, fanart, desc=desc)
    else:
        addDir(name, sys.argv[0]+"?mode=games&hostname="+urllib.quote_plus(hostname)+"&username="+urllib.quote_plus(username), thump, fanart, "22FFFFFF", desc=desc)

#add movie entry
#utils.addMovie(movie["name"], movie["thumbnail"], movie["webm"]["max"]) 
Example 30
Project: EDMC-Canonn   Author: canonn-science   File: whitelist.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self,cmdr, is_beta, system, station, entry, state,x,y,z,body,lat,lon,client):
        threading.Thread.__init__(self)
        self.cmdr=quote_plus(cmdr.encode('utf8'))
        self.system=quote_plus(system.encode('utf8'))
        self.is_beta=is_beta
        self.station=station
        self.body=body
        self.entry=entry
        self.state=state
        self.x=x
        self.y=y
        self.z=z
        self.lat=lat
        self.lon=lon
        self.client=client 
Example 31
Project: EDMC-Canonn   Author: canonn-science   File: whitelist.py    GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        
        url="https://us-central1-canonn-api-236217.cloudfunctions.net/submitRaw?"
        url=url+"&cmdrName={}".format(self.cmdr)
        url=url+"&systemName={}".format(self.system)
        url=url+"&bodyName={}".format(self.body)
        url=url+"&station={}".format(self.station)
        url=url+"&event={}".format(self.entry.get("event"))
        url=url+"&x={}".format(self.x)
        url=url+"&y={}".format(self.y)        
        url=url+"&z={}".format(self.z)        
        url=url+"&lat={}".format(self.lat)        
        url=url+"&lon={}".format(self.lon)        
        url=url+"&is_beta={}".format(self.is_beta)        
        url=url+"&raw_event={}".format(quote_plus(json.dumps(self.entry, ensure_ascii=False).encode('utf8')))
        url=url+"&clientVersion={}".format(self.client)
        
        r=requests.get(url)
            
        if not r.status_code == requests.codes.ok:
            error("whiteListSetter {} ".format(url))
            error(r.status_code)
            error(r.json())
            results=[]
        else:
           results=r.json() 
Example 32
Project: EDMC-Canonn   Author: canonn-science   File: factionkill.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self,cmdr, is_beta, system, reward,victimFaction):
        threading.Thread.__init__(self)
        self.cmdr=quote_plus(cmdr.encode('utf8'))
        self.system=quote_plus(system.encode('utf8'))
        if is_beta:
            self.is_beta = 'Y'
        else:
            self.is_beta = 'N'    
        self.reward=str(reward)
        self.victimFaction=quote_plus(victimFaction.encode('utf8')) 
Example 33
Project: EDMC-Canonn   Author: canonn-science   File: nhss.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self,cmdr,system,x,y,z,threat_level):
        threading.Thread.__init__(self)
        self.cmdr=quote_plus(cmdr.encode('utf8'))
        self.system=quote_plus(system.encode('utf8'))
        self.x=x
        self.y=y
        self.z=z
        self.threat_level=threat_level 
Example 34
Project: EDMC-Canonn   Author: canonn-science   File: hdreport.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, cmdr, x, y, z, entry):
        threading.Thread.__init__(self)
        self.cmdr = quote_plus(cmdr.encode('utf8'))
        self.system = quote_plus(entry.get("TG_ENCOUNTERS").get("TG_ENCOUNTER_TOTAL_LAST_SYSTEM").encode('utf8'))
        self.x = x
        self.y = y
        self.z = z
        ts = entry.get("TG_ENCOUNTERS").get("TG_ENCOUNTER_TOTAL_LAST_TIMESTAMP")
        year = int(ts[0:4]) - 1286
        self.eddatetime = "{}-{}:00".format(year, ts[4:])
        debug(self.eddatetime)

        self.entry = entry 
Example 35
Project: spotify-lyrics-cli   Author: kenogo   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def get_lyrics_genius(artist, title, nocheck=False):
    title = re.sub(r"\(.*\)|\[.*\]", '', title) # (feat.) [extended cut]
    title = re.sub(r"-.*", '', title) # - Remastered ...
    # Google for Lyrics
    search_name = "%s %s genius lyrics" % (artist, title)
    name = quote_plus(search_name)
    url = 'http://www.google.com/search?q=' + name
    result = requests.get(url).text
    link_start = result.find('https://genius.com')
    if(link_start == -1):
        return "Lyrics could not be found..."
    link_end = result.find('"', link_start + 1)
    link = result[link_start:link_end].lower()
    link = re.sub(r"&.*", '', link) # Remove PHP nonesense
    link_correct = check_link_genius(artist, title, link)
    if not link_correct and not nocheck:
        return "Lyrics could not be found... You can try running with --nocheck"

    # Get the lyrics from genius
    lyrics_html = requests.get(link).text
    soup = BeautifulSoup(lyrics_html, "lxml")
    raw_lyrics = str(soup.findAll('div', attrs={'class': 'lyrics'}))
    lyrics = raw_lyrics[1:len(raw_lyrics)-1]
    lyrics = re.sub(r"<[^<>]*>", '', lyrics) # Remove HTML tags
    if sys.version_info < (3, 0):
        lyrics = re.sub(r"\\n", '\n', lyrics)
    lyrics = lyrics[2:] # Remove two newlines
    return lyrics 
Example 36
Project: AshsSDK   Author: thehappydinoa   File: math2html.py    MIT License 5 votes vote down vote up
def googlecharts(self):
    "Make the contents using Google Charts http://code.google.com/apis/chart/."
    url = FormulaConfig.urls['googlecharts'] + urllib.quote_plus(self.parsed)
    img = '<img class="chart" src="' + url + '" alt="' + self.parsed + '"/>'
    self.contents = [Constant(img)] 
Example 37
Project: tang300   Author: 0ssifrage   File: weibotang300.py    MIT License 5 votes vote down vote up
def main():
    client = APIClient(
        app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=C_URL)
    client.set_access_token(ACCESS_TOKEN, EXPIRES_IN)
    base_dir = os.path.split(os.path.realpath(__file__))[0]

    f = open(os.path.join(base_dir, 'tang300.v4.json'), 'r')
    ps = json.load(f)
    f.close()
    try:
        logfilename = os.path.join(base_dir, 'log.txt')
        logfile = open(logfilename, 'r')
        idx = int(logfile.read())
        logfile.close()
    except:
        idx = 0

    p = ps[idx]
    q = urllib.quote_plus(p[1].encode('utf8'))
    s = u'《%s》%s %s https://www.google.com.hk/#q=%s' % (p[1], p[2], p[0], q)
    s = urllib.quote_plus(s.encode('utf8'))
    img = os.path.join(base_dir, 'poem_png/%03d.png' % idx)
    client.statuses.upload.post(
        status=s, pic=open(img, 'rb'))

    idx = (idx+1) % len(ps)
    logfile = open(logfilename, 'w')
    logfile.write(str(idx))
    logfile.close() 
Example 38
Project: repository.BludhavenGrayson   Author: BludhavenGrayson   File: default.py    GNU General Public License v2.0 5 votes vote down vote up
def addLink(name,url,mode,iconimage):
		u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
		ok=True
		liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
		liz.setInfo( type="Video", infoLabels={ "Title": name} )
		liz.setProperty('fanart_image', fanart)
		liz.setProperty("IsPlayable","true")
		ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
		return ok 
Example 39
Project: repository.BludhavenGrayson   Author: BludhavenGrayson   File: default.py    GNU General Public License v2.0 5 votes vote down vote up
def addDir(name,url,mode,iconimage):
		u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
		ok=True
		liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
		liz.setInfo( type="Video", infoLabels={ "Title": name} )
		liz.setProperty('fanart_image', fanart)
		ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
		return ok 
Example 40
Project: repository.BludhavenGrayson   Author: BludhavenGrayson   File: default.py    GNU General Public License v2.0 5 votes vote down vote up
def addLink(name,url,mode,iconimage):
		u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
		ok=True
		liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
		liz.setInfo( type="Video", infoLabels={ "Title": name} )
		liz.setProperty('fanart_image', fanart)
		liz.setProperty("IsPlayable","true")
		ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
		return ok 
Example 41
Project: repository.BludhavenGrayson   Author: BludhavenGrayson   File: plugintools.py    GNU General Public License v2.0 5 votes vote down vote up
def add_item( action="" , title="" , plot="" , url="" , thumbnail="" , fanart="" , isPlayable=True , folder=False ):
    _log("add_item action=["+action+"] title=["+title+"] url=["+url+"] fanart=["+fanart+"] thumbnail=["+thumbnail+"] isPlayable=["+str(isPlayable)+"] folder=["+str(folder)+"]")

    listitem = xbmcgui.ListItem( title.replace("&amp;","&"), iconImage="DefaultVideo.png", thumbnailImage=thumbnail )
    listitem.setInfo( "video", { "Title" : title, "FileName" : title, "Plot" : plot } )
    listitem.setProperty('fanart_image', fanart)
    
    if url.startswith("http://"):
        itemurl = url
        listitem.setProperty('IsPlayable', 'true')
        xbmcplugin.addDirectoryItem( handle=int(sys.argv[1]), url=itemurl, listitem=listitem)
    else:
        itemurl = '%s?action=%s&title=%s&url=%s&thumbnail=%s&plot=%s' % ( sys.argv[ 0 ] , action , urllib.quote_plus( title ) , urllib.quote_plus(url) , urllib.quote_plus( thumbnail ) , urllib.quote_plus( plot ))
        xbmcplugin.addDirectoryItem( handle=int(sys.argv[1]), url=itemurl, listitem=listitem, isFolder=folder) 
Example 42
Project: repository.BludhavenGrayson   Author: BludhavenGrayson   File: common.py    GNU General Public License v2.0 5 votes vote down vote up
def addLink(name,url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setProperty('fanart_image', iconimage)
        liz.setProperty("IsPlayable","true")
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
        return ok 
Example 43
Project: repository.BludhavenGrayson   Author: BludhavenGrayson   File: common.py    GNU General Public License v2.0 5 votes vote down vote up
def addVOD(name,url,mode,iconimage,plot):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setInfo( "video", { "Title" : name, "Plot" : plot } )
        liz.setProperty('fanart_image', fanart)
        liz.setProperty("IsPlayable","true")
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
        return ok 
Example 44
Project: repository.BludhavenGrayson   Author: BludhavenGrayson   File: default.py    GNU General Public License v2.0 5 votes vote down vote up
def addLink(name,url,mode,iconimage):
		u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
		ok=True
		liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
		liz.setInfo( type="Video", infoLabels={ "Title": name} )
		liz.setProperty('fanart_image', fanart)
		liz.setProperty("IsPlayable","true")
		ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
		return ok 
Example 45
Project: repository.BludhavenGrayson   Author: BludhavenGrayson   File: default.py    GNU General Public License v2.0 5 votes vote down vote up
def addDir(name,url,mode,iconimage):
		u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
		ok=True
		liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
		liz.setInfo( type="Video", infoLabels={ "Title": name} )
		liz.setProperty('fanart_image', fanart)
		ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
		return ok 
Example 46
Project: repository.BludhavenGrayson   Author: BludhavenGrayson   File: default.py    GNU General Public License v2.0 5 votes vote down vote up
def addLink(name,url,mode,iconimage):
		u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
		ok=True
		liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
		liz.setProperty('fanart_image', iconimage)
		liz.setProperty("IsPlayable","true")
		ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
		return ok 
Example 47
Project: repository.BludhavenGrayson   Author: BludhavenGrayson   File: default.py    GNU General Public License v2.0 5 votes vote down vote up
def addLink(name,url,mode,iconimage):
		u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
		ok=True
		liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
		liz.setInfo( type="Video", infoLabels={ "Title": name} )
		liz.setProperty('fanart_image', fanart)
		liz.setProperty("IsPlayable","true")
		ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
		return ok 
Example 48
Project: repository.BludhavenGrayson   Author: BludhavenGrayson   File: common.py    GNU General Public License v2.0 5 votes vote down vote up
def addLink(name,url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setProperty('fanart_image', iconimage)
        liz.setProperty("IsPlayable","true")
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
        return ok 
Example 49
Project: repository.BludhavenGrayson   Author: BludhavenGrayson   File: common.py    GNU General Public License v2.0 5 votes vote down vote up
def addDir(name,url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setProperty('fanart_image', iconimage)
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok 
Example 50
Project: hdxscraper-world-bank-climate   Author: nerevu   File: utils.py    MIT License 5 votes vote down vote up
def fetch(**kwargs):
    """Fetches realtime data and generates records"""
    sub_query = kwargs['SUB_QUERY']
    sub_query['CCode'] = kwargs['code']
    sub_query['thisVariable'] = kwargs['metric']
    sub_string = ','.join('"%s":"%s"' % (k, v) for k, v in sub_query.items())
    sub_quote = '{%s}' % quote_plus(sub_string)
    query = urlencode(kwargs['BASE_QUERY'])
    url = '%s?%s&argumentCollection=%s' % (kwargs['BASE_URL'], query, sub_quote)
    r = requests.get(url)
    return {'records': r.json()}