Example #1
0
def run(*args):
    """Add a card to the database from the mtgsdk."""
    if args:
        # import pdb; pdb.set_trace()
        set_str = args[0]
        cur_set = ''
        try:
            cur_set = sourceSet.find(set_str)
        except:
            print('Set id was invalid, please check id')
            return
        set_in_db = False
        all_sets = Set.objects.all()
        selected_set = ''
        for one_set in all_sets:
            if cur_set.name == one_set.name:
                set_in_db = True
                selected_set = one_set
        if set_in_db:
            cards_in_set = selected_set.card_set.all()
            cards_in_set.delete()
            gen_set(set_str, selected_set)
        else:
            new_set = Set(name=cur_set.name,
                          set_id=cur_set.code,
                          slug=slugify(cur_set.code))
            new_set.save()
            gen_set(set_str, new_set)

    else:
        all_cards = Card.objects.all()
        all_cards.delete()
        sets = Set.objects.all()
        if not sets:
            return
        cur_set = sets[0]
        rivals = SourceCard.where(set='rix')
        rivals_cards = rivals.all()
        for card in rivals_cards:
            new_card = Card.objects.create(name=card.name,
                                           colors=card.colors,
                                           cmc=card.cmc,
                                           image=card.image_url,
                                           mana_cost=card.mana_cost,
                                           rarity=card.rarity,
                                           card_type=card.types,
                                           card_subtypes=card.subtypes,
                                           card_text=card.text,
                                           number=card.number
                                           )
            if card.power:
                new_card.power = card.power
            if card.toughness:
                new_card.toughness = card.toughness
            if card.loyalty:
                new_card.loyalty = card.loyalty
            new_card.save()
            cur_set.card_set.add(new_card)
            if card.rarity == 'Common':
                pass
Example #2
0
    def get_edition_list(self):
        """
        Loads all editions from the API.
        For a SET, mtg api has the following properties:
            # code
            # name
            # gatherer_code
            old_code
            # magic_cards_info_code
            # release_date
            # border
            # type
            # block
            online_only
            booster
            mkm_id
            mkm_name
        We are using the commented ones, but more could be fetched from the API.
        """

        editions = []
        all_sets = Set.all()
        for s in all_sets:
            editions.append([s.code, s.name, s.gatherer_code, s.magic_cards_info_code, s.release_date,
                             s.border, s.type, s.block])
        return editions
Example #3
0
    def db_insert_data_card(self, cards_json):
        """Insert download from mtgjson"""
        c_rows = []
        s_rows = []
        for data in cards_json.values():
            cards = []
            for raw in data["cards"]:
                c = Card(raw)
                c.image_url = util.CARD_IMAGE_URL.format(c.multiverse_id)
                c.set = data["code"]
                c.set_name = data["name"]
                cards.append(c)

            for c in cards:
                c_rows.append(self.card_to_table_mapping(c))
            set = Set(data)
            s_rows.append(self.set_to_table_mapping(set))

        # Use separate connection to commit changes immediately
        con = sqlite3.connect(self.db_file)
        try:
            with con:
                sql_string = "INSERT INTO `cards` VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?," \
                             "?,?,?,?,?,?,?,?,?,?,?)"
                con.executemany(sql_string, c_rows)
                sql_string = "INSERT INTO `sets` VALUES (?,?,?,?,?,?,?,?,?,?,?)"
                con.executemany(sql_string, s_rows)

        except sqlite3.OperationalError as err:
            util.log("Database Error", util.LogLevel.Error)
            util.log(str(err), util.LogLevel.Error)
        except sqlite3.IntegrityError as err:
            util.log("Database Error", util.LogLevel.Error)
            util.log(str(err), util.LogLevel.Error)
Example #4
0
    def _get_all_sets(self):
        """
        Iterate through MTGSDK and extend all Set objects to self.sets.
        """

        self.sets.extend(Set.all())
        self.stdout.write(f'Grabbed {len(self.sets)} sets.')
Example #5
0
    def test_generate_booster_returns_cards(self):
        with vcr.use_cassette('fixtures/booster.yaml'):
            cards = Set.generate_booster('ktk')

            #NOTE: API booster size seems incorrect, returns 14 cards instead of expected 15
            self.assertEqual(14, len(cards))

            self.assertEqual('KTK', cards[0].set)
Example #6
0
 def downloadSets(self):
     #Downloading all sets name in one file
     sets = Set.all()
     
     with open('dataSet/allSets.csv', 'w', encoding='utf-8') as csvfile:
         writer = csv.writer(csvfile, delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)
         writer.writerow(['name', 'code', 'mkm_id', 'mkm_name', 'release_date'])
         for set in sets:
             writer.writerow([set.name, set.code, set.mkm_id, set.mkm_name, set.release_date])
Example #7
0
def GetAllSets():
    mtgsets = MTGSet.all()
    sets = []

    for mtgset in mtgsets:
        sett = Objects.Set(mtgset.code, mtgset.name)
        sets.append(sett)

    return sets
Example #8
0
 def sync_sets(self):
     sets = list(api_set.all())
     for set in sets:
         body = {
             'full_name': set.name,
             'abbreviation': set.code,
             'release_date': set.release_date,
             'type': set.type
         }
         Set.objects.update_or_create(defaults=body, abbreviation=set.code)
Example #9
0
def season():
    page = ""
    sets = Set.all()
    sets = [s for s in sets if s.type == 'core' or s.type == 'expansion']
    list.sort(sets, key=lambda s: s.release_date, reverse=True)
    page += "<script src='static/mtgleague.js?test=%s'></script>\n" % uuid.uuid4(
    )
    page += "<h1>MTG League Season</h1>\n"
    page += '<select id="setname" onchange="newSeason.updateStatus()">\n'
    for set in sets:
        setId = set.code
        setInfo = "%s [%s - %s]" % (set.name, set.type, set.release_date)
        page += "   <option value='%s'>%s</option>\n" % (setId, setInfo)
    page += '</select>\n'
    page += '''
<button onclick="newSeason.create()" id="createButton">create</button>
<button onclick="newSeason.reset()" id="resetButton">reset</button>
<br/>
<div>status: <span id="status"></div>
<div id="season-state-div">state: <span id="season-state"></span>
    <button onclick="newSeason.advance()" id="advanceButton">advance</button>
</div>
<div id="SeasonContent">
    <div id="Players"><h2>Players</h2>
        <div id="player-registration">
            <input type="text" id="newPlayerName" placeholder="Please use your office login"/><button onclick="newSeason.registerPlayer()">register</button>
        </div>
        <table id="players-table"></table>
    </div>
    <div id="Matches">
        <h2>Matches</h2>
        <select id="match-week" onchange="newSeason.updateMatches()"></select>
        <table id="match-table"></table>
    </div>
    <div id="rarepool">
        <h2>Rare Pool</h2>
        <div>Redeem Rare:
            <select id="rare-sel-player"></select>
            <select id="rare-sel-card" onchange="newSeason.updateRareSelImg()"></select>
            <button onclick="newSeason.redeemRare()">redeem</button>
            <img id="rare-sel-img" src="" alt="no image"/>
        </div>
        <table id="rarepool-table"></table>
    </div>
</div>
<script type='text/javascript'>
    window.onload = newSeason.updateStatus()
    var playerNameInput = document.getElementById('newPlayerName')
    playerNameInput.addEventListener("keydown", function(evt) {
                                                    if (evt.keyCode == 13) {
                                                        newSeason.registerPlayer() ;
                                                        playerNameInput.value=""
                                                }})
</script>'''
    return page
Example #10
0
 def test_find_returns_set(self):
     with vcr.use_cassette('fixtures/ktk.yaml'):
         set = Set.find('ktk')
         
         self.assertEqual('KTK', set.code)
         self.assertEqual('Khans of Tarkir', set.name)
         self.assertEqual('expansion', set.type)
         self.assertEqual('black', set.border)
         self.assertTrue('common' in set.booster)
         self.assertEqual('2014-09-26', set.release_date)
         self.assertEqual('ktk', set.magic_cards_info_code)
Example #11
0
    def test_find_returns_set(self):
        with vcr.use_cassette('fixtures/ktk.yaml'):
            set = Set.find('ktk')

            self.assertEqual('KTK', set.code)
            self.assertEqual('Khans of Tarkir', set.name)
            self.assertEqual('expansion', set.type)
            #NOTE: The API doesn't seem to be providing "border" at this time
            #self.assertEqual('black', set.border)
            self.assertTrue('common' in set.booster)
            self.assertEqual('2014-09-26', set.release_date)
Example #12
0
def query_and_write_sets():
    setlist = []
    print("query all sets")
    sets = Set.all()
    print("number of sets: " + str(len(sets)))
    for set in sets:
        dic = {'name': set.name, 'code': set.code}
        setlist.append(dic)
    write_json(setlist, "mtg_sets.json")
    print("all sets written to 'mtg_sets.json'")
    del setlist
Example #13
0
def net_load_set_list() -> dict:
    """ Load the list of all MTG sets from the Gather"""
    try:
        start = time()
        sets = Set.all()
        stop = time()
        log("Fetched set list in {}s".format(round(stop - start, 3)),
            LogLevel.Info)
    except MtgException as err:
        log(str(err), LogLevel.Error)
        return {}
    return [set.__dict__ for set in sets]
def get_card(card_request, session):
    session_attributes = {}
    cards = Card.where(name=card_request['intent']['slots']['CardName']['value'])\
                .where(contains='imageUrl').all()
    card = cards[0]
    title = card.name
    output = card.name + " is a " + card.type + " from " + Set.find(
        card.set).name + ",  and it's text reads " + card.text
    reprompt_text = "Please try again"
    return build_response(
        session_attributes,
        build_speechlet_response(title, output, reprompt_text, False))
Example #15
0
def generate_packs(selected_set, quantity):
    while quantity > 0:
        counter = 1
        card = Set.generate_booster(selected_set)
        current_pack = pack_number(selected_set)
        for i in card:
            img_data = requests.get(
                'http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid='
                + str(i.multiverse_id) + '&type=card').content
            with create_and_open(
                    current_pack,
                    current_pack + str(counter) + ' ' + str(i.name) + '.jpg',
                    'wb') as f:
                f.write(img_data)
                counter += 1
        quantity -= 1
Example #16
0
def card_query_to_set_name(card):
    """
    Takes: a card (a line from a facebook message) which has had all other commands removed (quantity, foil, etc)
        besides the set code
    Returns: the verbose full set name of the set code given, or an empty string
    """
    if card.split()[0][0] == "!" and len(
            card.split()[0]) == 4:  # Set codes must be 3 letters long
        code = card.split()[0][1:]  # Cut off exclamation mark
        try:
            set = Set.find(code).name
        except restclient.MtgException:
            set = ""
        return set
    else:
        return ""
Example #17
0
    def table_to_set_mapping(row):
        """Return Set object representation of a table row"""
        set = Set()
        set.code = row['code']
        set.name = row['name']
        set.type = row['type']
        set.border = row['border']
        set.mkm_id = row['mkmid']
        set.mkm_name = row['mkmname']
        set.release_date = row['releasedate']
        set.gatherer_code = row['gatherercode']
        set.magic_cards_info_code = row['magiccardsinfocode']
        set.booster = ast.literal_eval(row['booster'])
        set.old_code = row['oldcode']

        return set
Example #18
0
    def updateAll(self):
        psets = PersistentList()
        pcards = PCardList()

        for seti in mtgsdkSet.all():
            pset = PSet(seti)
            setCards = [
                PCard(card) for card in mtgsdkCard.where(set=seti.code).all()
            ]
            pset.extend(setCards)
            psets.append(pset)
            pcards.extend(setCards)
            print(pset, len(pcards), len(psets))

        self.root.sets = psets
        self.root.cards = pcards
        transaction.commit()
        print(self.sets)
        print(self.cards)
Example #19
0
    def writeInAllSets(self):
        try:
            sets = Set.where().all()
        except:
            raise Exception("Error in connection to database")

        setNames = ""

        for set in sets:
            setNames += set.code + "|" + set.name + "|"

            if set.block is not None:
                setNames += set.block + "\n"
            else:
                setNames += "\n"

        setNames = setNames.rstrip("\n")

        with open(self.filePathSets, "w") as file:
            file.write(setNames)
Example #20
0
    def __init__(self, root):
        self.root = root
        root.title("MTG Set Checker")

        # Define screen size based on user's screen
        screen_width = int(root.winfo_screenwidth() / 2)
        screen_height = int(root.winfo_screenheight() / 2)

        self.width = screen_width
        self.height = screen_height

        window_geometry = str(self.width) + 'x' + str(self.height)
        self.root.geometry(window_geometry)

        # Retrieve from MTGSDK, sort by release date, and pass into ScrollCanvas
        self.sets = Set.all()
        self.sets.sort(key=lambda set: set.release_date, reverse=True)

        setNames = list(set.name for set in self.sets)

        # Create Scroll Canvas
        self.setCheck = ScrollCanvas(root, setNames)

        # Test button for Check Button variable
        self.ok = Button(root, text="OK", command=self.printVar)

        # Add Clear Button
        self.clear = Button(root, text="Uncheck", command=self.uncheck)

        # Create Entry for Search
        # Create StringVar and bind to callback function on change
        sv = StringVar()
        sv.trace("w", lambda name, index, mode, sv=sv: self.update(sv))
        self.search = Entry(root, textvariable = sv)

        # Create ScrolledText for Cards
        cardsVar = StringVar()
        self.cards = ScrolledText(root)

        self.make_grid()
Example #21
0
    def form_valid(self, form):
        form.instance.user = self.request.user
        versions = []
        name = form.cleaned_data['name']
        set_name = form.cleaned_data['set_name']
        sets = MtgSet.where(name=set_name).all()
        if len(sets) > 0:
            code = sets[0].code
            versions = MtgCard.where(name=name, set=code).all()
        else:
            versions = MtgCard.where(name=name).all()
        if len(versions) > 0:
            retval = versions[0].image_url
        else:
            retval = "https://static.wikia.nocookie.net/mtgsalvation_gamepedia/images/f/f8/Magic_card_back.jpg"
        if form.is_valid():
            obj = form.save(commit=False)
            obj.image_url = retval
            #form.cleaned_data['image_url'] = retval
            obj.save()

        return super().form_valid(form)
Example #22
0
    def readSetsFromOnline(self):
        try:
            setObjects = Set.where().all()
        except OperationalError:
            raise OperationalError("Error in connection to database")

        sets = []
        setInfo = []

        for set in setObjects:
            setInfo = [
                set.code,
                set.name.replace(u"\u2014", "-").replace(u"\u2022", "*")
            ]

            if set.block is None:
                setInfo.append("")
            else:
                setInfo.append(set.block)

            sets.append(setInfo)

        return sets
Example #23
0
def retrieve_sets():
    return [i.__dict__ for i in Set.all()]
Example #24
0
 def fetch_a_card(self) -> MTGCard:
     card = secrets.choice(Card.where(set=secrets.choice(Set.all()).code).all())
     return self._fetch_from_scryfall(card)
Example #25
0
import json
from mtgsdk import Card, Set, Subtype

with open('logo.json') as surl:
    surldict = json.load(surl)

sets = Set.all()

print("{")
print("\"allsets\":	[")

for iset in sets:
    cardSetList = Card.where(set=iset.code) \
           .all()

    print("{")

    set_code = "none"
    if iset.code is not None:
        set_code = iset.code
    print("\"code\":" + "\"" + set_code + "\",")

    set_name = "none"
    if iset.name is not None:
        set_name = iset.name
    print("\"name\":" + "\"" + set_name + "\",")

    set_rDate = "none"
    if iset.release_date is not None:
        set_rDate = iset.release_date
    print("\"rDate\":" + "\"" + set_rDate + "\",")
Example #26
0
    def UpdateDB():
    #This is the master update script
    #Will first refresh the SETS table and then check to see if any sets are not present on CARDS table
    #Will then attempt to grab all cards in all sets that are currently not present
    
    #WARNING: 
    #Will take a long time on first load.  
    #Reccommend using UpdateSet() if you only care about specific sets.
        from mtgsdk import Card
        from mtgsdk import Set
        import sqlite3
        import base64
        import urllib.request, io
        import contextlib
        conn = sqlite3.connect('mtgDB.db')
        c = conn.cursor()

        #Drop tables
        c.executescript('''
        DROP TABLE IF EXISTS sets;
        DROP TABLE IF EXISTS mtgsets;
        ;''')
        print('Sets Table Dropped')

        c.execute('''CREATE TABLE if not exists sets (
            id   INTEGER       UNIQUE
            PRIMARY KEY
            NOT NULL,
            code VARCHAR (255),
            name VARCHAR (255),
            gatherer_code VARCHAR (255),
            old_code VARCHAR (255),
            magic_cards_info_code VARCHAR (255),
            release_date VARCHAR (255),
            border VARCHAR (255),
            stype VARCHAR (255),
            block VARCHAR (255),
            online_only VARCHAR (255),
            booster VARCHAR (255),
            mkm_id VARCHAR (255),
            mkm_name VARCHAR (255)
            );''')
        print("Sets Table created")

        #insert values
        sets = Set.all()
        for x in range (0, len(sets)):
            code =str(sets[x].code)
            name =str(sets[x].name)
            gatherer_code =str(sets[x].gatherer_code)
            old_code  =str(sets[x].old_code)
            magic_cards_info_code  =str(sets[x].magic_cards_info_code)
            release_date  =str(sets[x].release_date)
            border  =str(sets[x].border)
            stype  =str(sets[x].type)
            block  =str(sets[x].block)
            online_only  =str(sets[x].online_only)
            booster  =str(sets[x].booster)
            mkm_id  =str(sets[x].mkm_id)
            mkm_name  =str(sets[x].mkm_name)
            
            #to prevent single quote insert errors
            name = name.replace("'", "''")
            c.execute("INSERT INTO sets VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",(None,code,name,gatherer_code,old_code,magic_cards_info_code,release_date,border,stype,block,online_only,booster,mkm_id,mkm_name ))
            #print("Set #" + str(x) + " of " + str(len(sets)))

        print('Sets Table Populated')

        #Clear 'NONE' values from SETS
        c.execute('''UPDATE sets SET id = null where id='None' ''')
        c.execute('''UPDATE sets SET code = null where code='None' ''')
        c.execute('''UPDATE sets SET name = null where name='None' ''')
        c.execute('''UPDATE sets SET gatherer_code = null where gatherer_code='None' ''')
        c.execute('''UPDATE sets SET old_code = null where old_code='None' ''')
        c.execute('''UPDATE sets SET magic_cards_info_code = null where magic_cards_info_code='None' ''')
        c.execute('''UPDATE sets SET release_date = null where release_date='None' ''')
        c.execute('''UPDATE sets SET border = null where border='None' ''')
        c.execute('''UPDATE sets SET stype = null where stype='None' ''')
        c.execute('''UPDATE sets SET block = null where block='None' ''')
        c.execute('''UPDATE sets SET online_only = null where online_only='None' ''')
        c.execute('''UPDATE sets SET booster = null where booster='None' ''')
        c.execute('''UPDATE sets SET mkm_id = null where mkm_id='None' ''')
        c.execute('''UPDATE sets SET mkm_name = null where mkm_name='None' ''')
        print('Sets Table Cleaned')

        c.execute("SELECT DISTINCT code from sets where code not in (select distinct set_code from cards)")
        codes = c.fetchall()
        z = 0

        print("Adding cards from the following Sets:")
        print(codes)
        for z in range(0, len(codes)-1):
            codes[z] = str(codes[z]).replace('(','')
            codes[z] = codes[z].replace(')','')
            codes[z] = codes[z].replace(',','')
            codes[z] = codes[z].replace('\'','')
            print("Now getting cards from: " + codes[z])

            for y in range (1, 10000):
                cards = Card.where(set=codes[z]).where(page=y).where(pageSize=100).where(orderBy='set').all()
                #cards = Card.where(orderBy='name').all()
                for x in range (0, len(cards)):
                    name    =str(cards[x].name)
                    multiverse_id    =str(cards[x].multiverse_id)
                    layout    =str(cards[x].layout)
                    names    =str(cards[x].names)
                    mana_cost    =str(cards[x].mana_cost)
                    cmc    =str(cards[x].cmc)
                    colors =str(cards[x].colors)
                    color_identity    =str(cards[x].color_identity)
                    type_line    =str(cards[x].type)
                    types    =str(cards[x].types)
                    supertypes    =str(cards[x].supertypes)
                    subtypes    =str(cards[x].subtypes)
                    rarity    =str(cards[x].rarity)
                    text    =str(cards[x].text)
                    flavor    =str(cards[x].flavor)
                    artist    =str(cards[x].artist)
                    number    =str(cards[x].number)
                    power    =str(cards[x].power)
                    toughness    =str(cards[x].toughness)
                    loyalty    =str(cards[x].loyalty)
                    set_code    =str(cards[x].set)
                    set_name    =str(cards[x].set_name)
                    image_url    =str(cards[x].image_url)
                    border   =str(cards[x].border)
                    
                    # and len(str(cards[x].names)) == 0
                    if cards[x].names is not None and len(cards[x].names) != 0:
                        #print(cards[x].names)
                        if cards[x].names.index(name) == 0:
                            names = cards[x].names[1]
                        else:
                            names = cards[x].names[0]
                
                    #Image BLOB
                    data = None
                    if cards[x].image_url is not None:
                        #method to download card images from the 
                        with contextlib.closing(urllib.request.urlopen(image_url, data)) as fp:
                            image = base64.b64encode(fp.read())
                    else:
                        image = "No Image Available"
                    
                    #to prevent single quote import issues
                    text = text.replace("'", "''")
                    flavor = flavor.replace("'", "''")
                    name = name.replace("'", "''")
                    names = names.replace("'", "''")
                    names = names.replace('[', '')
                    names = names.replace(']', '')
                    names = names.replace('"', '')
                    set_name = set_name.replace("'", "''")
                    artist = artist.replace("'", "''")
                    mana_cost = mana_cost.replace('{', '')
                    mana_cost = mana_cost.replace('}', '')
                    color_identity = color_identity.replace('[', '')
                    color_identity = color_identity.replace(']', '')
                    color_identity = color_identity.replace(',', '')
                    color_identity = color_identity.replace(' ', '')
                    color_identity = color_identity.replace("'", '')
                    types = types.replace('[', '')
                    types = types.replace(']', '')
                    types = types.replace(',', '')
                    types = types.replace("'", '')
                    supertypes = supertypes.replace('[', '')
                    supertypes = supertypes.replace(']', '')
                    supertypes = supertypes.replace(',', '')
                    supertypes = supertypes.replace("'", '')
                    subtypes = subtypes.replace('[', '')
                    subtypes = subtypes.replace(']', '')
                    subtypes = subtypes.replace(',', '')
                    subtypes = subtypes.replace("'", '')
                    colors = colors.replace('White', 'W')
                    colors = colors.replace('Blue', 'U')
                    colors = colors.replace('Black', 'B')
                    colors = colors.replace('Red', 'R')
                    colors = colors.replace('Green', 'G')
                    colors = colors.replace(']', '')
                    colors = colors.replace('[', '')
                    colors = colors.replace(',', '')
                    colors = colors.replace(' ', '')
                    colors = colors.replace("'", "")
                    
                    c.execute("INSERT INTO cards VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",(None,name,multiverse_id,layout,names,mana_cost,cmc,colors,color_identity,type_line,supertypes,types,subtypes,rarity,text,flavor,artist,number,power,toughness,loyalty,border,image_url,set_code,set_name, image))
                    print(name + ' ' + set_code)
                    
                if(len(cards) == 0):
                    conn.commit()
                    break
                    
            #cards
            c.execute('''UPDATE cards SET id = null where id='None' ''')
            c.execute('''UPDATE cards SET name = null where name='None' ''')
            c.execute('''UPDATE cards SET multiverse_id = null where multiverse_id='None' ''')
            c.execute('''UPDATE cards SET layout = null where layout='None' ''')
            c.execute('''UPDATE cards SET names = null where names='None' ''')
            c.execute('''UPDATE cards SET mana_cost = null where mana_cost='None' ''')
            c.execute('''UPDATE cards SET cmc = null where cmc='None' ''')
            c.execute('''UPDATE cards SET colors = null where colors='None' ''')
            c.execute('''UPDATE cards SET color_identity = null where color_identity='None' ''')
            c.execute('''UPDATE cards SET type_line = null where type_line='None' ''')
            c.execute('''UPDATE cards SET supertypes = null where supertypes='None' ''')
            c.execute('''UPDATE cards SET types = null where types='None' ''')
            c.execute('''UPDATE cards SET subtypes = null where subtypes='None' ''')
            c.execute('''UPDATE cards SET rarity = null where rarity='None' ''')
            c.execute('''UPDATE cards SET text = null where text='None' ''')
            c.execute('''UPDATE cards SET flavor = null where flavor='None' ''')
            c.execute('''UPDATE cards SET artist = null where artist='None' ''')
            c.execute('''UPDATE cards SET number = null where number='None' ''')
            c.execute('''UPDATE cards SET power = null where power='None' ''')
            c.execute('''UPDATE cards SET toughness = null where toughness='None' ''')
            c.execute('''UPDATE cards SET loyalty = null where loyalty='None' ''')
            c.execute('''UPDATE cards SET border = null where border='None' ''')
            c.execute('''UPDATE cards SET image_url = null where image_url='None' ''')
            c.execute('''UPDATE cards SET set_code = null where set_code='None' ''')
            c.execute('''UPDATE cards SET set_name = null where set_name='None' ''')

            # Save (commit) the changes
            conn.commit()

        # We can also close the connection if we are done with it.
        # Just be sure any changes have been committed or they will be lost.
        conn.close()

        print("done")
html = '''
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link href="//cdn.jsdelivr.net/npm/keyrune@latest/css/keyrune.css" rel="stylesheet" type="text/css" />
    <link rel='stylesheet' href='style.css'>
  </head>
  <body>
{}
  </body>
</html>
'''

sets = Set.all()
sets.sort(key=lambda x: x.release_date, reverse=True)

mtg_list = []

for set in sets:
    if set.online_only != 1:
        mtg_list.append({
            'code': set.code.lower(),
            'name': set.name,
            'month': calendar.month_name[strptime(set.release_date, '%Y-%m-%d').tm_mon],
            'year': strptime(set.release_date, '%Y-%m-%d').tm_year
        })

items = []
Example #28
0
    def test_where_filters_on_name(self):
        with vcr.use_cassette('fixtures/filtered_sets.yaml'):
            sets = Set.where(name='khans of tarkir promos').all()

            self.assertEqual(1, len(sets))
            self.assertEqual('PKTK', sets[0].code)
 def test_where_filters_on_name(self):
     with vcr.use_cassette('fixtures/filtered_sets.yaml'):
         sets = Set.where(name='khans').all()
         
         self.assertEqual(1, len(sets))
         self.assertEqual('KTK', sets[0].code)
    def test_all_returns_all_sets(self):
        with vcr.use_cassette('fixtures/all_sets.yaml'):
            sets = Set.all()

            self.assertGreater(len(sets), 190)
Example #31
0
    def test_all_returns_all_sets(self):
        with vcr.use_cassette('fixtures/all_sets.yaml'):
            sets = Set.all()

            self.assertGreater(len(sets), 190)
Example #32
0
def find_cost(decknumber, all_main_decks, carddict, legal_sets, error, player_names, total_cost):
	setname = "temp"
	possible_sets = []
	cost_of_deck = 0
	for cardnumber in range(len(all_main_decks[decknumber])):
		cardname = all_main_decks[decknumber][cardnumber][0]
		if(cardname == "Mountain" or cardname == "Island" or cardname == "Swamp" or cardname == "Forest" or cardname == "Plains" or cardname == "Wastes"):
			continue#These are free cards, no one sells them
		if cardname in carddict:#Save time, on look ups
			cost_of_deck = cost_of_deck + (carddict[cardname] * float(all_main_decks[decknumber][cardnumber][1]))
			continue
			
			
		#format the card so it can be accepted
		tempcard = cardname
		tempcard = "\"" + cardname + "\""
		tempcard = tempcard.replace("'", "\'")
		cards = Card.where(name=tempcard).all()
		possible_sets.clear()
		#clean up the raw data

		#Find all sets the card was printed in
		for x in range(len(cards)):
			possible_sets.append(Set.find(cards[x].set).name)
			possible_sets[x] = possible_sets[x].replace('\\xa0', '')
			possible_sets[x] = possible_sets[x].replace('&nbsp;', '')
			possible_sets[x] = possible_sets[x].replace(' ','')
			#for some reason, the API returns 'time spiral timeshifted' but its referred to as timeshifted
			if(possible_sets[x] == "Time Spiral Timeshifted"):
				possible_sets[x] = "Timeshifted"
		
		flag = 0
		#Find the modern legal sets the card was printed in
		for set_1 in range(len(possible_sets)):
			for set_2 in range(len(legal_sets)):
				if(possible_sets[set_1] == legal_sets[set_2]):
					setname = possible_sets[set_1]
					flag = 1
				if(flag == 1):
					break
			if(flag == 1):
				break
		if(flag == 0):
			#Dont mind the debugging.
			#print("CARD NOT FOUND IN LEGAL SET")
			#for set_1 in range(len(possible_sets)):
			#	print(possible_sets[set_1])
			error.write(cardname)
			error.write('\n')
			error.write(tempcard)
			error.write('\n')
			continue
		flag = 0#Sanity check
		
		#alter the text s.t. it fits the url format
		setname = setname.replace(" ",'+')
		setname = setname.replace(".","")
		setname = setname.replace(":","")
		setname = setname.replace("'","")
		
		#For some reason, the site Im using has 'core set' after magic 2015 and 2014 but NOT 
		#after 2013-2010
		if(setname == "Magic+2015" or setname == "Magic+2014"):
			setname = setname + "+Core+Set"
		
		tempcard = cardname
		tempcard = tempcard.replace(" // ", " ")
		tempcard = tempcard.replace(" ","+")
		tempcard = tempcard.replace(",","")
		tempcard = tempcard.replace("'","")
		
		url = 'https://www.mtggoldfish.com/price/%s/%s#paper'%(setname,tempcard)
		
		cash = urllib.request.urlopen(url).read()
		sop = bs.BeautifulSoup(cash,'lxml')
		x = 0
		for div in sop.find_all('div' , class_='price-box-price'):
			if(x == 1):#Finds the physical cost of the card
				carddict[cardname] = float(div.text)
				cost_of_deck = cost_of_deck + (float(div.text) * float(all_main_decks[decknumber][cardnumber][1]))
				x = 0
			else:#as opposed to the price of it in an online format
				x = x + 1
	print("Total cost of the deck: $" + (str(float(truncate(cost_of_deck,2)))))
	
	#Originally wrote to file with no user input
	#ditched the idea but kept non-error file writing in the off chance I want to use it
	total_cost.write(player_names[decknumber])
	total_cost.write(": $")
	total_cost.write(str(float(truncate(cost_of_deck,2))))
	total_cost.write('\n')
Example #33
0
def net_load_sets():
    try:
        sets = Set.all()
    except:
        return ""
    return sets
 def test_generate_booster_returns_cards(self):
     with vcr.use_cassette('fixtures/booster.yaml'):
         cards = Set.generate_booster('ktk')
         
         self.assertEqual(15, len(cards))
         self.assertEqual('KTK', cards[0].set)