def createCard(request): if request.user.is_authenticated(): if request.method == 'POST': try: formDict = json.loads(request.body, encoding='latin1') except ValueError as e: print e return HttpResponse(status=500) try: values = parseCreateCardFormData(formDict) card = Card(name=values[0], value=values[1], cardIcon=values[2]) card.save() cardUser = CardUser(user=request.user, card=card, expiry_date=values[3]) cardUser.save() except Exception as e: print e return HttpResponse(status=500) return HttpResponse(card.id) else: return HttpResponse(status=400) return HttpResponse(status=401)
def upload_card_set(request): if request.method == 'POST': form = UploadCardSetForm(request.POST, request.FILES) if form.is_valid(): # Read cards file try: cards = Mnemosyne2Cards.read(request.FILES['file']) except Exception: # FIXME be more specific about what to catch cards = None #print >>sys.stderr, cards if cards: # Create new card set card_set = CardSet(name=form.cleaned_data['name']) card_set.save() # Create cards for question, answer in cards: card = Card(card_set=card_set, question=question, answer=answer) card.save() # TODO: provide feedback for invalid uploads else: form = UploadCardSetForm() return render_to_response('upload.html', {'form': form}, context_instance=RequestContext(request))
def new(request): if request.method == 'GET': if Card.objects.filter(card_user__in=Card_user.objects.filter( user_id=request.user.id)).count() == 0: return render(request, 'exchange/add.html', {'message': 'Vous n\'avez pas de carte a échanger'}) else: return render( request, 'exchange/add.html', { 'own_cards': Card.objects.filter(card_user__in=Card_user.objects.filter( user_id=request.user.id)).order_by('name'), 'all_cards': Card.objects.all() }) if request.method == 'POST': title = request.POST['title'] id_card_sender = request.POST['cards'] id_card_receiver = request.POST['card_demand'] query = Exchange(exchange_statut="pending", user_id=request.user.id, title=title, card_sender=Card(id=id_card_sender), card_receiver=Card(id=id_card_receiver)).save() return render(request, 'exchange/index.html', {'message': 'Votre demande a été enregistré'})
def _load_cards(self, eras, mythologies, tags): path = pathlib.Path('cards/all_data/cards/').glob('*.yaml') for file in path: with open(file) as f: card = yaml.safe_load(f) c = Card( name=card['name'], card_type=card['card_type'], cost=card['cost'], strength=card['strength'], max_pow=card['max_pow'], init_pow=card['init_pow'], mythology=mythologies[card['mythology']] if card['mythology'] else None, passive_effect=card['passive_effect'], quote=card['quote'], image=card['image'] ) c.save() for era in card['eras']: c.eras.add(eras[era]) if card['tags']: for tag in card['tags']: c.tags.add(tags[tag]) if card['abilities']: for ab in card['abilities']: for p, a in ab.items(): ability = Ability.objects.create(name=a, phase=p) c.abilities.add(ability)
def test_card_all_one_cards(self): self.assertEquals(Card.objects.get_queryset().all().count(), 0) # add expansion set es = ExpansionSet(name="Alpha", abbr="aaa") es.save() # add a rarity rc = Rarity(id='c', rarity='Common', sortorder=1) rc.save() # add a card pc = PhysicalCard() pc.save() bc = BaseCard() bc.physicalcard = pc bc.name = 'Test Name' bc.clean() bc.save() self.assertEquals(bc.physicalcard.layout, PhysicalCard.NORMAL) c = Card( basecard=bc, rarity=rc, expansionset=es, multiverseid=100, card_number='99') c.save() self.assertEquals(Card.objects.get_queryset().all().count(), 1)
def update_cards(self) -> bool: """ Updates existing Cards with any changes returns: True if there were no errors, otherwise False """ self.logger.info("Updating %s cards", UpdateCard.objects.count()) card_to_update: UpdateCard for card_to_update in UpdateCard.objects.all(): if card_to_update.update_mode == UpdateMode.CREATE: card = Card( scryfall_oracle_id=card_to_update.scryfall_oracle_id, name=card_to_update.name, ) else: card = Card.objects.get( scryfall_oracle_id=card_to_update.scryfall_oracle_id) for field, value in card_to_update.field_data.items(): if card_to_update.update_mode == UpdateMode.UPDATE: value = value["to"] if hasattr(card, field): setattr(card, field, value) else: raise NotImplementedError( f"Cannot update unrecognised field Card.{field}") card.save() return True
def form_valid(self, form): import_text = form.cleaned_data.pop("import_text") form.cleaned_data["owner"] = self.request.user course = Course(**form.cleaned_data) course.save() if import_text: for (term, definition) in import_text: card = Card(term=term, definition=definition, course=course) card.save() return super().form_valid(form)
def create(self, validated_data): new_position = Card.objects.filter( list_id=validated_data['list_id'].id).count() + 1 card = Card(name=validated_data['name'], list_id=validated_data['list_id'], description=validated_data['description'], owner=validated_data['owner'], expiration_date=validated_data['expiration_date'], position=new_position) card.save() return card
def handle(self, *args, **options): csv_file = options['csv_file'] with open(csv_file, encoding="latin-1") as datafile: reader = csv.DictReader(datafile) for row in reader: row['uuid'] = uuid.uuid4() card = Card() for field, data in row.items(): if '' != data: # only ingest fields with data setattr(card, field, data) card.save()
def push_from_json(json_file_path): with open(json_file_path, 'r') as f: cards = json.load(f) counter = 0 size = len(cards) for card in cards: new_card = Card(name=card['card_name'], local_path=card['card_image_url'].split('info')[1]) new_card.save() counter += 1 print('{}/{} card pushed'.format(counter, size))
def cardsForAddress(request, address): if request.method == "GET": cards = Card.objects.filter(owner=address) cards = list(map(lambda card: "{\"name\": \"" + card.template.name + "\", \"cardId\":" + str(card.template.cardId) + ",\"address\": \"" + card.address + "\"}", cards)) cards = '[' + ','.join(cards) + ']' return HttpResponse("{\"cards\": " + str(cards) +"}") elif request.method == 'POST': body = json.loads(request.body.decode("utf-8")) # Check if card has already been submitted if Card.objects.filter(id=body['id']).count() != 0: return HttpResponse("{message: There already exists a card with this id.}", status=403) card = Card(template=CardTemplate.objects.filter(name=body['name']).first(),owner=address, id=body['id'],address=body['address']) card.save() return HttpResponse("{\"name\": \"" +card.template.name + "\", \"cardId\": " + str(card.template.cardId) + "}")
def test_cards_get_random_words(admin): """ Test the select_random_words method """ with pytest.raises(ValueError) as error: Card.objects.select_random_words() assert error == 'the user and words fields are empty at the same time' words = Card.objects.select_random_words(admin) assert len(words) == 2 random_words = Card.objects.get_random_words(admin) words = Card.objects.select_random_words(words=random_words, additional='additional') assert len(words) == 2 for i in range(10): card = Card() card.word = 'word' + str(i) card.complete = 122 card.created_by = admin card.deck_id = 1 card.save() words = Card.objects.select_random_words(admin, additional='additional') words_next = Card.objects.select_random_words(admin, additional='additional') assert len(words) == 4 assert words != words_next assert 'additional' in words
def create_deck(): """ Create a list of playing cards in our database """ suits = [0, 1, 2, 3] ranks = [ 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'jack', 'queen', 'king', 'ace' ] def get_card_image(suit, rank): rank_repr = CONVERSION[rank] if rank in CONVERSION else rank suit_repr = "" for suit_index, suit_name in Card.SUITS: if suit == suit_index: suit_repr = suit_name break return "card_images/{}_of_{}s.jpg".format(rank_repr, suit_repr) cards = [ Card(suit=suit, rank=rank, image=get_card_image(suit, rank)) for rank in ranks for suit in suits ] Card.objects.bulk_create(cards)
def create_standard_cards(): # creating abilities # tap for mana tap_ability = Ability(cost='t', benefit='m1g') tap_ability.save() # creating land card = Card(kind='person', support=0) card.save() card.abilities.add(tap_ability) card.save() # creating creatures for power, endurance in product(range(0, 6), range(1, 6)): card = Card(kind='opinion', support=1, power=power, endurance=endurance) card.save()
def render_to_response(self, context, **response_kwargs): set_code = context['set_code'] try: expansion = Expansion.objects.get(code=set_code) data = Card.grand_total(expansion.name) except Expansion.DoesNotExist: data = [] return JsonResponse(data, safe=False)
def user_card_ownership_count(card: Card, user: User) -> int: """ Returns the total number of cards that given user owns of the given card :param card: The card to find all ownerships for :param user: The user who should own the card :return: The ownership total """ return card.get_user_ownership_count(user, prefetched=True)
def user_card_ownership_count(card: Card, user: settings.AUTH_USER_MODEL) -> int: """ Returns the total number of cards that given user owns of the given card :param card: The card to find all ownerships for :param user: The user who should own the card :return: The ownership total """ return card.get_user_ownership_count(user, prefetched=True)
def add(request): card = Card.create(request) url = reverse('view', kwargs = {'slug': card.slug}) + '?new=1' sender_subject = add_replace(card, config.EMAIL_SUBJECT_SENDER) sender_body = add_replace(card, config.EMAIL_BODY_SENDER) recipient_subject = add_replace(card, config.EMAIL_SUBJECT) recipient_body = add_replace(card, config.EMAIL_BODY) send_mail(recipient_subject, None, card.sender.email, [card.recipient.email], fail_silently = True, html_message = mark_safe(recipient_body)) send_mail(sender_subject, None, card.sender.email, [card.sender.email], fail_silently = True, html_message = mark_safe(sender_body)) return HttpResponseRedirect(url)
def get_context_data(self, **kwargs): rarity = self.request.GET.get('rarity', '') context = super(CardList, self).get_context_data(**kwargs) set_code = kwargs.get('set_code', '') expansions = Expansion.objects.all() try: expansion = Expansion.objects.get(code=set_code) stats = Card.grand_total(expansion.name) if rarity: cards = Card.objects.filter(set_name=expansion.name, rarity=rarity) else: cards = Card.objects.filter(set_name=expansion.name) except Expansion.DoesNotExist: stats = Card.grand_total('') cards = Card.objects.all() context['card_list'] = cards max_count = stats['total'] distinct_total = stats['distinct_total'] context['distinct_total'] = distinct_total context['max_count'] = max_count total_owned = stats['total_owned'] context['set_code'] = set_code context['expansions'] = expansions context['owned'] = cards.filter(count__gt=0) if distinct_total: owned_percentage = (context['owned'].count() * 100.0) / distinct_total else: owned_percentage = 0 context['owned_diff'] = distinct_total - context['owned'].count() context['total_diff'] = max_count - total_owned context['owned_percentage'] = '{0:.2f}'.format(owned_percentage) context['rarity'] = stats['rarity'] context['total_owned'] = total_owned if max_count: total_percentage = (total_owned * 100.0) / max_count else: total_percentage = 0 context['total_percentage'] = '{0:.2f}'.format(total_percentage) return context
def import_lots(request): """Import a bunch of cards.""" if request.method == "POST": form = ImportCardForm(request.POST, request.FILES) if form.is_valid(): for card in Card.from_yaml(request.FILES['yamlfile']): card.save() return redirect('home') else: form = ImportCardForm() return render(request, 'cards/import.html', {'form': form})
def test_votes_use_elo(self): bad_card = Card(name='Baddie',elo=1000,votes=1000) good_card = Card(name='Goodie',elo=1900,votes=1000) good_card.save() bad_card.save() response = self.client.post('/vote/', {'voted_for':'Goodie', 'voted_against':'Baddie'}) return self.assertEqual(Card.objects.get(name='Goodie').elo,1902) #minimum elo gain
def createCard(request): if request.user.is_authenticated(): if request.method == 'POST': try: formDict = json.loads(request.body, encoding = 'latin1') except ValueError as e: print e return HttpResponse(status=500) try: values = parseCreateCardFormData(formDict) card = Card(name = values[0], value = values[1], cardIcon = values[2]) card.save() cardUser = CardUser(user = request.user, card = card, expiry_date = values[3]) cardUser.save() except Exception as e: print e return HttpResponse(status=500) return HttpResponse(card.id) else: return HttpResponse(status=400) return HttpResponse(status=401)
def setUp(self): super().setUp() self.card = Card(cardName="Chase Freedom", bankName="Chase", annualFee=0, rewardsType="Cash Back", rewardValue=0.01, rewardsDisplay="5% cash back on select categories", groceryMultiplier=2, restMultiplier=2, travelMultiplier=2, gasMultiplier=2, elseMultiplier=1, APR=2, bonusDisplay="dd", bonusValue=2, link="Chase.com", creditScore=2, bonusMinimumSpend=1, bonusSpendMonths=1) self.card.save() self.browser.get(self.live_server_url + reverse("cards:forms"))
def test_cards_default_deck(admin): """ Should set the default deck for user """ card = Card() card.word = 'word' card.created_by = admin card.save() assert card.deck_id == 1
def exploding_kittens_dying_in_the_first_round(): """ What happened today...My defuse has been stolen before my turn and then I've picked up the Exploding kitten straight away. What are the odds of this? Jack of Hearths will be our Defuse and Queen of Hearts will be our Exploding Kitten """ deck = StandardDeck() # there are 40 + 20 cards roughly king_of_spades = Card(13, constants.SUIT_SPADES) # so lets fill the deck with fluff - king of spades for x in range(60 - len(deck.cards)): deck.insert_card(king_of_spades, force=True) defuse = Card(11, constants.SUIT_HEARTS) exploding_kitten = Card(12, constants.SUIT_HEARTS) # Lets deal "defuse" to player 1, among with 6 other cards player_1_cards = [deck.pick_card(defuse)] for x in range(1, 6): card = Card(value=x, suit=constants.SUIT_CLUBS) player_1_cards += [deck.pick_card(card)] player_2_cards = [] for x in range(0, 6): card = Card(value=x + 1, suit=constants.SUIT_DIAMONDS) player_2_cards += [deck.pick_card(card)] # now lets pick defuse from player 1 and at the same time that player # will pick up an exploding kitten card = player_1_cards.pop(random.randrange(len(player_1_cards))) if defuse.is_the_same_card(card): # After picking defuse from player 1, player 2 now picks up # non-exploding kitten card deck.pick_card(Card(value=10, suit=constants.SUIT_HEARTS)) # Player 1, now without defuse, is picking up the card, hoping it is # not an Exploding kitten second_card = deck.pick_random_card() if second_card.is_the_same_card(exploding_kitten): return True
def add_new_card(request, card_uid): card = Card(tag_uid=card_uid) encKeyA = request.POST["keyA"] encKeyB = request.POST["keyB"] card.keyA = encKeyA card.keyB = encKeyB card.save() # Log everything! event_text = datetime.now().strftime("%Y-%m-%d %H:%M:%S") event_text += " [Door.Back]" event_text += " New Card" event_text += " (" + card_uid + ")" event_text += " Card Added" return render_to_response("cards/success.txt")
def test_get_war_result_usercard_less_than_dealercard(self): """Test that we get the proper result for usercard less than dealercard""" dealercard = Card.objects.create(suit=Card.CLUB, rank="ace") result = Card.get_war_result(self.card, dealercard) self.assertEqual(result, -1)
def test_war_result_draw(self): """test for draw scenario""" user = Card.objects.create(suit=Card.HEART, rank='five') comp = Card.objects.create(suit=Card.HEART, rank='five') self.assertEqual(Card.get_war_result(user, comp), 0)
def save_form(self): # noqa: D102 form = self.get_form() # TODO: add validation form.is_valid() self.object = Card.release_card(form.cleaned_data['card_holder'])
def test_get_war_result_usercard_equal_to_dealercard(self): """Test that we get the proper result for usercard equal to dealercard""" dealercard = Card.objects.create(suit=Card.CLUB, rank="jack") result = Card.get_war_result(self.card, dealercard) self.assertEqual(result, 0)
def index(request): cards = Card.objects.all().order_by('name', 'edition') if request.method == 'POST': form = CardForm(request.POST) if form.is_valid(): edition = Edition.objects.get(set_id=form.cleaned_data['edition']) foil = False if (('foil' in form.cleaned_data and form.cleaned_data['foil'] == 'true')): foil = True try: card = Card.objects.get( name=form.cleaned_data['name'], foil=foil, edition=edition, condition=form.cleaned_data['condition']) card.quantity += int(form.cleaned_data['quantity']) card.save() except Card.DoesNotExist: card = Card( name=form.cleaned_data['name'], edition=edition, foil=foil, condition=form.cleaned_data['condition'], quantity=form.cleaned_data['quantity']) card.save() url = ('https://api.deckbrew.com/mtg/cards/%s' % slugify(card.name)) response = requests.get(url) editions = response.json()['editions'] for edition in editions: if ((edition['set_id'] == card.edition.set_id and 'price' in edition)): card.multiverse_id = edition['multiverse_id'] card.rarity = edition['rarity'][0].upper() card.price_low = edition['price']['low'] / 100.0 card.price_med = edition['price']['median'] / 100.0 card.price_high = edition['price']['high'] / 100.0 card.save() form = CardForm() context = Context({ 'card_list': cards, 'form': form }) return render(request, 'index.html', context)
def test_leaderboard_showing_pt(self): new_card = Card(name='Kraken Hatchling',elo='9999',votes=10) new_card.save() response = self.client.get('/leaderboard/') return self.assertContains(response, '[0/4]')
def mass_add(request): if request.method == "POST": data = request.POST user = UserCustom.objects.get(user_id__exact=request.user.pk) try: form = MassCardForm(data) if form.is_valid(): start = form.cleaned_data['code_start'] end = form.cleaned_data['code_end'] length = form.cleaned_data['code_length'] pool = [str(x).zfill(length) for x in range(start, end + 1, 1)] for code in pool: try: card = Card.objects.get(code__exact=code, org_id__exact=user.org.pk) exist = True except: card = Card() exist = False card.org = user.org if not exist: card.code = code card.org = user.org card.type = form.cleaned_data['type'] card.discount = form.cleaned_data['discount'] card.bonus = form.cleaned_data['bonus'] card.accumulation = form.cleaned_data['accumulation'] card.reg_date = datetime.now().date() card.last_transaction_date = datetime.now().date() else: if form.cleaned_data['doubles'] == 'rewrite': card.type = form.cleaned_data['type'] card.discount = form.cleaned_data['discount'] card.bonus = form.cleaned_data['bonus'] card.accumulation = form.cleaned_data[ 'accumulation'] card.fio = '' card.deleted = 'n' card.reg_date = datetime.now().date() card.last_transaction_date = datetime.now().date() card.changes_date = None elif form.cleaned_data['doubles'] == 'append': card.type = form.cleaned_data['type'] card.discount = form.cleaned_data['discount'] card.bonus = form.cleaned_data['bonus'] card.accumulation = form.cleaned_data[ 'accumulation'] card.deleted = 'n' card.reg_date = datetime.now().date() card.last_transaction_date = datetime.now().date() card.changes_date = None elif form.cleaned_data['doubles'] == 'ignore': continue card.save() return HttpResponseRedirect('/cards/') except Exception as e: response = {"result": e} return HttpResponse(response, content_type="application/json") response = {"result": "error"} return HttpResponse(json.dumps(response), content_type="application/json")
def test_new_card(self): new_card = Card(name='Cobblebrute',elo='9999',votes=5) new_card.save() response = self.client.get('/leaderboard/') return self.assertContains(response, '[5/2]')
def handle(self, **options): # Mandatory set if options['set'] is None: print("set argument is missing!") sys.exit() # set must be valid if len(options['set']) != 3: print("set is not valid, must be 3 digit") sys.exit() lang = options['lang'].lower() if len(options['lang']) == 2 else "en" set = options['set'].lower() with open("data/sets/" + lang + "/" + set + ".json") as f: cards = json.load(f) counter = 1 for single_card in cards: card = Card.objects.filter( scryfall_id=single_card['id']).first() if card is None: card = Card( language=lang, set=set, layout=single_card['layout'], rarity=single_card['rarity'], multiverse_id=single_card['multiverse_ids'].pop(0) if len(single_card['multiverse_ids']) > 0 else "", scryfall_id=single_card['id'], collector_number=single_card['collector_number'], ) print( str(counter) + "/" + str(len(cards)) + " New card from " + set + " (" + lang + ") : " + single_card['layout']) # nopep8 faces = [] types = [] if single_card['layout'] == "normal": # NORMAL layout : 1 Face, 1 Type card.name = single_card[ 'printed_name'] if "printed_name" in single_card else single_card[ 'name'] face = Face( card=card, illustration_id=single_card['illustration_id']) face.descriptors = get_image_descriptions( single_card['image_uris']['large']) # nopep8 faces.append(face) type = Type( # Only get the card type (ex: Creature — Human Rogue) type=single_card['type_line'].split(" — ").pop(0), face=face, ) types.append(type) elif single_card['layout'] == "modal_dfc": # MODAL DOUBLE FACE : 2 Faces, 2 Types for single_face in single_card["card_faces"]: face = Face( card=card, illustration_id=single_face["illustration_id"], name=single_face['printed_name'] if "printed_name" in single_face else single_face['name']) face.descriptors = get_image_descriptions( single_face['image_uris']['large']) # nopep8 faces.append(face) if card.name != "": card.name = card.name + " // " card.name = card.name + face.name type = Type( # Only get the card type (ex: Creature — Human Rogue) type=single_face['type_line'].split(" — ").pop( 0), face=face, ) types.append(type) if len(faces) > 0 and len(types) > 0: card.save() for face in faces: face.save() for type in types: type.save()
import django django.setup() from cards.models import Card Card.fix()
def add(request): try: context = { "decks": Deck.objects.all().order_by('name'), "deck_types": DeckType.objects.all().order_by('sort_order', 'name') } name = request.POST['name'].strip() if len(name) > 0: d = Deck(name=name, notes=request.POST['notes'], deckType=DeckType.objects.get( pk=int(request.POST['deckType']))) d.save() p = re.compile("(\\d+)x (.+)") issue_list = [] cards = None if len(request.POST['list'].strip().replace('\r\n', '\n')) != 0: main = request.POST['list'].strip().replace('\r\n', '\n').split('\n') else: main = [] if len(request.POST['sideboard'].strip().replace('\r\n', '\n')) != 0: total = main + request.POST['sideboard'].strip().replace( '\r\n', '\n').split('\n') else: total = main print(total) for i, line in enumerate(total): m = p.match(line.strip()) if m is None: issue_list.append( "Line {} is badly formed. Card could not be added.". format(line)) else: c = Card.objects.filter(name__iexact=m.groups()[1]) if len(c) == 0: #try json if cards is None: f = open(os.path.join(settings.BASE_DIR, 'AllCards.json'), 'r', encoding='utf8') cards = json.load(f) f.close() if m.groups()[1] in cards: c = Card(name=m.groups()[1], text=cards[m.groups()[1]]['text'], notes="", addMana=False) #mana cost if "manaCost" in cards[m.groups()[1]]: c.manaCost = cards[ m.groups()[1]]['manaCost'].replace( '}{', ',').replace('{', '').replace( '}', '').replace('/', '') #ptl if "power" in cards[m.groups()[1]]: c.power = cards[m.groups()[1]]["power"] if "toughness" in cards[m.groups()[1]]: c.toughness = cards[m.groups()[1]]["toughness"] if "loyalty" in cards[m.groups()[1]]: c.loyalty = cards[m.groups()[1]]["loyalty"] c.save() #types if "supertypes" in cards[m.groups()[1]]: for type in cards[m.groups()[1]]['supertypes']: t = Type.objects.filter(name__exact=type, typeType__exact=2) if len(t) == 0: t = Type(name=type, typeType=2) t.save() else: t = t[0] c.types.add(t) if "types" in cards[m.groups()[1]]: for type in cards[m.groups()[1]]['types']: t = Type.objects.filter(name__exact=type, typeType__exact=3) if len(t) == 0: t = Type(name=type, typeType=3) t.save() else: t = t[0] c.types.add(t) if "subtypes" in cards[m.groups()[1]]: for type in cards[m.groups()[1]]['subtypes']: t = Type.objects.filter(name__exact=type, typeType__exact=1) if len(t) == 0: t = Type(name=type, typeType=1) t.save() else: t = t[0] c.types.add(t) #sets f = open( os.path.join(settings.BASE_DIR, 'SetList.json'), 'r') sets = json.load(f) f.close() if "printings" in cards[m.groups()[1]]: for code in cards[m.groups()[1]]["printings"]: for jset in sets: if jset["code"] == code: if jset["type"] not in bad_set_types: set = Set.objects.filter( name__exact=jset["name"]) if len(set) == 0: set = Set( name=jset["name"]) set.save() else: set = set[0] set.cards.add(c) break if i < len(main): dc = DeckCard(card=c, count=int(m.groups()[0]), deck=d) else: dc = DeckCard(card=c, sideboard_count=int( m.groups()[0]), deck=d) dc.save() else: issue_list.append( "Could not find a card named {}. Card could not be added." .format(m.groups()[1])) else: if i < len(main): dc = DeckCard(card=c[0], count=int(m.groups()[0]), deck=d) else: dc = DeckCard(card=c[0], sideboard_count=int(m.groups()[0]), deck=d) dc.save() if len(issue_list) > 0: context['saved'] = '\\n'.join(issue_list) context['new_deck'] = d.id else: return redirect('/decks/{}'.format(d.id)) else: context['error'] = "Deck must have a name." if mobile(request): return render(request, 'decks/m_add.html', context) else: return render(request, 'decks/add.html', context) except KeyError: if mobile(request): return render(request, 'decks/m_add.html', context) else: return render(request, 'decks/add.html', context) except OSError as ex: print(ex)
class TestFormPage(BaseFunctionalTest): def setUp(self): super().setUp() self.card = Card(cardName="Chase Freedom", bankName="Chase", annualFee=0, rewardsType="Cash Back", rewardValue=0.01, rewardsDisplay="5% cash back on select categories", groceryMultiplier=2, restMultiplier=2, travelMultiplier=2, gasMultiplier=2, elseMultiplier=1, APR=2, bonusDisplay="dd", bonusValue=2, link="Chase.com", creditScore=2, bonusMinimumSpend=1, bonusSpendMonths=1) self.card.save() self.browser.get(self.live_server_url + reverse("cards:forms")) # test valid data in form submit redirects to display_cards page def test_form_valid_data_submit(self): self.__check_form_data_submit_helper(1000) self.__check_valid_form_results_populated() # test no data in form submit stays in forms page def test_form_no_data_submit(self): self.__submit_form() self.__check_form_submit_redirection() # test invalid data in form submit stats in forms page def test_form_invalid_data_submit(self): self.__check_form_data_submit_helper('test') # helper to input data and redirect for form def __check_form_data_submit_helper(self, data): assert data is not None text_boxes = self.browser.find_elements_by_xpath( "//input[@type='number']") for textbox in text_boxes: textbox.send_keys(data) time.sleep(0.5) self.__submit_form() time.sleep(2) self.__check_form_submit_redirection() # find submit button and submit form def __submit_form(self): self.browser.find_element_by_tag_name("form").submit() # check submit form page redirection def __check_form_submit_redirection(self): self.assertEquals(self.browser.current_url, self.live_server_url + reverse('cards:forms')) # check valid form populates results on the page def __check_valid_form_results_populated(self): results = self.browser.find_elements_by_class_name("display") self.assertLess(0, len(results))
def update_card(self, staged_card: StagedCard) -> Card: """ Updates or creates the Card object for the given StagedCard :param staged_card: The staging information for this card :return: The updated or created Card """ try: if staged_card.is_token: card = Card.objects.get(name=staged_card.get_name(), scryfall_oracle_id=staged_card.get_scryfall_oracle_id(), is_token=True, side=staged_card.get_side()) else: card = Card.objects.get(name=staged_card.get_name(), is_token=False) if not self.force_update and staged_card.get_name() in self.updated_cards: logger.info('%s has already been updated', card) self.increment_ignores('Card') return card logger.info('Updating existing card %s', card) self.increment_updated('Card') except Card.DoesNotExist: card = Card(name=staged_card.get_name()) logger.info('Creating new card %s', card) self.increment_created('Card') self.updated_cards.append(staged_card.get_name()) card.cost = staged_card.get_mana_cost() card.cmc = staged_card.get_cmc() card.colour_flags = staged_card.get_colour() card.colour_identity_flags = staged_card.get_colour_identity() card.colour_count = staged_card.get_colour_count() card.colour_sort_key = staged_card.get_colour_sort_key() card.colour_weight = staged_card.get_colour_weight() card.power = staged_card.get_power() card.toughness = staged_card.get_toughness() card.num_power = staged_card.get_num_power() card.num_toughness = staged_card.get_num_toughness() card.loyalty = staged_card.get_loyalty() card.num_loyalty = staged_card.get_num_loyalty() card.type = staged_card.get_types() card.subtype = staged_card.get_subtypes() card.original_type = staged_card.get_original_type() card.rules_text = staged_card.get_rules_text() card.original_text = staged_card.get_original_text() card.layout = staged_card.get_layout() card.side = staged_card.get_side() card.scryfall_oracle_id = staged_card.get_scryfall_oracle_id() card.is_reserved = staged_card.is_reserved() card.is_token = staged_card.is_token card.full_clean() card.save() return card
def test_war_result_loss(self): """test for user loses scenario""" user = Card.objects.create(suit=Card.HEART, rank='four') comp = Card.objects.create(suit=Card.HEART, rank='five') self.assertEqual(Card.get_war_result(user, comp), -1)
def rest_new_card(request): response = {} if request.method == 'PUT': user = UserCustom.objects.get(user_id__exact=request.user.pk) card_new_data = json.loads(request.body.decode()) card = Card() card.org = user.org card.reg_date = datetime.now() card.changes_date = datetime.now() card.holder_name = card_new_data['holder_name'] card.code = card_new_data['code'] card.holder_phone = card_new_data['holder_phone'] card.sex = card_new_data['sex'] card.type = card_new_data['type'] try: card.save() response['status'] = 'success' response['message'] = 'Новая карта успешно заведена!' return JsonResponse(response, safe=False) except IntegrityError as err: response['status'] = 'error' response['message'] = 'Карта с таким кодом уже существует!' return JsonResponse(response, safe=False)
def test_votes_use_certainty(self): new_card = Card(name='Cobblebrute',elo='1000',votes=10) new_card.save() new_card = Card(name='Homicidal Seclusion',elo='1000',votes=0) new_card.save() new_card = Card(name='Rakdos Guildgate',elo='1000',votes=0) new_card.save() new_card = Card(name='Life from the Loam',elo='1000',votes=0) new_card.save() response = self.client.post('/vote/', {'voted_for':'Cobblebrute', 'voted_against':'Homicidal Seclusion'}) response = self.client.post('/vote/', {'voted_for':'Rakdos Guildgate', 'voted_against':'Life from the Loam'}) cobblebrute = Card.objects.get(name='Cobblebrute') rakdos_guildgate = Card.objects.get(name='Rakdos Guildgate') homicidal_seclusion = Card.objects.get(name='Homicidal Seclusion') life_from_the_loam = Card.objects.get(name='Life from the Loam') if (rakdos_guildgate.elo > cobblebrute.elo and cobblebrute.elo > 1000 and life_from_the_loam.elo == homicidal_seclusion.elo): pass else: self.fail("ELOs not moving properly: " + str(rakdos.elo) + " " + str(cobblebrute.elo) + " " + str(life_from_the_loam.elo) + " " + str(homicidal_seclusion.elo))
def maintenance(request): response = {} if request.method == "POST": post = request.POST user = UserCustom.objects.get(user_id__exact=request.user.pk) if "cmd" in post: if post["cmd"] == "save": # сохранение карты if "data" in post: data = json.loads(post["data"]) try: form = CardForm(data) if form.is_valid(): try: #if "collision" in post: #if post['collision'] card = Card.objects.get( code__exact=form.cleaned_data['code'], org_id__exact=user.org.pk) except ObjectDoesNotExist as e: card = Card() card.code = form.cleaned_data['code'] card.holder_name = form.cleaned_data['holder_name'] card.holder_phone = form.cleaned_data[ 'holder_phone'] card.bonus = form.cleaned_data['bonus'] card.discount = form.cleaned_data['discount'] card.accumulation = form.cleaned_data[ 'accumulation'] card.type = form.cleaned_data['type'] card.changes_date = datetime.now().date() if not card.reg_date: card.reg_date = datetime.now().date() card.last_transaction_date = datetime.now( ).date() card.org = user.org card.save() response = {"result": "ok"} return HttpResponse( json.dumps(response), content_type="application/json") except: response = {"result": "error"} return HttpResponse(json.dumps(response), content_type="application/json") if post["cmd"] == "get": # получение данных по карте if "data" in post: data = json.loads(post["data"]) try: card = Card.objects.filter( code__exact=data["code"], org_id__exact=user.org.pk).get() date_func = lambda a: '' if a is None else a.strftime( '%Y-%m-%d') data = { "code": card.code, "holder_name": card.holder_name, "holder_phone": card.holder_phone, "accumulation": card.accumulation, "bonus": card.bonus, "discount": card.discount, "type": card.type, "reg_date": date_func(card.reg_date), "changes_date": date_func(card.changes_date), "last_transaction_date": date_func(card.last_transaction_date) } response = {"result": "ok", "data": data} response = json.dumps(response) return HttpResponse(response, content_type="application/json") except Exception as err: response = {"result": "error", "msg": err} return HttpResponse(json.dumps(response), content_type="application/json") if post["cmd"] == "delete": # получение данных по карте if "data" in post: data = json.loads(post["data"]) try: for code in data: card = Card.objects.filter( code__exact=code, org_id__exact=user.org.pk).get() card.deleted = 'y' card.save() response = {"result": "ok", "data": data} response = json.dumps(response) return HttpResponse(response, content_type="application/json") except Exception as err: response = {"result": "error", "msg": err} return HttpResponse(json.dumps(response), content_type="application/json") if post["cmd"] == "restore": # получение данных по карте if "data" in post: data = json.loads(post["data"]) try: for code in data: card = Card.objects.filter( code__exact=code, org_id__exact=user.org.pk).get() card.deleted = 'n' card.save() response = {"result": "ok", "data": data} response = json.dumps(response) return HttpResponse(response, content_type="application/json") except Exception as err: response = {"result": "error", "msg": err} return HttpResponse(json.dumps(response), content_type="application/json")
raise django.setup() from cards.models import Card from orgs.models import Org import xlrd import re from datetime import datetime rb = xlrd.open_workbook('sport_import.xlsx') sheet = rb.sheet_by_index(0) org = Org.objects.get(id__exact=3) for nrow in range(sheet.nrows): card = Card() if nrow == 0: continue row = sheet.row_values(nrow) name = row[0] name = re.sub(r'[0-9]+', '', name) name = name.strip() name = name.title() card.holder_name = name code = row[1] card.code = str(code) reg_date = row[2] try:
def handle(self, *args, **options): try: file = io.open('cardlist.txt', 'rt') errors = io.open('failed.txt', 'w') booster = None count = 0 fail_count = 0 for line in file: if line.strip() == '': continue if line.startswith('###'): booster_name = line.strip('# \n') print booster_name booster = Booster.objects.get(name=booster_name) continue count += 1 try: response = requests.get('http://yugiohprices.com/api/card_data/' + line.strip()) json = response.json() except Exception, e: bugsnag.notify(e, context='CardImport', meta_data={ 'card': line, 'booster_name': booster_name, 'response': response.text }) json = None card = Card(name=line.strip()) if json and json['status'] == 'success': card.description = json['data']['text'] if json['data']['card_type'] == 'monster': card.attack = json['data']['atk'] card.defense = json['data']['def'] card.attribute = json['data']['family'].lower() card.level = json['data']['level'] card.save() types = [] for t in json['data']['type'].split('/'): ct = CardType.objects.get(name=t.strip()) types.append(ct.id) card.card_types = types else: card.effect_type = ('{} {}'.format(json['data']['property'], json['data']['card_type'])).lower() else: errors.write(line) errors.flush() fail_count += 1 card.save() card.boosters = [ booster.id ] card.save() print '{} - {} ({})'.format(booster.name, line.strip(), str(count)) except Exception, e: bugsnag.notify(e, context='CardImport', meta_data={ 'card': line, 'booster_name': booster_name, 'response': response.text })
def handle(self, *args, **options): all_sets = CardSet.objects.all() if len(all_sets) == 0: raise CommandError(NO_CARDSETS) if len(args) == 1: sets = CardSet.objects.filter(name__icontains=args[0], country="GB") if len(sets) < 1: raise CommandError(NO_SETS_FOUND.format(args[0], "\n".join([str(cs) for cs in all_sets]))) else: sets = CardSet.objects.filter(country="GB") self.stdout.write("found card sets {0}\n".format(", ".join([str(cs) for cs in sets]))) self.stdout.write("Started Scrape command\n") card_no = re.compile("\s*(?P<card_no>\d+)/(?P<count>\d+)\s*") card_list_h2 = re.compile("((C|c)ard (L|l)ist(s)*)|(Setlist)") energy_type = re.compile("(?P<energy_type>\w+) Energy \(((TCG)|(Basic))\)") for cs in sets: self.stdout.write("Processing '{0}'\n".format(cs.name)) if cs.partial_url is None or cs.partial_url == "": raise CommandError("{0} does not have a valid URL".format(cs)) html = json.load(urlopen(BASE_URL.format(API_URL.format(urlquote(cs.partial_url)))))["parse"]["text"]["*"] try: h2 = ( node for node in BeautifulSoup(html).find_all("h2") if node.find("span", "mw-headline") != None and node.find(text=card_list_h2) != None ).next() rows = ( node.find_all("tr") for node in h2.next_siblings if not isinstance(node, NavigableString) and node.find("b") != None and node.find("b").find(text=cs.name) != None ).next() except StopIteration: self.stdout.write("'{0}' does not have any valid cards\n".format(cs.name)) continue cs.card_set.all().delete() for tr in rows: td = tr.find("td") if td is not None and td != -1: match = card_no.match(td.text) if match != None and int(match.group("count")) == cs.official_count: node = td.next_sibling.next_sibling name_node = node.next_sibling.next_sibling type_node = name_node.next_sibling.next_sibling rarity_node = type_node.next_sibling.next_sibling if rarity_node.a is None and rarity_node.a != -1: rarity_name = "None" else: rarity_name = rarity_node.a["title"].strip() rarity, created = Rarity.objects.get_or_create(name=rarity_name) if created and rarity_node.a != None and rarity_node.a.img != None: logo_temp = NamedTemporaryFile() rarity_url = rarity_node.a.img["src"] logo_temp.write(urlopen(rarity_url).read()) logo_ext = urlparse(rarity_url).path.split(".")[-1] logo_filename = "{0}.{1}".format(str(rarity.id), logo_ext) logo_temp.flush() rarity.logo.save(logo_filename, File(logo_temp)) if type_node.a is not None and type_node.a != -1: card_type_name = type_node.a["title"].strip() t_match = energy_type.match(card_type_name) if t_match != None: card_type_name = t_match.group("energy_type") elif ( type_node.img is not None and type_node.img != -1 and type_node.img["alt"] == "Dragon-attack.png" ): card_type_name = "Dragon" else: try: card_type_name = CARD_TYPE_MAP[type_node.text.strip()] except KeyError: self.stderr.write("Unrecognised type {0}".format(str(type_node))) card_type, created = CardType.objects.get_or_create(name=card_type_name) if created and type_node.a != None and type_node.a.img != None: logo_temp = NamedTemporaryFile() card_type_url = type_node.a.img["src"] logo_temp.write(urlopen(card_type_url).read()) logo_ext = urlparse(card_type_url).path.split(".")[-1] logo_filename = "{0}.{1}".format(str(card_type.id), logo_ext) logo_temp.flush() card_type.logo.save(logo_filename, File(logo_temp)) card = Card( card_no=match.group("card_no"), card_set=cs, name=name_node.text.encode("utf-8").strip(), card_type=card_type, rarity=rarity, ) if name_node.a is not None and name_node.a != -1: card.url = BASE_URL.format(name_node.a["href"][1:]) card.save() self.stdout.write( "{0}/{1} - {2} ({3})\n".format( str(card.card_no), str(cs.official_count), card.name, cs.name ) ) self.stdout.write("total cards {0}\n".format(str(cs.card_set.all().count())))
def create_test_card(fields: dict) -> Card: """ Creates a test card with fields from the given dict :param fields: The fields to populate :return: A card object """ card = Card() card.name = 'undefined' card.cmc = 0 card.num_power = 0 card.num_toughness = 0 card.num_loyalty = 0 card.colour_count = 0 card.colour_sort_key = 0 card.colour_weight = 0 card.is_reserved = False for key, value in fields.items(): card.__dict__[key] = value card.save() return card
from cards.models import Card Mlist = ['Nayeon', 'Jeongyeon', 'Momo', 'Sana', 'Jihyo', 'Mina', 'Dahyun', 'Chaeyoung', 'Tzuyu'] for member in Mlist: c = Card(number=91+Mlist.index(member), member=member, piece=0, album="More & more") c.save()
def test_leaderboard_showing_oracle(self): good_card = Card(name='Inaction Injunction',elo=9999,votes=1000) good_card.save() response = self.client.get('/leaderboard/') return self.assertContains(response, 'Detain')
def xls2sql(source_path, source_file): har = source_file.split('.')[:1][0] # значение характеристики позиции, источник-имя файла rb = xlrd.open_workbook("%s\%s" % (source_path, source_file)) sheet = rb.sheet_by_index(0) #предотвращаем дублирование записей # sql="SELECT `har`,`decimal` FROM `cards` WHERE `har`=%d" % har # cursor.execute(sql) # data = cursor.fetchall() data = Card.objects.filter(Har=har) sDecimal = [x['Decimal'] for x in data.distinct().values('Decimal')]#составляем список децимальный номеров, которые есть в БД fields = sheet.row_values(0) for rownum in range(1, sheet.nrows): row = sheet.row_values(rownum) if row[1] and row[5]: # поля Имя и дата не должны быть пустыми DecMore = "" fullDecimal = "" #проверка входнных данных try: row[0] = '%03d' % int(row[0]) fullDecimal = row[0] for i in range(2, 4): if not row[i]: ErrorInLog('[%s.%s]:поле %s пусто\n'.decode('utf-8') % (har, row[0], fields[i])) except ValueError, err: # если децималный номер нестандартный pat = re.compile(r"^(\d{1,3})((-|\.).*)") # патерн для рег. выражения. 2ая группа - допустимые символы # после которых идет дополнительная часть reResult = pat.match(row[0]) fullDecimal = row[0] if reResult: # Если децимальный номер не валидный то row[0] = reResult.group(1) # разделяем децимальный номер на валидную часть DecMore = reResult.group(2) # и не валидную else: ErrorInLog('[%s.%s]:%s\n'.decode('utf-8') % (har, row[0], err)) # проверяем есть ли совпаедния с БД if not fullDecimal in [("%03d" % validDecimal) + DecMore.strip() for validDecimal in sDecimal]: try: row[5] = convertExcelTime(row[5], source_file) except TypeError: ErrorInLog(u'[%s.%s]:Ошибка заполнения времени %s' % (har, row[0], row[5])) if unicode(row[2]).strip: xlsProject = Project.objects.get_or_create(Name=row[2]) else: xlsProject = 'Не указан' xlsDeveloper = Developer.objects.get_or_create(Name=row[3], defaults={ 'Devision': Devision.objects.get_or_create(Name='КО')[ 0]}) try: save = Card(Har=har.encode('utf-8'), Decimal=row[0], DecimalMore=DecMore, Name=row[1].encode('utf-8'), Project=xlsProject[0], Developer=xlsDeveloper[0], CreatingDate=row[5]) save.save() except ValueError, ValidationError: logFile = open(LOG_FILE, 'a') logFile.write('[%s.%s]:Ошибка ввода в БД' % (har, row[0])) print '[%s.%s]:Ошибка ввода в БД' % (har, row[0]) logFile.close() except:
def handle(self, *args, **options): all_sets = CardSet.objects.all() if len(all_sets) == 0: raise CommandError(NO_CARDSETS) if len(args) == 1: sets = CardSet.objects.filter(name__icontains=args[0], country="GB") if len(sets) < 1: raise CommandError(NO_SETS_FOUND.format(args[0], "\n".join([str(cs) for cs in all_sets]))) else: sets = CardSet.objects.filter(country="GB") self.stdout.write("found card sets {0}\n".format( ", ".join([str(cs) for cs in sets]))) self.stdout.write("Started Scrape command\n") card_no = re.compile("\s*(?P<card_no>\d+)/(?P<count>\d+)\s*") card_list_h2 = re.compile("((C|c)ard (L|l)ist(s)*)|(Setlist)") energy_type = re.compile( "(?P<energy_type>\w+) Energy \(((TCG)|(Basic))\)") for cs in sets: self.stdout.write("Processing '{0}'\n".format(cs.name)) if cs.partial_url is None or cs.partial_url == "": raise CommandError("{0} does not have a valid URL".format(cs)) html = json.load(urlopen( BASE_URL.format( API_URL.format( urlquote(cs.partial_url)))))['parse']['text']['*'] try: h2 = (node for node in BeautifulSoup(html).find_all("h2") if node.find("span", "mw-headline") != None and node.find(text=card_list_h2) != None).next() rows = (node.find_all("tr") for node in h2.next_siblings if not isinstance(node, NavigableString) and node.find("b") != None and node.find("b").find(text=cs.name) != None).next() except StopIteration: self.stdout.write( "'{0}' does not have any valid cards\n".format(cs.name)) continue cs.card_set.all().delete() for tr in rows: td = tr.find("td") if td is not None and td != -1: match = card_no.match(td.text) if match != None \ and int(match.group("count")) == cs.official_count: node = td.next_sibling.next_sibling name_node = node.next_sibling.next_sibling type_node = name_node.next_sibling.next_sibling rarity_node = type_node.next_sibling.next_sibling if rarity_node.a is None and rarity_node.a != -1: rarity_name = "None" else: rarity_name = rarity_node.a['title'].strip() rarity, created = Rarity.objects.get_or_create( name=rarity_name) if created and rarity_node.a != None \ and rarity_node.a.img != None: logo_temp = NamedTemporaryFile() rarity_url = rarity_node.a.img['src'] logo_temp.write(urlopen(rarity_url).read()) logo_ext = urlparse(rarity_url).path.split('.')[-1] logo_filename="{0}.{1}".format(str(rarity.id), logo_ext) logo_temp.flush() rarity.logo.save(logo_filename, File(logo_temp)) if type_node.a is not None and type_node.a != -1: card_type_name = type_node.a['title'].strip() t_match = energy_type.match(card_type_name) if t_match != None: card_type_name = t_match.group("energy_type") elif type_node.img is not None and type_node.img != -1 \ and type_node.img['alt'] == "Dragon-attack.png": card_type_name = "Dragon" else: try: card_type_name = CARD_TYPE_MAP[ type_node.text.strip()] except KeyError: self.stderr.write( "Unrecognised type {0}".format( str(type_node))) card_type, created = CardType.objects.get_or_create( name=card_type_name) if created and type_node.a != None \ and type_node.a.img != None: logo_temp = NamedTemporaryFile() card_type_url = type_node.a.img['src'] logo_temp.write(urlopen(card_type_url).read()) logo_ext = urlparse(card_type_url ).path.split('.')[-1] logo_filename="{0}.{1}".format(str(card_type.id), logo_ext) logo_temp.flush() card_type.logo.save(logo_filename, File(logo_temp)) card = Card(card_no=match.group("card_no"), card_set=cs, name=name_node.text.encode('utf-8').strip(), card_type=card_type, rarity=rarity) if name_node.a is not None and name_node.a != -1: card.url = BASE_URL.format(name_node.a['href'][1:]) card.save() self.stdout.write("{0}/{1} - {2} ({3})\n".format( str(card.card_no), str(cs.official_count), card.name, cs.name)) self.stdout.write("total cards {0}\n".format( str(cs.card_set.all().count())))
def create(request): card = Card() context = { 'selected': True, } return render(request, 'create.html', context)
def test_sorting_is_working(self): good_card = Card(name='Inaction Injunction',elo=9999,votes=1000) good_card.save() response = self.client.get('/leaderboard/') first_card = response.context['cards'][0] return self.assertEqual(first_card.name,'Inaction Injunction')