当前位置: 首页>>代码示例>>Python>>正文


Python http.get_json函数代码示例

本文整理汇总了Python中util.http.get_json函数的典型用法代码示例。如果您正苦于以下问题:Python get_json函数的具体用法?Python get_json怎么用?Python get_json使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了get_json函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: youtime

def youtime(inp):
    """youtime <query> -- Gets the total run time of the first YouTube search result for <query>."""
    request = http.get_json(search_api_url, q=inp)

    if 'error' in request:
        return 'error performing search'

    if request['data']['totalItems'] == 0:
        return 'no results found'

    video_id = request['data']['items'][0]['id']
    request = http.get_json(api_url.format(video_id))

    if request.get('error'):
        return
    data = request['data']

    if not data.get('duration'):
        return

    length = data['duration']
    views = data['viewCount']
    total = int(length * views)

    length_text = timeformat.format_time(length, simple=True)
    total_text = timeformat.format_time(total, accuracy=8)

    return 'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for ' \
           'a total run time of {}!'.format(data['title'], length_text, views,
                                            total_text)
开发者ID:FurCode,项目名称:RoboCop2,代码行数:30,代码来源:youtube.py

示例2: rottentomatoes

def rottentomatoes(inp, bot=None):
    '.rt <title> -- gets ratings for <title> from Rotten Tomatoes'

    api_key = bot.config.get("api_keys", {}).get("rottentomatoes", None)
    if not api_key:
        return None

    title = inp.strip()

    results = http.get_json(movie_search_url % (http.quote_plus(title), api_key))
    if results['total'] > 0:
        movie = results['movies'][0]
        title = movie['title']
        id = movie['id']
        critics_score = movie['ratings']['critics_score']
        audience_score = movie['ratings']['audience_score']
        url = movie['links']['alternate']

        if critics_score != -1:
            reviews = http.get_json(movie_reviews_url%(id, api_key))
            review_count = reviews['total']

            fresh = critics_score * review_count / 100
            rotten = review_count - fresh

            return response % (title, critics_score, fresh, rotten, audience_score, url)
开发者ID:Ashtheking,项目名称:APCSBot,代码行数:26,代码来源:rottentomatoes.py

示例3: rottentomatoes

def rottentomatoes(inp, bot=None):
    ".rt <title> -- gets ratings for <title> from Rotten Tomatoes"

    api_key = bot.config.get("api_keys", {}).get("rottentomatoes", None)
    if not api_key:
        return "error: no api key set"

    results = http.get_json(movie_search_url, q=inp, apikey=api_key)
    if results["total"] == 0:
        return "no results"

    movie = results["movies"][0]
    title = movie["title"]
    id = movie["id"]
    critics_score = movie["ratings"]["critics_score"]
    audience_score = movie["ratings"]["audience_score"]
    url = movie["links"]["alternate"]

    if critics_score == -1:
        return

    reviews = http.get_json(movie_reviews_url % id, apikey=api_key, review_type="all")
    review_count = reviews["total"]

    fresh = critics_score * review_count / 100
    rotten = review_count - fresh

    return u"%s - critics: \x02%d%%\x02 (%d\u2191/%d\u2193) audience: \x02%d%%\x02 - %s" % (
        title,
        critics_score,
        fresh,
        rotten,
        audience_score,
        url,
    )
开发者ID:redi-code,项目名称:sexibot,代码行数:35,代码来源:media.py

示例4: rt

def rt(inp, api_key=None):
    """.rt <title> - Gets ratings for <title> from Rotten Tomatoes."""

    results = http.get_json(movie_search_url, q=inp, apikey=api_key)
    if results['total'] == 0:
        return 'No results.'

    movie = results['movies'][0]
    title = movie['title']
    id = movie['id']
    critics_score = movie['ratings']['critics_score']
    audience_score = movie['ratings']['audience_score']
    url = movie['links']['alternate']

    if critics_score == -1:
        return

    reviews = http.get_json(movie_reviews_url %
                            id, apikey=api_key, review_type='all')
    review_count = reviews['total']

    fresh = critics_score * review_count / 100
    rotten = review_count - fresh

    return u"%s - critics: \x02%s%%\x02 (%s\u2191%s\u2193)" \
        " audience: \x02%s%%\x02 - %s" % (title.strip(), str(critics_score).strip(), str(fresh)
                                          .strip(), str(rotten).strip(), str(audience_score).strip(' '), url.strip(' '))
开发者ID:Cameri,项目名称:Gary,代码行数:27,代码来源:rottentomatoes.py

示例5: rottentomatoes

def rottentomatoes(inp, bot=None):
    """rt <title> -- gets ratings for <title> from Rotten Tomatoes"""

    api_key = bot.config.get("api_keys", {}).get("rottentomatoes", None)
    if not api_key:
        return "error: no api key set"

    title = inp.strip()

    results = http.get_json(movie_search_url, q=title, apikey=api_key)
    if results['total'] == 0:
        return 'No results.'

    movie = results['movies'][0]
    title = movie['title']
    movie_id = movie['id']
    critics_score = movie['ratings']['critics_score']
    audience_score = movie['ratings']['audience_score']
    url = movie['links']['alternate']

    if critics_score == -1:
        return

    reviews = http.get_json(movie_reviews_url % movie_id, apikey=api_key, review_type='all')
    review_count = reviews['total']

    fresh = critics_score * review_count / 100
    rotten = review_count - fresh

    return "{} - Critics Rating: \x02{}%\x02 ({} liked, {} disliked) " \
           "Audience Rating: \x02{}%\x02 - {}".format(title, critics_score, fresh, rotten, audience_score, url)
开发者ID:FurCode,项目名称:RoboCop2,代码行数:31,代码来源:rottentomatoes.py

示例6: frink

def frink(inp):
    ".frink <query> -- searches Frinkiac for Simpsons quotes"

    steamed_hams = http.get_json(frinkiac_search_url, q=inp)

    if not steamed_hams:
        return "no cromulent quotes found"
    
    if(len(steamed_hams) > 10):
        steamed_hams = steamed_hams[:10]

    SKIIIINNER = random.choice(steamed_hams)
    episode = SKIIIINNER['Episode']
    timestamp = SKIIIINNER['Timestamp']
    
    aurora_borealis = http.get_json(frinkiac_caption_url, e=episode, t=timestamp)
    
    leader_beans = []
    
    for skinner_excuse in aurora_borealis['Subtitles']:
        leader_beans.append(skinner_excuse['Content'])
    
    ah_superintendent_chalmers = string.join(leader_beans)
    if len(ah_superintendent_chalmers) > 250:
        ah_superintendent_chalmers = ah_superintendent_chalmers[:250] + "..."
    what_a_pleasant_surprise = frinkiac_url + 'caption/%s/%s' % (episode, timestamp)

    return "\"%s\" %s" % (ah_superintendent_chalmers, what_a_pleasant_surprise)
开发者ID:erodad,项目名称:skybot-plugins,代码行数:28,代码来源:frinkiac.py

示例7: rottentomatoes

def rottentomatoes(inp,bot=None):
    '.rt <title> -- gets ratings for <title> from Rotten Tomatoes'

    api_key = bot.config.get("api_keys", {}).get("rottentomatoes", None)
    if not api_key:
        return "error: no api key set"

    results = http.get_json(movie_search_url, q=inp, apikey=api_key)
    if results['total'] == 0:
        return 'no results'

    movie = results['movies'][0]
    title = movie['title']
    id = movie['id']
    critics_score = movie['ratings']['critics_score']
    audience_score = movie['ratings']['audience_score']
    url = movie['links']['alternate']

    if critics_score == -1:
        return

    reviews = http.get_json(movie_reviews_url % id, apikey=api_key, review_type='all')
    review_count = reviews['total']

    fresh = critics_score * review_count / 100
    rotten = review_count - fresh

    return u"%s - critics: \x02%d%%\x02 (%d\u2191/%d\u2193) audience: \x02%d%%\x02 - %s" % (title, critics_score, fresh, rotten, audience_score, url)
开发者ID:inexist3nce,项目名称:Taigabot,代码行数:28,代码来源:media.py

示例8: youtime

def youtime(inp, bot=None):
    """youtime <query> -- Gets the total run time of the first YouTube search result for <query>."""
    key = bot.config.get("api_keys", {}).get("youtube")
    request = http.get_json(search_api_url, key=key, q=inp, type='video')

    if 'error' in request:
        return 'Error performing search.'

    if request['pageInfo']['totalResults'] == 0:
        return 'No results found.'

    video_id = request['items'][0]['id']['videoId']

    request = http.get_json(api_url, key=key, id=video_id)

    data = request['items'][0]

    length = data['contentDetails']['duration']
    timelist = length[2:-1].split('M')
    seconds = 60*int(timelist[0]) + int(timelist[1])

    views = int(data['statistics']['viewCount'])
    total = int(seconds * views)

    length_text = timeformat.format_time(seconds, simple=True)
    total_text = timeformat.format_time(total, accuracy=8)

    return u'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for ' \
            'a total run time of {}!'.format(data['snippet']['title'], length_text, views, total_text)
开发者ID:Boltovnya,项目名称:uguubot,代码行数:29,代码来源:youtube.py

示例9: imdb

def imdb(text):
    """imdb <movie> -- Gets information about <movie> from IMDb."""

    strip = text.strip()

    if id_re.match(strip):
        content = http.get_json("http://www.omdbapi.com/", i=strip)
    else:
        content = http.get_json("http://www.omdbapi.com/", t=strip)

    if content.get('Error', None) == 'Movie not found!':
        return 'Movie not found!'
    elif content['Response'] == 'True':
        content['URL'] = 'http://www.imdb.com/title/{}'.format(content['imdbID'])

        out = '\x02%(Title)s\x02 (%(Year)s) (%(Genre)s): %(Plot)s'
        if content['Runtime'] != 'N/A':
            out += ' \x02%(Runtime)s\x02.'
        if content['imdbRating'] != 'N/A' and content['imdbVotes'] != 'N/A':
            out += ' \x02%(imdbRating)s/10\x02 with \x02%(imdbVotes)s\x02' \
                   ' votes.'
        out += ' %(URL)s'
        return out % content
    else:
        return 'Unknown error.'
开发者ID:FurCode,项目名称:RoboCop2,代码行数:25,代码来源:imdb.py

示例10: urban

def urban(text):
    """urban <phrase> [id] -- Looks up <phrase> on urbandictionary.com."""

    if text:
        # clean and split the input
        text = text.lower().strip()
        parts = text.split()

        # if the last word is a number, set the ID to that number
        if parts[-1].isdigit():
            id_num = int(parts[-1])
            # remove the ID from the input string
            del parts[-1]
            text = " ".join(parts)
        else:
            id_num = 1

        # fetch the definitions
        page = http.get_json(define_url, term=text, referer="http://m.urbandictionary.com")

        if page['result_type'] == 'no_results':
            return 'Not found.'
    else:
        # get a random definition!
        page = http.get_json(random_url, referer="http://m.urbandictionary.com")
        id_num = None

    definitions = page['list']

    if id_num:
        # try getting the requested definition
        try:
            definition = definitions[id_num - 1]

            def_text = " ".join(definition['definition'].split())  # remove excess spaces
            def_text = formatting.truncate_str(def_text, 200)
        except IndexError:
            return 'Not found.'

        url = definition['permalink']

        output = "[{}/{}] {} :: {}".format(id_num, len(definitions), def_text, url)

    else:
        definition = random.choice(definitions)

        def_text = " ".join(definition['definition'].split())  # remove excess spaces
        def_text = formatting.truncate_str(def_text, 200)

        name = definition['word']
        url = definition['permalink']
        output = "\x02{}\x02: {} :: {}".format(name, def_text, url)

    return output
开发者ID:FurCode,项目名称:RoboCop2,代码行数:54,代码来源:urban.py

示例11: stock

def stock(inp):
    '''.stock <symbol> [info] -- retrieves a weeks worth of stats for given symbol. Optionally displays information about the company.'''

    arguments = inp.split(' ')

    symbol = arguments[0].upper()

    try:
        fundamentals = http.get_json(
            'https://api.robinhood.com/fundamentals/{}/'.format(symbol))
        quote = http.get_json(
            'https://api.robinhood.com/quotes/{}/'.format(symbol))
    except http.HTTPError:
        return '{} is not a valid stock symbol.'.format(symbol)

    if fundamentals['open'] is None or quote['ask_price'] is None:
        return 'unknown ticker symbol %s' % inp

    if len(arguments) > 1 and arguments[1] == 'info':
        return fundamentals['description']

    # Manually "calculate" change since API does not provide it
    price = float(quote['last_trade_price'])
    change = price - float(quote['adjusted_previous_close'])

    # Extract name as Upper Case Corp Name from description.
    name = ''
    m = re.match(r'^([A-Z]\S* )*', fundamentals['description'])
    if m:
        name = m.group(0)

    def maybe(name, key, fmt=human_price):
        if fundamentals.get(key):
            return ' | {0}: {1}'.format(name, fmt(float(fundamentals[key])))
        return ''

    response = {
        'name': name,
        'change': change,
        'percent_change': 100 * change / (price - change),
        'symbol': quote['symbol'],
        'price': price,
        'color': '5' if change < 0 else '3',
        'high': float(fundamentals['high']),
        'low': float(fundamentals['low']),
        'average_volume': maybe('Volume', 'average_volume'),
        'market_cap': maybe('MCAP', 'market_cap'),
        'pe_ratio': maybe('P/E', 'pe_ratio', fmt='{:.2f}'.format),
    }

    return ("{name}({symbol}) ${price:,.2f} \x03{color}{change:,.2f} ({percent_change:,.2f}%)\x03 | "
            "Day Range: ${low:,.2f} - ${high:,.2f}"
            "{pe_ratio}{average_volume}{market_cap}").format(**response)
开发者ID:NIGHTCHAOS,项目名称:skybot,代码行数:53,代码来源:stock.py

示例12: hats

def hats(inp, api_key=None):
    """.hats <Steam Vanity URL|Numeric Steam ID> - Shows backpack information for TF2."""

    # Get SteamID
    if inp.isdigit():
        steamid64 = inp
    else:
        try:
            id_url = 'http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=%s&vanityurl=%s' % \
                (api_key, http.quote(inp.encode('utf8'), safe=''))
            steamid64 = http.get_json(id_url)['response']['steamid']
        except:
            return "Error getting numeric Steam ID, please try format '.hats <Numeric Steam ID>'"

    # Get Steam User's TF2 Inventory/Check for User
    try:
        inv_url = 'http://api.steampowered.com/IEconItems_440/GetPlayerItems/v0001/?SteamID=%s&key=%s' % \
            (steamid64, api_key)
        inv = http.get_json(inv_url)
    except:
        return "Sorry, I couldn't find '%s''s Steam inventory." % inp

    # Count Items into Categories
    total, dropped, dhats, dun, un, hats = 0, 0, 0, 0, 0, 0
    for x in inv["result"]["items"]:
        total += 1
        ind = int(x['defindex'])
        if x['origin'] == 0:
            if x['quality'] == 5:
                dun += 1
            if 47 <= ind <= 55 or 94 <= ind <= 126 or 134 <= ind <= 152:
                dhats += 1
            else:
                dropped += 1
        else:
            if x['quality'] == 5:
                un += 1
            if 47 <= ind <= 55 or 94 <= ind <= 126 or 134 <= ind <= 152:
                hats += 1

    # Get Market Price for Backpack
    try:
        backpack_url = 'http://backpack.tf/api/IGetUsers/v3/?steamids=%s' % steamid64
        backpack = http.get_json(backpack_url)
        ref = backpack['response']['players'][steamid64]['backpack_value']['440']
    except:
        ref = '???'

    return '%s has %s items, %s hats, and %s unusuals (%s/%s/%s of the ' \
        'items/hats/unusals were from drops) and has a backpack worth %s ref' %  \
        (inp, total, hats + dhats, un + dun, dropped, dhats, dun, ref)
开发者ID:Cameri,项目名称:Gary,代码行数:51,代码来源:tf2.py

示例13: api_get

def api_get(kind, query):
    """Use the RESTful Google Search API."""
    if kind == 'image':
        url = ('https://www.googleapis.com/customsearch/v1?key={}&cx={}'
               '&searchType={}&num=1&safe=off&q={}')
        return http.get_json(url.format(query[0], query[1], kind, query[2]))
    elif kind == 'images':
        url = ('https://www.googleapis.com/customsearch/v1?key={}&cx={}'
               '&searchType={}&num=1&safe=off&q={}&fileType="{}"')
        return http.get_json(url.format(query[0], query[1], 'image', query[2], query[3]))
    else:
        url = ('https://www.googleapis.com/customsearch/v1?key={}&cx={}'
               '&num=1&safe=off&q={}')
        return http.get_json(url.format(query[0], query[1], query[2].encode('utf-8')))
开发者ID:inexist3nce,项目名称:Taigabot,代码行数:14,代码来源:google.py

示例14: lastfm

def lastfm(inp,nick=None,api_key=None):
    ".lastfm [user1] [user2] -- gets Last.fm information about a single user or compares two users. "\
    "If user1 is blank then the user matching the current nickname will be returned."

    try:
        user1, user2 = inp.split(' ')
        return compare(user1,user2,api_key)
    except ValueError:
        user = inp
    if not inp:
        user = nick

    user_json = http.get_json(api_url, method='user.getinfo', user=user, api_key=api_key)
    try: #check if user exists
        return user_json['message'].replace('that name','the name ' + user)
    except:
        pass

    user_info = user_json['user']
    output = user_info['url'] + ' | ' + user_info['playcount'] + ' plays'
    if user_info['playcount'] != '0': #keyerror with zero plays
        output += ' | Top artists: '
        top_artists = http.get_json(api_url, method='user.gettopartists', user=user, api_key=api_key)['topartists']
        count = int(top_artists['@attr']['total'])
        top_artists = top_artists['artist']
        if count == 0: #arnie is a dick and had only two artists and tracks
            output += 'none'
        elif count > 4:
            count = 3
        print count
        for i in range(0,count):
            output += top_artists[i]['name'] + ' (' + top_artists[i]['playcount'] + ')'
            if i < (count-1):
                output += ', '

        output += ' | Top tracks: '
        top_tracks = http.get_json(api_url, method='user.gettoptracks', user=user, api_key=api_key)['toptracks']
        count = int(top_tracks['@attr']['total'])
        top_tracks = top_tracks['track']
        if count == 0:
            output += 'none'
        elif count > 4:
            count = 3
        print count
        for i in range(0,count):
            output += top_tracks[i]['artist']['name'] + ' - ' + top_tracks[i]['name'] + ' (' + top_tracks[i]['playcount'] + ')'
            if i < (count-1):
                output += ', '

    return output
开发者ID:Ell,项目名称:Siri,代码行数:50,代码来源:lastfm.py

示例15: cube

def cube(inp):
  up = '\x0309up'
  down = '\x0304down'
  status = http.get_json('http://direct.cyberkitsune.net/canibuycubeworld/status.json')
  stats = http.get_json('http://direct.cyberkitsune.net/canibuycubeworld/stats.json')

  siteup = str(round(((float(stats['siteup'])/stats['updatecount'])*100)*100)/100) + '%'
  regup = str(round(((float(stats['regup'])/stats['updatecount'])*100)*100)/100) + '%'
  shopup = str(round(((float(stats['shopup'])/stats['updatecount'])*100)*100)/100) + '%'

  out = 'Picroma is ' + (up if status['site'] else down) + ' \x03(%s)' % siteup
  out += ' | Registration is ' + (up if status['reg'] else down) + ' \x03(%s)' % regup
  out += ' | Shop is ' + (up if status['shop'] else down) + ' \x03(%s)' % shopup
  return out
开发者ID:Alligator,项目名称:homero,代码行数:14,代码来源:cube.py


注:本文中的util.http.get_json函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。