Пример #1
0
    '''
    Returns last dumped match ID from DUMP_DIR
    '''
    matches = [m for m in os.listdir(dump_dir) if m.endswith('.json')]

    if len(matches) == 0:
        return None

    return max([int(m.split('.')[0]) for m in matches])

# Minimal log setting
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# LOL api wrapper
wrapper = RiotWatcher(key=config.API_KEY, default_region=BRAZIL)

# First match to be dumped
starting_match_id = last_match(config.DUMP_DIR) or config.STARTING_MATCH_ID

n = 10000  # total n matches to dump
counter = 0  # total matches dumped
i = 0  # matches iterator

while counter < n:
    try:
        # Next match to dump
        match_id = starting_match_id + i

        filename = '%s%d%s' % (config.DUMP_DIR, match_id, ".json")
Пример #2
0
import os
import time

from django.db import IntegrityError
from riotwatcher.riotwatcher import RiotWatcher, NORTH_AMERICA

# from lol_stats2.settings.development import get_env_variable
from utils.functions import chunks
from summoners.models import Summoner

MAX_IDS_PER_QUERY = 40
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

rw = RiotWatcher(os.environ['RIOT_API_KEY'])

with open(os.path.join(BASE_DIR, 'seed/summonerIds5.txt'), 'r') as f:
    summoner_ids = f.readlines()

summoner_ids = [int(id.strip('\n')) for id in summoner_ids]
print("Summoner IDs to query: {}".format(summoner_ids))
chunked_ids = list(chunks(summoner_ids, MAX_IDS_PER_QUERY))

for chunk in chunked_ids:
    while not rw.can_make_request():
        time.sleep(1)
        print(".", end="", flush=True)

    summoners = rw.get_summoners(ids=chunk, region=NORTH_AMERICA)

    for k in summoners:
        try:
Пример #3
0
from django.shortcuts import render_to_response
from django.template import RequestContext
from collections import OrderedDict
from riotwatcher.riotwatcher import RiotWatcher, LoLException, error_404
from LOLHub.models import *
from django import template
from django.http import HttpResponse
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
import time
import requests

# Constantes
w = RiotWatcher(key=settings.RIOT_API_KEY, default_region='lan')


# Create your views here.
def Index(request):
    return render_to_response('Index.html',
                              context_instance=RequestContext(request))


def StatsCard(request, sname=''):
    if sname != '':
        me = w.get_summoner(name=sname)
        lEntry = None
        try:
            lEntry = w.get_league_entry(summoner_ids=(me['id'], ))
            if (lEntry[str(me['id'])][0]['queue'] != 'RANKED_SOLO_5x5'):
Пример #4
0
from flask import Flask
from flask import render_template
from riotwatcher.riotwatcher import RiotWatcher

app = Flask(__name__)

riot_api = None
items = None
dd_urls = {}

@app.route('/items')
def items():
    return render_template('items.html', items=items['data'], dd_url=dd_urls['na'])

@app.route('/userinfo/<username>')
def user_info(username):
    game = riot_api.get_current_game(riot_api.get_summoner(name=username)['id'])
    return render_template('items.html', participants=game['participants'])

if __name__ == '__main__':
    app.debug = True
    app.config.from_pyfile('dev.cfg')
    riot_api = RiotWatcher(app.config['API_KEY'])
    items = riot_api.static_get_item_list()

    for region in ['br', 'eune', 'euw', 'kr', 'lan', 'las', 'na', 'oce', 'ru', 'tr']:
        data = riot_api.static_get_realm(region)
        dd_urls[region] = data['cdn'] + '/' + data['v']
    app.run()
Пример #5
0
'''
Script to find a match at a specific date time by using gradient descendent.

Adaptaded from Lucas Coppio:
https://gist.github.com/Scoppio/2d5cf12311239ca9807f643ef21b88d1
'''
import math
import time
import random
from datetime import datetime
from riotwatcher.riotwatcher import RiotWatcher, BRAZIL
import config

riot_client = RiotWatcher(key=config.API_KEY, default_region=BRAZIL)


def sign(x):
    ''' Get a sign of a given number x '''
    return math.copysign(1, x)


def timestamp_to_datetime(t):
    ''' Convert a timestamp (seconds) to datetime format '''
    return datetime.fromtimestamp(t)


def timestamp(*args, **kwargs):
    ''' Convert a datetime to timestamp (seconds) '''
    return time.mktime(datetime(*args, **kwargs).timetuple())

Пример #6
0
logger = logging.getLogger(__name__)

# Set the default Django settings module
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lol_stats2.settings.base')

app = Celery('lol_stats2',
             broker='amqp://',
             backend='redis://'
             )

# Using a string here means the worker will not have to pickle the object
# when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

riot_watcher = RiotWatcher(RIOT_API_KEY)

# TODO: Move tasks into separate modules.
# TODO: Create separate task for static API calls (not counted against rate limit).

@app.task(bind=True, ignore_result=False, rate_limit='.7/s', max_retries=3,
          default_retry_delay=RIOT_API_RETRY_DELAY)
def riot_api(self, kwargs):
    """
    A rate-limited task that queries the Riot API using a RiotWatcher instance.

    Celery accepts a single rate limit for a task, but Riot expresses
    limits in 2 forms (neither of which can be exceeded):
    10 req / 10 sec
    500 req / 10 min
Пример #7
0
def create_riot_client(api_key):
    return RiotWatcher(key=api_key, default_region=BRAZIL)
Пример #8
0
    Returns last dumped match ID from DUMP_DIR
    '''
    matches = [m for m in os.listdir(dump_dir) if m.endswith('.json')]

    if len(matches) == 0:
        return None

    return max([int(m.split('.')[0]) for m in matches])


# Minimal log setting
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# LOL api wrapper
wrapper = RiotWatcher(key=config.API_KEY, default_region=BRAZIL)

# First match to be dumped
starting_match_id = last_match(config.DUMP_DIR) or config.STARTING_MATCH_ID

n = 10000  # total n matches to dump
counter = 0  # total matches dumped
i = 0  # matches iterator

while counter < n:
    try:
        # Next match to dump
        match_id = starting_match_id + i

        filename = '%s%d%s' % (config.DUMP_DIR, match_id, ".json")