Example #1
0
def get_characters(page):
    if request.method == 'POST':
        key_type = request.form.get('type')
        value = request.form.get('filter')
        if value == "":
            return render_template('characters.html',
                                   character=paginate(page),
                                   filtered=True,
                                   page=page)
        if key_type == "films":
            character = Character.objects(films__icontains=value)
        elif key_type == "starships":
            character = Character.objects(starships__icontains=value)
        elif key_type == "vehicles":
            character = Character.objects(vehicles__icontains=value)
        elif key_type == "planets":
            character = Character.objects(planets__icontains=value)

        return render_template('characters.html',
                               character=character,
                               filtered=True,
                               page=page)

    return render_template('characters.html',
                           character=paginate(page),
                           filtered=False,
                           page=page)
Example #2
0
def character_profile():
    form = CharacterCreationForm()
    if request.method == 'GET':
        char = flask_login.current_user.character
        if char is None:
            return render_template('character_profile.html',form=form)    
        else:
            char.update_character()
            return render_template('character_profile.html',character=char)
    elif request.method == 'POST':
        if form.validate_on_submit():
            if Character.query.filter_by(name=form.name.data).first():
                flash('Character name already in use. Try again.','error')
                return redirect(url_for('character_profile'))
            else:
                character = Character(name=form.name.data)
                character.title = 'the newly landed'
                character.location = Room.query.filter_by(name='The Red Death').first()
                db.session.add(character)
                flask_login.current_user.character = character
                db.session.add(flask_login.current_user)
                db.session.commit()
                generate_starter_equipment(character)
                flash('Character created! Welcome to Deimos 2147!','error')
                return redirect(url_for('character_profile'))
        else:
            flash('Failed to validate form','error')
            return redirect(url_for('character_profile'))
Example #3
0
    def post_character(jwt):
        body = request.get_json()
        try:
            name = body.get('name')
            fighting = body.get('fighting')
            intelligence = body.get('intelligence')
            good = body.get('good')
            new_game_id = body.get('game_id')
            print("1")

            character = Character(name=name,
                                  fighting=fighting,
                                  intelligence=intelligence,
                                  good=good,
                                  game_id=new_game_id)
            print("2")
            character.insert()
            print("3")
            return jsonify({
                'success': True,
                'character_id': character.id,
                'character_name': character.name
            })
        except:
            abort(400)
Example #4
0
def index():
    party = Party(name='Dungeons and Databases')
    characters = [
        2342595, 2266180, 2790689, 5304380, 6448988, 2278224, 4657425, 2271732
    ]
    members = []
    for character in characters:
        try:
            data = get_character_health(character_id=character)
            members.append(
                Character(character, data['name'], 0, 0, data['current_hp'],
                          data['health_status']))
            cache.set(character, data, timeout=100 * 60)
        except ThrottlingException as e:
            data = cache.get(character)
            if data is None:
                flash(
                    "D&D Beyond throttled us and charcter_id {} was not already cached."
                    .format(character), 'danger')
            else:
                members.append(
                    Character(character, data['name'], 0, 0,
                              data['current_hp'], data['health_status']))
                flash(
                    "ThrottlingException from D&D Beyond, retrieving {} from cache"
                    .format(data['name']), 'warning')
    for char in sorted(members, key=lambda x: x.name):
        party.add(char)
    return render_template('main.html', entries=party)
Example #5
0
    def test_character_add_two_count(self):
        # add two characters, validate count
        num_characters = self.session.query(Character).count()

        character_one = Character(name='Snorlax',
                                  universe='Pokemon',
                                  weight='180',
                                  moves='Rollout, Belly Drum, Heavy Slam, Yawn',
                                  debut='2004',
                                  tier='E',
                                  image_path='Snorlax.png')

        character_two = Character(name='Sonic',
                                  universe='Sonic',
                                  weight='95',
                                  moves='Hammer Spin Dash, Burning Spin Dash, Spring Jump, Springing Headbutt',
                                  debut='2013',
                                  tier='A',
                                  image_path='Sonic.png')

        self.object_list.append(character_one)
        self.object_list.append(character_two)

        self.commit_objects()

        self.assertEqual(
            self.session.query(Character).count(), num_characters + 2)
Example #6
0
def investigate(request):
    # rlt = request.GET["staff"]
    # return HttpResponse(rlt)

    # ctx = {}
    # ctx.update(csrf(request))
    # if request.POST:
    #     ctx["rlt"] = request.POST["staff"]
    # return render(request, "investigate.html", ctx)

    # if request.POST:
    #     submitted = request.POST["staff"]
    #     newRecord = Character(name=submitted)
    #     newRecord.save()
    # ctx = {}
    # ctx.update(csrf(request))
    # allRecords = Character.objects.all()
    # ctx["staff"] = allRecords
    # return render(request, "investigate.html", ctx)

    if request.POST:
        recvForm = CharacterForm(request.POST)
        if recvForm.is_valid():
            submitted = recvForm.cleaned_data["name"]
            newRecord = Character(name=submitted)
            newRecord.save()
    recvForm = CharacterForm()
    ctx = {}
    ctx.update(csrf(request))
    allRecords = Character.objects.all()
    ctx["staff"] = allRecords
    ctx["form"] = recvForm
    return render(request, "investigate.html", ctx)
Example #7
0
 def oppose(self, args, channel, exchange, user):
     messages = []
     if len(args) == 1:
         raise Exception('No opposition added')
     if not exchange:
         raise Exception('You don\'t have an active exchange. Try this:```css\n.d new exchange "EXCHANGE NAME"```')
     elif args[1].lower() == 'list' or args[1].lower() == 'l':
         return [exchange.get_string_opposition(channel)]
     elif args[1].lower() in ['delete','d']:
         for char_name in args[2:]:
             char = Character().find(user=user, name=char_name, guild=channel.guild, category='Character')
             [exchange.opposition.remove(s) for s in exchange.opposition if char and str(char.id) == s]
             messages.append(f'***{char.name}*** removed from the opposition in _{exchange.name}_' if char else f'**{char_name}** was not found')
         self.save(exchange, user)
         messages.append(exchange.get_string_opposition(user))
         return messages
     else:
         for char_name in args[1:]:
             char = Character().find(user=None, name=char_name, guild=channel.guild, category='Character')
             if char:
                 if str(char.id) in exchange.opposition:
                     messages.append(f'***{char.name}*** is already in the opposition in the _{exchange.name}_ exchange')
                 else:
                     exchange.opposition.append(str(char.id))
                     messages.append(f'Added ***{char.name}*** to the opposition in the _{exchange.name}_ exchange')
             else:
                 messages.append(f'***{char_name}*** not found. No opposition added to _{exchange.name}_')
         self.save(exchange, user)
         messages.append(exchange.get_string_opposition(user))
         return messages
Example #8
0
    def create_character(payload):
        body = request.get_json()
        first_name = body.get('first_name', None)
        last_name = body.get('last_name', None)
        char_class_id = body.get('char_class_id', None)
        race_id = body.get('race_id', None)
        try:
            race = Race.query.get(race_id)
            char_class = Char_class.query.get(char_class_id)
            new_character = Character(
                first_name=first_name,
                last_name=last_name,
                char_class_id=char_class_id,
                race_id=race_id,
                strength=race.strength_bonus + char_class.strength_bonus +
                STAT_BASE,
                speed=race.speed_bonus + char_class.speed_bonus + STAT_BASE,
                will=race.will_bonus + char_class.will_bonus + STAT_BASE)
            new_character.insert()
            character_list = format_list(Character.query.all())

            return jsonify({
                'success': True,
                'created_id': new_character.id,
                'character_list': character_list,
                'number_of_characters': len(character_list)
            })
        except BaseException:
            abort(422)
Example #9
0
def update_characters(user):
    try:
        for apikey in user.account.apikeys.all():
            Character.update_from_api(apikey)
    except SoftTimeLimitExceeded:
        for apikey in user.account.apikeys.all():
            Character.update_from_api(apikey)
Example #10
0
def insert_chars_from_guild(realm, guild_name, chars_to_scan):
    data = load_json_from_url(GUILD_API_URL.format(region=realm.region, realm=realm.name, guild_name=guild_name))

    # sometimes api returns error for a valid guild name
    try:
        members = data["members"]
    except KeyError:
        logging.exception("No data return for guild name: %s, realm: %s" % (guild_name, realm.name))
        return

    for member in members:
        name = member["character"]["name"]

        # sometimes there is a character without realm. Possibly because it was deleted/transferred/renamed recently
        realm_name = member["character"].get("realm")
        if realm_name is None:
            continue

        realm = get_realm(realm.region, realm.name)
        char = Character()
        char.name = name
        char.realm = realm
        char.retrieve_guild = False
        if not session.query(Character).filter(Character.name == char.name,
                                               Character.realm == char.realm).first() and char not in session:
            session.add(char)
            chars_to_scan.append(char)
    session.commit()
Example #11
0
 def player(self, args, channel, zone, user):
     messages = []
     if len(args) == 1:
         raise Exception('No characters added')
     if not zone:
         raise Exception('You don\'t have an active zone. Try this:```css\n.d new zone "ZONE NAME"```')
     elif args[1].lower() == 'list' or args[1].lower() == 'l':
         return [zone.get_string_characters(channel)]
     elif args[1].lower() in ['delete','d']:
         for char_name in args[2:]:
             char = Character().filter(id__in=zone.characters, name=char_name, guild=channel.guild, category='Character', archived=False).first()
             [zone.characters.remove(s) for s in zone.characters if char and str(char.id) == s]
             messages.append(f'***{char.name}*** removed from _{zone.name}_' if char else f'**{char_name}** was not found')
         self.save(zone, user)
         messages.append(zone.get_string_characters(user))
         return messages
     else:
         for char_name in args[1:]:
             char = Character().find(user=None, name=char_name, guild=channel.guild, category='Character')
             if char:
                 if str(char.id) in zone.characters:
                     messages.append(f'***{char.name}*** is already in _{zone.name}_')
                 else:
                     zone.characters.append(str(char.id))
                     messages.append(f'Added ***{char.name}*** to _{zone.name}_ zone')
             else:
                 messages.append(f'***{char_name}*** not found. No character added to _{zone.name}_')
         self.save(zone, user)
         messages.append(zone.get_string_characters(user))
         return messages
Example #12
0
def test_character_creation_ht_in_constraint(database):
    with pytest.raises(IntegrityError) as excinfo:
        with database.transaction():
            # Create character with height in inches greater than 11
            character1 = Character.create(character_name='Qritz1',
                                          player_name='Avery',
                                          alignment='CG',
                                          race='elf',
                                          size='md',
                                          gender='male',
                                          age='29',
                                          height_ft='5',
                                          height_in='12',
                                          weight='109',
                                          hair_color='black',
                                          eye_color='brown')
    assert 'CHECK constraint failed: character' in str(excinfo.value)

    with pytest.raises(IntegrityError) as excinfo:
        with database.transaction():
            # Create character with height in inches greater less than 0
            character2 = Character.create(character_name='Qritz2',
                                          player_name='Avery',
                                          alignment='CG',
                                          race='elf',
                                          size='md',
                                          gender='male',
                                          age='29',
                                          height_ft='5',
                                          height_in='-1',
                                          weight='109',
                                          hair_color='black',
                                          eye_color='brown')
    assert 'CHECK constraint failed: character' in str(excinfo.value)
Example #13
0
 def characters_delete(id: int):
     if not auth.is_authorized():
         return redirect('/login')
     character = Character.query.filter_by(id=id).first()
     if character.user_id != auth.get_user().id:
         abort(403)
     Character.delete(character)
     return redirect('/characters')
Example #14
0
def result():
    char_json = json.loads('{"name":"Lucca Redframe","title":"None (8 titles unlocked)","sex":"male","vocation":"Elite Knight","level":228,"achievement_points":151,"world":"Zenobra","residence":"Thais","house":{"name":"Treetop 13","town":"Ab\'Dendriel","paid":"2021-03-05","world":"Zenobra","houseid":0},"guild":{"name":"Zenobra Pune","rank":"One"},"last_login":[{"date":"2021-02-08 11:18:02.000000","timezone_type":2,"timezone":"CET"}],"account_status":"Premium Account","status":"offline"}')
    char = Character(json=char_json)
    char.online_time = '154h 15min'
    char.kills.append(Frag(date=datetime(2021, 1, 12, 4, 52), target_name='Dell Brega', target_level=100, frag_type='injustified', is_kill=True))
    char.kills[-1].add_killer('Lucca Redframe', 200)
    char.kills.append(Frag(date=datetime(2021, 1, 12, 4, 24), target_name='Dell Brega', target_level=100, frag_type='injustified', is_kill=True))
    char.kills[-1].add_killer('Lucca Redframe', 200)
    char.kills.append(Frag(date=datetime(2021, 1, 12, 4, 7), target_name='Lius lambinha', target_level=19, frag_type='justified', is_kill=True))
    char.kills[-1].add_killer('Lucca Redframe', 20)

    char.deaths.append(Frag(date=datetime(2021, 1, 12, 4, 58), target_name='Lucca Redframe', target_level=200, frag_type='injustified', is_kill=False))
    char.deaths[-1].add_killer('Lambinha delas', 800)
    char.deaths.append(Frag(date=datetime(2021, 1, 12, 4, 42), target_name='Lucca Redframe', target_level=200, frag_type='injustified', is_kill=False))
    char.deaths[-1].add_killer('Lambinha delas', 800)
    char.deaths.append(Frag(date=datetime(2021, 1, 12, 4, 33), target_name='Lucca Redframe', target_level=200, frag_type='injustified', is_kill=False))
    char.deaths[-1].add_killer('Lambinha delas', 800)
    char.deaths.append(Frag(date=datetime(2021, 1, 12, 4, 15), target_name='Lucca Redframe', target_level=210, frag_type='justified', is_kill=False))
    char.deaths[-1].add_killer('Lambe lambe', 1000)

    char.kills.append(Frag(date=datetime(2021, 2, 11, 4, 51), target_name='Dell Brega', target_level=100, frag_type='injustified', is_kill=True))
    char.kills[-1].add_killer('Lucca Redframe', 200)
    char.kills.append(Frag(date=datetime(2021, 2, 11, 4, 22), target_name='Dell Brega', target_level=100, frag_type='injustified', is_kill=True))
    char.kills[-1].add_killer('Lucca Redframe', 200)
    char.kills.append(Frag(date=datetime(2021, 2, 11, 4, 4), target_name='Lius lambinha', target_level=19, frag_type='justified', is_kill=True))
    char.kills[-1].add_killer('Lucca Redframe', 20)

    char.deaths.append(Frag(date=datetime(2021, 2, 11, 4, 57), target_name='Lucca Redframe', target_level=200, frag_type='injustified', is_kill=False))
    char.deaths[-1].add_killer('Lambinha delas', 800)
    char.deaths.append(Frag(date=datetime(2021, 2, 11, 4, 44), target_name='Lucca Redframe', target_level=200, frag_type='injustified', is_kill=False))
    char.deaths[-1].add_killer('Lambinha delas', 800)
    char.deaths.append(Frag(date=datetime(2021, 2, 11, 4, 33), target_name='Lucca Redframe', target_level=200, frag_type='injustified', is_kill=False))
    char.deaths[-1].add_killer('Lambinha delas', 800)
    char.deaths.append(Frag(date=datetime(2021, 2, 11, 4, 11), target_name='Lucca Redframe', target_level=210, frag_type='justified', is_kill=False))
    char.deaths[-1].add_killer('Lambe lambe', 1000)

    char.kills.append(Frag(date=datetime(2021, 2, 10, 4, 57), target_name='Dell Brega', target_level=100, frag_type='injustified', is_kill=True))
    char.kills[-1].add_killer('Lucca Redframe', 200)
    char.kills.append(Frag(date=datetime(2021, 2, 10, 4, 29), target_name='Dell Brega', target_level=100, frag_type='injustified', is_kill=True))
    char.kills[-1].add_killer('Lucca Redframe', 200)
    char.kills.append(Frag(date=datetime(2021, 2, 10, 4, 5), target_name='Lius lambinha', target_level=19, frag_type='justified', is_kill=True))
    char.kills[-1].add_killer('Lucca Redframe', 20)

    char.deaths.append(Frag(date=datetime(2021, 2, 10, 4, 59), target_name='Lucca Redframe', target_level=200, frag_type='injustified', is_kill=False))
    char.deaths[-1].add_killer('Lambinha delas', 800)
    char.deaths.append(Frag(date=datetime(2021, 2, 10, 4, 49), target_name='Lucca Redframe', target_level=200, frag_type='injustified', is_kill=False))
    char.deaths[-1].add_killer('Lambinha delas', 800)
    char.deaths.append(Frag(date=datetime(2021, 2, 10, 4, 30), target_name='Lucca Redframe', target_level=200, frag_type='injustified', is_kill=False))
    char.deaths[-1].add_killer('Lambinha delas', 800)
    char.deaths.append(Frag(date=datetime(2021, 2, 10, 4, 15), target_name='Lucca Redframe', target_level=210, frag_type='justified', is_kill=False))
    char.deaths[-1].add_killer('Lambe lambe', 1000)

    char.frags.extend(char.kills)
    char.frags.extend(char.deaths)
    char.frags.sort(key=lambda x: x.date, reverse=True)
    char.process_presences()

    return render_template('result.html', chars=[char, char, char])
Example #15
0
File: app.py Project: MChrys/Metron
    def add():
        '''
        Description :
            Create a new Character with Hat associate, following the rules
        Example :
            >>> request.post(/create?Name=Alain&Age=18&Weight=80
            /   &Human=True&Color=YELLOW)

        '''

        from rules import Character_rules

        character_schema = CharacterSchema()

        Name=request.args.get('Name')
        Age=request.args.get('Age')
        Weight=request.args.get('Weight')
        Human= json.loads(request.args.get('Human').lower())

        if 'Color' in request.args:
            from models import ColorHat, Hat

            Color = request.args.get('Color')
            hat = Hat(Color = Color)
            hat_schema = HatSchema()
            params = {
                'Name' : Name,
                'Age' : Age,
                'Weight' : Weight ,
                'Human' : Human,
                'Hat' : hat
            }
            
            #hat = hat_schema.load({'Color' : Color})
            result_hat = hat_schema.dump(hat.create())

        else:
            params = {
                'Name' : Name,
                'Age' : Age,
                'Weight' : Weight ,
                'Human' : Human,
                'Hat': None
            }
        #Check all the rules
        message = [rule(params) for k,rule in Character_rules.items() ]
        for b, m  in message :
            if not(b):
                return make_response(m,401)
        try:
            #character = character_schema.load(params)
            character = Character(**params)
            result_character = character_schema.dump(character.create())
            return make_response(jsonify({'character': result_character}),200)

        except Exception as e:
            raise str(e) 
Example #16
0
def get_character_mail(character_id, last_mail_id=None, current_user=None):
    target_character = Character.get(character_id)
    character_application_access_check(current_user, target_character)
    if last_mail_id:
        kwargs = {'last_mail_id': last_mail_id}
    else:
        kwargs = {}
    mail_list = target_character.get_op('get_characters_character_id_mail',
                                        character_id=character_id,
                                        **kwargs)

    from_ids = set(entry['from'] for entry in mail_list)
    if from_ids:
        character_ids = set()
        corp_ids = set()
        alliance_ids = set()
        mailing_list_ids = set()
        id_set_dict = {
            'character': character_ids,
            'corporation': corp_ids,
            'alliance': alliance_ids,
            'mailing_list': mailing_list_ids,
        }
        name_data = get_from_names(list(from_ids))
        for entry in name_data:
            id_set_dict[entry['category']].add(entry['id'])
        for entry in mail_list:
            for recipient in entry['recipients']:
                id_set_dict[recipient['recipient_type']].add(
                    recipient['recipient_id'])

        characters = Character.get_multi(character_ids)
        corporations = Corporation.get_multi(corp_ids)
        alliances = Alliance.get_multi(alliance_ids)
        all_parties = {}
        all_parties.update(characters)
        all_parties.update(corporations)
        all_parties.update(alliances)
        for id in mailing_list_ids:
            all_parties[id] = MailingList('Mailing List {}'.format(id))

    for entry in mail_list:
        entry['redlisted'] = []
        entry['from_name'] = all_parties[entry['from']].name
        recipients_redlisted = False
        for recipient in entry['recipients']:
            recipient['recipient_name'] = all_parties[
                recipient['recipient_id']].name
            if all_parties[recipient['recipient_id']].is_redlisted:
                recipient['redlisted'] = ['recipient_name']
            else:
                recipient['redlisted'] = []
        if recipients_redlisted:
            entry['redlisted'].append('recipients')
        if all_parties[entry['from']].is_redlisted:
            entry['redlisted'].append('from_name')
    return {'info': mail_list}
Example #17
0
def initDbForE2e(wipe=True):

    if wipe:
        clearDB()

    # TODO: Id of user a
    admin_id = 123

    db.session.add(
        Character(
            id=admin_id,
            user_id=admin_id,
            name='ADMIN NAME',
            corporation_id=ascee_corp_id,
            refresh_token='YOUR TOKEN HERE',
        ))
    db.session.add(Admin(
        id=admin_id,
        user_id=admin_id,
        name='Billy Admin',
    ))

    # TODO: Id of recruiter user
    recruiter_id = 345

    db.session.add(
        Character(id=recruiter_id,
                  user_id=recruiter_id,
                  name='RECRUITER NAME',
                  corporation_id=ascee_corp_id,
                  refresh_token='YOUR TOKEN HERE'))
    db.session.add(Recruiter(
        id=recruiter_id,
        name='RECRUITER NAME',
    ))

    # TODO: Id of applicant user
    character_id = 234

    db.session.add(
        Character(id=character_id,
                  user_id=character_id,
                  name='APPLICANT NAME',
                  corporation_id=ascee_corp_id,
                  corporation=Corporation(id=ascee_corp_id, name='ASCEE'),
                  refresh_token='YOUR TOKEN HERE'))
    db.session.add(User(
        id=character_id,
        name='APPLICANT NAME',
    ))

    db.session.add(Question(text='How long have you been playing Eve?'))
    db.session.add(Question(text='PVP or PVE? Why?'))

    db.session.add(Application(user_id=character_id))
    db.session.commit()
Example #18
0
def select():
    #Run as soon as the page is grabbed
    if request.method == 'GET':
        #Build the Boss out of the twiter bots
        boss = twitter.build_a_boss()
        #Give the boss its stats
        boss.set_stats(boss, boss.name)

        #Get the database
        get_db()

        #Create boss entry in the character SQL table (Use SQLAlchemy-flask)
        b1 = Character(title='boss',
                       health=200,
                       name=boss.name,
                       desc=boss.flavour,
                       pwr=boss.pwr,
                       spd=boss.spd,
                       intel=boss.int,
                       appearance=boss.appearance)  #TODO debug this
        finalbots_db.session.add(b1)
        finalbots_db.session.commit()

    #Run when player presses "Submit"
    if request.method == 'POST' and 'class' in request.form:
        session['class'] = request.form.get('class')

        #Create player entry in the Character SQL table
        if session['class'] == 'warrior':
            p1 = Character(title='player1',
                           health=100,
                           pwr=15,
                           spd=10,
                           intel=5)
        elif session['class'] == 'mage':
            p1 = Character(title='player1',
                           health=100,
                           pwr=5,
                           spd=10,
                           intel=15)
        elif session['class'] == 'thief':
            p1 = Character(title='player1',
                           health=100,
                           pwr=5,
                           spd=15,
                           intel=10)

        # Add and commit to db
        finalbots_db.session.add(p1)
        finalbots_db.session.commit()

        #proceeed to the choose action page
        return redirect(url_for('finalbots.choose'))

    return render_template('game/creation.html')
Example #19
0
    def test_participants_add_two_count(self):
        # add two/more participants, assert the number of participants
        num_participants = self.session.query(Participant).count()
        character_one = Character(name='Snorlax',
                                  universe='Pokemon',
                                  weight='180',
                                  moves='Rollout, Belly Drum, Heavy Slam, Yawn',
                                  debut='2004',
                                  tier='E',
                                  image_path='Snorlax.png')

        character_two = Character(name='Sonic',
                                  universe='Sonic',
                                  weight='95',
                                  moves='Hammer Spin Dash, Burning Spin Dash, Spring Jump, Springing Headbutt',
                                  debut='2013',
                                  tier='A',
                                  image_path='Sonic.png')

        tournament_one = Tournament(name='bust2',
                                    sanitized='bust2',
                                    date='April 11th, 2015',
                                    location='CA',
                                    image_path='https://images.smash.gg/images/tournament/1035/image-10e39229043ff962dd367a516b0bc090.png')

        tournament_two = Tournament(name='Smash Broski',
                                    sanitized='smash-broski',
                                    date='April 1, 2017',
                                    location='MA',
                                    image_path='path_to_image')

        participant_one = Participant(sponsor='C9',
                                      tag='mang0',
                                      main=character_one,
                                      location='California',
                                      tournament=tournament_one)

        participant_two = Participant(sponsor='Selfless',
                                      tag='Broseidon',
                                      main=character_two,
                                      location='Russia',
                                      tournament=tournament_two)

        self.object_list.append(character_one)
        self.object_list.append(character_two)
        self.object_list.append(tournament_one)
        self.object_list.append(tournament_two)
        self.object_list.append(participant_one)
        self.object_list.append(participant_two)

        self.commit_objects()

        self.assertEqual(self.session.query(Participant).count(),
                         num_participants + 2)
Example #20
0
def add_character():

    # recibir info del request
    request_body = request.get_json()
    print(request_body)

    new_character = Character(name=request_body["name"], birth_year=request_body["birth_year"], height=request_body["height"], mass=request_body["mass"],
        hair_color=request_body["hair_color"], eye_color=request_body["eye_color"], gender=request_body["gender"], planet_id=request_body["planet_id"])
    
    db.session.add(new_character)
    db.session.commit()

    return jsonify("All good, added: ", new_character.serialize()), 200
Example #21
0
def create_characters():
    with open("../anapioficeandfire/characters.json") as char_file:
        characters = json.load(char_file)

    for d in characters:
        id = d["url"].split("/").pop()
        name = d["name"]
        gender = d["gender"]
        culture = d["culture"]
        born = d["born"]
        died = d["died"]
        father = d["father"]
        mother = d["mother"]

        c = Character.query.get(id)
        if not c:
            c = Character(
                id=id, name=name, gender=gender, culture=culture, born=born,
                died=died, father=father, mother=mother)
        else:
            c.name = name
            c.gender = gender
            c.culture = culture
            c.born = born
            c.died = died
            c.father = father
            c.mother = mother

        create_rel_spouse(c, d["spouse"])
        create_rel_allegiances(c, d["allegiances"])
        create_rel_books(c, d["books"])
        create_rel_povbooks(c, d["povBooks"])

        db.session.add(c)
        print(c)
Example #22
0
def investigate(request):
    if request.POST:
        form = CharacterForm(request.POST)
        if form.is_valid():
            submitted = form.cleaned_data['name']
            new_record = Character(name=submitted)
            new_record.save()
    form = CharacterForm
    ctx = dict()
    ctx.update(csrf(request))
    all_record = Character.objects.all()
    ctx['staff'] = all_record
    ctx['form'] = form
    return render(request, 'west/investigate.html', ctx)
Example #23
0
def api_admin_refresh_db():
    """
    Refreshes database entities using ESI.

    Returns:
        {'status': 'ok'}

    Error codes:
        Forbidden (403): If logged in user is not an admin
    """
    user_admin_access_check(current_user)
    Corporation.refresh_from_esi()
    Character.refresh_from_esi()
    return jsonify({'status': 'ok'})
Example #24
0
    def get(self):
        # Loading character DB
        char = Character()
        for x in aliases.charlist:
            print x[0]
            print x[1]
            char = Character.get_or_insert(str(x[0]), name=str(x[0]), avatarFile=str(x[1]))
            print char
            char.put()

        for ch in Character.query().order(Character.name).fetch():
            print ch

        get_chars(True)
        self.response.write('Loaded DB')
Example #25
0
def create_character():
    """Creates a new character"""
    if "user_id" not in session:
        flash("Please login first!")
        return redirect('/')

    form = CharacterForm()

    if form.validate_on_submit():
        name = form.name.data
        c_class = form.c_class.data
        race = form.race.data
        background = form.background.data
        equipment = form.equipment.data
        origin = form.origin.data

        character = Character(
        name=name, c_class=c_class, race=race, 
        background=background, equipment=equipment,
        origin=origin, user_id=session['user_id']
        )
        
        db.session.add(character)   
        db.session.commit()
        return redirect('/characters')

    return render_template('new_character.html', form=form)
Example #26
0
def get_character_fittings(character_id, current_user=None):
    character = Character.get(character_id)
    character_application_access_check(current_user, character)
    fitting_data = character.get_op(
        'get_characters_character_id_fittings',
        character_id=character_id,
    )
    types = set()
    for entry in fitting_data:
        types.add(entry['ship_type_id'])
        for item in entry['items']:
            types.add(item['type_id'])
    type_dict = Type.get_multi(list(types))

    for entry in fitting_data:
        entry['redlisted'] = []
        entry['ship_type_name'] = type_dict[entry['ship_type_id']].name
        if type_dict[entry['ship_type_id']].is_redlisted:
            entry['redlisted'].append('ship_type_name')
        items_redlisted = False
        for item in entry['items']:
            item['type_name'] = type_dict[item['type_id']].name
            if type_dict[item['type_id']].is_redlisted:
                item['redlisted'] = ['type_name']
                items_redlisted = True
            else:
                item['redlisted'] = []
        if items_redlisted:
            entry['redlisted'].append('items')
    return {'info': fitting_data}
Example #27
0
    def test_participants_add_one(self):
        # add a participant
        character = Character(name='Snorlax',
                              universe='Pokemon',
                              weight='180',
                              moves='Rollout, Belly Drum, Heavy Slam, Yawn',
                              debut='2004',
                              tier='E',
                              image_path='Snorlax.png')

        tournament = Tournament(name='bust2',
                                sanitized='bust2',
                                date='April 11th, 2015',
                                location='CA',
                                image_path='https://images.smash.gg/images/tournament/1035/image-10e39229043ff962dd367a516b0bc090.png')

        participant = Participant(sponsor='C9',
                                  tag='mang0',
                                  main=character,
                                  location='California',
                                  tournament=tournament)

        self.object_list.append(character)
        self.object_list.append(tournament)
        self.object_list.append(participant)

        self.commit_objects()

        result = self.session.query(Participant).order_by(
            Participant.id.desc()).first()
        self.assertEqual(result.sponsor, participant.sponsor)
        self.assertEqual(result.tag, participant.tag)
        self.assertEqual(result.location, participant.location)
        self.assertEqual(result.tournament, participant.tournament)
Example #28
0
def get_character_skills(character_id, current_user=None):
    character = Character.get(character_id)
    character_application_access_check(current_user, character)
    skill_data = character.get_op(
        'get_characters_character_id_skills',
        character_id=character_id,
    )
    queue_data = character.get_op(
        'get_characters_character_id_skillqueue',
        character_id=character_id,
    )
    for skill_list in skill_data['skills'], queue_data:
        for entry in skill_list:
            skill = Type.get(entry['skill_id'])
            group = Group.get(skill.group_id)
            entry['skill_id'] = {
                'group_name': group.name,
                'skill_name': skill.name,
            }
    return {
        'info': {
            'skills': skill_data['skills'],
            'queue': queue_data,
            'total_sp': skill_data['total_sp']
        }
    }
Example #29
0
def create_character():
    request_body = request.get_json()
    character = Character(name=request_body["name"], birth_year=request_body["birth_year"],  gender=request_body["gender"], height=request_body["height"], mass=request_body["mass"], home_world=request_body["home_world"])
    db.session.add(character)
    db.session.commit()
    print("Character created: ", request_body)
    return jsonify(request_body), 200
Example #30
0
    def get(self,charset_key):
        
        text = self.request.get("text")
        charset = CharacterSet.get(charset_key)
        images = []
        
        if text:
            for character in text:
                
                logging.info(character)
            
                the_character = character.upper()

                character_images_query = Character.all()
                character_images_query.filter("character = ", the_character)
                characters = character_images_query.fetch(1000)
        
                if characters:
                    images.append(choice(characters).image_url)
                
        
        template_vars = {
            "charset":charset,
            "text":text,
            "images":images,
        }

        self.response.out.write(template.render(get_template_path("charset"), template_vars))
Example #31
0
def get_character_corporation_history(character_id, current_user=None):
    character = Character.get(character_id)
    character_application_access_check(current_user, character)
    corporation_list = character.get_op(
        'get_characters_character_id_corporationhistory',
        character_id=character_id,
    )
    for entry in corporation_list:
        entry['is_deleted'] = entry.get('is_deleted', False)
        if entry['is_deleted']:
            entry['corporation_name'] = 'Deleted corp {}'.format(
                entry['corporation_id'])
            entry['alliance_name'] = 'Unknown'
            entry['redlisted'] = []
        else:
            corporation = Corporation.get(entry['corporation_id'])
            entry['corporation_name'] = corporation.name
            if corporation.alliance:
                entry['alliance_name'] = corporation.alliance.name
            else:
                entry['alliance_name'] = None
            redlisted_names = []
            if corporation.is_redlisted:
                redlisted_names.append('corporation_name')
            if corporation.alliance and corporation.alliance.is_redlisted:
                redlisted_names.append('alliance_name')
            if character.is_redlisted:
                redlisted_names.append('character_name')
            entry['redlisted'] = redlisted_names
    return {'info': corporation_list}
Example #32
0
def list_addAll():
    body = request.get_json()
    people = body['character']
    planet = body['planet']
    vehicles = body['starship']

    for c in character:
        character1 = Character(name=c["Character Name"],
                               heigth=c["Character heigth"],
                               mass=c["Character mass"],
                               hair_color=c["Character hair color"],
                               skin_color=c["Character skin color"],
                               gender=c["Character Gender"])
        db.session.add(character1)

    for p in planet:
        planet1 = Planet(name=p["Name"],
                         diameter=p["Diameter"],
                         climate=p["Climate"],
                         gravity=p["Gravity"],
                         population=p["Population"])
        db.session.add(planet1)

    for s in starship:
        starships1 = Starship(name=s["Vehicle name"],
                              model=s["Model"],
                              passengers=serialize["Passengers"],
                              consumable=s["consumable"],
                              cargo_capacity=s["Cargo capacity"],
                              hyperdrive_rating=s["Hyperdrive rating"])
        db.session.add(starship1)

        db.session.commit()
Example #33
0
def add_character(data_list):
    player = Player.objects.get(id=data_list['player'])
    alignment = Alignments(id=data_list['alignment'])
    size = Sizes(id=data_list['size'])
    character = Character(character_name=data_list['character_name'],
                          player=player, size=size, alignment=alignment,
                          gender=data_list['gender'], race=data_list['race'],
                          age=data_list['age'], height=data_list['height'], weight=data_list['weight'],
                          eyes=data_list['eyes'], hair=data_list['hair'], strength_base=data_list['str'],
                          dexterity_base=data_list['dex'], constitution_base=data_list['con'],
                          intelligence_base=data_list['int'], wisdom_base=data_list['wis'],
                          charisma_base=data_list['cha'])
    character.save()
    levels = Levels(character=Character.objects.get(id=character.id), class_name=data_list['class'], levels=1)
    levels.save()
    return character.character_name
Example #34
0
    def post(self):
        messageid = self.request.get("messageid")
        if messageid == "":
            rawCharacter =  cgi.escape(self.request.get("character"), quote = True)
            rawLocation =   cgi.escape(self.request.get("address"), quote = True)
            # Validate character
            (character, charError) = map.validateCharacter(rawCharacter)
            # Validate location
            location = map.validateLocation(rawLocation)
            error, msgError = "", ""

            # Check validation errors and format error message
            if character == None:
                msgChar = rawCharacter
            else:
                msgChar = str(character.name)

            if charError != "":
                error = charError
                msgError = error
            if location.status != "OK":
                error = (error + " " + location.status.encode('utf_8')).decode('utf_8')
                msgError = error
            if (charError == "") and (location.status == "OK"):
                error = ("Move %s to %s. Got it!" % (msgChar, location.address.encode('utf_8'))).decode('utf_8')
                msgError = ""

            print datetime.datetime.utcnow()
            print "error: " + error.encode('utf_8')
            print type(error)
            print "msgError: " + msgError.encode('utf_8')
            print type(msgError)
            # Store in Message store
            if recordMessage("WebForm", None, self.request.remote_addr, msgChar, location, rawCharacter+" "+rawLocation, msgError):
                print "IN APP:"
                top_msgs(True)
                self.writeHTML(error=error, character=character, location=location)
            else:
                error = "App Error: Failed to insert message."
                self.writeHTML(error=error, character=character, location=location)

        else:
            # Validate messageid and get message
            messagekey = ndb.Key(urlsafe=messageid)
            message = Message()
            message = messagekey.get()
            character = Character.query(Character.name == message.character).get()
            location = Location()
            location.address = message.address
            location.latlng = message.latlng

            # If message found
            if not message:
                error = "App Error: Cannot get message."
                self.writeHTML(error=error, character=None, location=None)

            # If message not found
            else:
                # Write
                self.writeHTML(error="", character=character, location=location)
 def player(self, args, channel, scenario, user):
     if len(args) == 1:
         return ['No characters added']
     if not scenario:
         return [
             'You don\'t have an active scenario.\nTry this: ```css\n.d new scenario "Scenario Name"```'
         ]
     elif args[1].lower() == 'list' or args[1].lower() == 'l':
         return [scenario.get_string_characters(channel)]
     elif args[1].lower() == 'delete' or args[1].lower() == 'd':
         char = ' '.join(args[2:])
         [
             scenario.characters.remove(s) for s in scenario.characters
             if char.lower() in s.lower()
         ]
         self.save(scenario, user)
         return [
             f'{char} removed from scenario characters',
             scenario.get_string_characters(channel)
         ]
     else:
         search = ' '.join(args[1:])
         char = Character().find(None, search, channel.guild)
         if char:
             scenario.characters.append(str(char.id))
         else:
             return [
                 f'***{search}*** not found. No character added to _{scenario.name}_'
             ]
         self.save(scenario, user)
         return [
             f'Added {char.name} to scenario characters',
             scenario.get_string_characters(channel)
         ]
Example #36
0
def get_character_journal(character_id, current_user=None):
    character = Character.get(character_id)
    character_application_access_check(current_user, character)
    wallet_data = character.get_paged_op(
        'get_characters_character_id_wallet_journal',
        character_id=character_id)
    return process_journal(character_id, wallet_data)
Example #37
0
def create_quote(anime):

    characters_models = []
    characters = anime.get_characters()
    for character in characters:
        quotes_models = []
        quotes = character.get_quotes()
        for quote in quotes:
            print(type(quote.get_tags()))
            quotes_models.append(
                Quote(quote=quote.get_quote(),
                      tags=quote.get_tags(),
                      views=quote.get_views(),
                      likes=quote.get_likes()))

        characters_models.append(
            Character(name=character.get_name(),
                      image=character.get_image(),
                      quotes=quotes_models,
                      views=character.get_views()))

    db.session.add(
        Anime(name=anime.get_name(),
              image=anime.get_image(),
              characters=characters_models,
              views=anime.get_views()))

    print("{} added".format(anime.get_name()))
Example #38
0
 def post(self, request, *args, **kwargs):
     form_class = self.get_form_class()
     form = self.get_form(form_class)
     if form.is_valid():
         user = request.user
         character = Character(user=user, name=request.POST['name'], gender=request.POST['gender'])
         character.save()
         food = Object(obj_type=1)
         food.character = character
         food.save()
         bandage = Object(obj_type=2)
         bandage.character = character
         bandage.save()
         return HttpResponseRedirect('/')
         return self.form_valid(form, **kwargs)
     else:
         return self.form_invalid(form, **kwargs)
Example #39
0
 def test_get_character_1(self):
     c = Character.get("Chewbacca")
     self.assertEqual(c.name, "Chewbacca")
     self.assertEqual(c.planet, "Kashyyyk")
     self.assertEqual(c.species, "Wookiee")
     self.assertEqual(c.gender, "Male")
     self.assertEqual(c.birth, "200 BBY, Kashyyyk")
     self.assertEqual(c.height, "2.28 meters")
Example #40
0
 def post(self,charset_key):
     
     character_set = CharacterSet.get(charset_key)
     
     logging.info(character_set)
     
     upload_files = self.get_uploads('file')
     blob_info = upload_files[0]
     
     new_character = Character(
         character = self.request.get("character").upper(),
         character_set = character_set,
         image_blob = blob_info.key(),
         image_url = get_serving_url(blob_info.key()),
     )
     new_character.save()
     
     self.redirect("/admin/%s/" % charset_key)
Example #41
0
    def test_get_character_3(self):
        c = Character.get("Darth Vader")

        self.assertEqual(c.name, "Darth Vader")
        self.assertEqual(c.planet, "Tatooine")
        self.assertEqual(c.species, "Human")
        self.assertEqual(c.gender, "Male")
        self.assertEqual(c.birth, "41.9 BBY")
        self.assertEqual(c.height, "1.88 meters, later 2.02 in armor")
Example #42
0
    def test_get_character_2(self):
        c = Character.get("Boba Fett")

        self.assertEqual(c.name, "Boba Fett")
        self.assertEqual(c.planet, "Kamino")
        self.assertEqual(c.species, "Human")
        self.assertEqual(c.gender, "Male")
        self.assertEqual(c.birth, "31.5 BBY , Kamino")
        self.assertEqual(c.height, "1.83 meters")
Example #43
0
    def test_get_all_1(self) :
        characters = Character.get_all()
        char_name = [characters[i].name for i in range(len(characters))]
        expected = ['Greedo', 'Anakin Solo', 'Garindan', 'C-3PO', 'Dorsk 81', 'Ree-Yees', 'Lowbacca', 'Bossk', 'Hethrir', 'Dengar', 'Chewbacca', 'Tionne', 'Moruth Doole', 'Winter', 'Yoda', 'Lando Calrissian', 'Leia Organa Solo', 'Roganda Ismaren', 'Vima-Da-Boda', 'Wicket Wystri Warrick', 'Davin Felth', 'Owen Lars', 'Weequay', 'Grand Admiral Thrawn', 'Biggs Darklighter', 'Lak Sivrak', 'Emperor Palpatine', 'IG-88', 'Nien Nunb', 'Prince Isolder', 'Kyp Durron', 'Cindel Towani', 'Mako Spince', 'Momaw Nadon', 'Gaeriel Captison', '4-LOM', 'Admiral Daala', 'Mon Mothma', 'Ken', 'Tigris', 'Han Solo', 'Nichos Marr', 'Jabba the Hutt', 'Gallandro', 'Salla Zend', 'Mara Jade', 'Teneniel Djo', 'Nomi Sunrider', 'Luke Skywalker', 'Ponda Baba', 'Gethzerion', 'Obi-Wan Kenobi', 'Jacen Solo', 'General Jan Dodonna', 'Garm Bel Iblis', 'Pter Thanas', "Yarna D'al' Gargan", 'General Crix Madine', 'Callista', 'Qwi Xux', 'Grand Moff Tarkin', 'Bib Fortuna', 'Tenel Ka', 'Lobot', 'Labria', 'Triclops', "Emperor's Royal Guards", 'Tusken Raiders', 'Wedge Antilles', 'Shug Ninx', 'Brea Tonnika', "Elder Sh'tk'ith", "Joruus C'baoth", 'Dannik Jerriko', 'Barada', 'Tessek', 'Khabarakh', 'Rillao', 'Ephant Mon', 'Talon Karrde', 'Lady Valarian', 'Admiral Ackbar', 'Exar Kun', "Figrin D'an", 'Oola', 'Ulic Qel-Droma', "Borsk Fey'lya", 'Het Nkik', 'Kabe', 'Zuckuss', 'Captain Gilad Pellaeon', 'Darth Vader', 'Salacious Crumb', 'Bodo Baas', 'Bollux', 'Dev Sibwarra', 'Gartogg', 'Princess Kneesaa', 'Boba Fett', 'Muftak']

        # comparing the two list elements ignoring order
        result = not set(char_name).isdisjoint(expected)

        self.assertEqual(result, True)
Example #44
0
def run_add_cast(request, run_id):
	"""
	FIXME
	@param request:
	@type request:
	@param run_id:
	@type run_id:
	"""
	run = get_object_or_404(Run, pk=run_id)
	aPlayer = Player(run=run, user=request.user)
	if request.method == "POST":
		form = PlayerForm(request.POST, instance=aPlayer)
		if form.is_valid():
			if request.POST['character']:
				aChar=get_object_or_404(Character, pk=request.POST['character'])
			else:
				if request.POST["characterName"]!="":
					aChar=Character(larp=run.larp, name=request.POST["characterName"])
					aChar.save()
				else:
					aChar=False
			if aChar:
				aPlayer=Player(run=run, user=request.user, character=aChar, characterName=request.POST['characterName'])
				aPlayer.save()
			else:
				aPlayer=Player(run=run, user=request.user)
				aPlayer.save()
			return HttpResponseRedirect(run.get_absolute_url())
	else:
		form = PlayerForm()
		form.run=run_id
		if run.is_past:
			form.fields["character"].queryset = Character.objects.filter(larp=run.larp)
		else:
			if run.larp.spoilerability == 'ch':
				form.fields["character"].queryset = Character.objects.none()
			else:
				form.fields["character"].queryset = Character.objects.filter(larp=run.larp, spoiler=False)
	return render_to_response('eventCRUD/cast_add.html', {
		'form':form, 
		'run':run,
		},
		context_instance=RequestContext(request)
	)
Example #45
0
def insert_chars_from_auc(realm):
    """
    Insert all player characters represented in auction house into database
    note: realm names in auction house dump are always localised, with spaces removed
    """
    auc_data = load_auction_data(realm)
    region = realm.region
    unique_auc_chars = set((lot["owner"], lot["ownerRealm"]) for lot in auc_data["auctions"]["auctions"])
    print("Unique chars currently on %s auction house: %d" % (realm.name, len(unique_auc_chars)))
    for name, realm_name_localised in unique_auc_chars:
        realm = get_realm(region, realm_name_localised)
        char = Character()
        char.name = name
        char.realm = realm
        char.retrieve_guild = True
        if not session.query(Character).filter(Character.name == char.name,
                                               Character.realm == char.realm).first():
            session.add(char)
    session.commit()
Example #46
0
def cache(key, update = False):
    msgs = memcache.get(key)
    if msgs is None or update:
        print "DB CACHE QUERY %s" % key
        if key is 'top_msgs':
            msgs = Message.query().order(-Message.createDate).fetch(20)
        elif key is 'get_chars':
            msgs = Character.all()
        msgs = list(msgs)
        memcache.set(key, msgs)
    return msgs
Example #47
0
def createCharacter(request):
  if request.method == 'POST':
    form = CharacterForm(request.POST)
    if form.is_valid():
      data = form.cleaned_data
      character = Character.create(data['gameSystem'], data['name'])
      return HttpResponseRedirect(reverse(charSheet, kwargs = {'charId': character.id}))
  else:
    form = CharacterForm()

  return render(request, 'createCharacter.html', {'form': form})
Example #48
0
def createCharacter():
    result = dict(
        type=ProtocolTypes.CreateCharacter,
        result=ResultCodes.Success)

    if request.form['data']:
        got_data = json.loads(request.form['data'])

        from_keys = ['session_id', 'character']
        if checkContainKeys(from_keys, got_data):
            result['result'], got_user = checkSessionId(got_data['session_id'])
            if got_user:
                got_character = Character.query.filter_by(user_id=got_user.id).first()
                if got_character:
                    result['result'] = ResultCodes.DataExist
                else:
                    got_character = got_data['character']
                    got_user.name = got_character['name']
                    db_session.add(got_user)

                    user_character = Character(got_user.id, got_character['name'])
                    user_character.body_type = got_character['body_type']
                    user_character.cloak_type = got_character['cloak_type']
                    user_character.color_r = got_character['color_r']
                    user_character.color_g = got_character['color_g']
                    user_character.color_b = got_character['color_b']
                    user_character.face_type = got_character['face_type']
                    user_character.gender = got_character['gender']
                    user_character.hair_type = got_character['hair_type']
                    user_character.weapon_type = got_character['weapon_type']
                    
                    db_session.add(user_character)

                    result['result'] = commitData()
        else:
            result['result'] = ResultCodes.InputParamError
    else:
        result['result'] = ResultCodes.AccessError

    return str(json.dumps(result))
Example #49
0
def validateCharacter(rawCharacter):
    # debug: print Character table
    for ch in Character.query().fetch(10):
        print ch

    # Validate character
    formattedChar = rawCharacter.lower()
    character = aliases.aliases.get(formattedChar)
    print rawCharacter
    print formattedChar
    print "Character: %s" % character
    character = Character.query(Character.name == character).get()
    print character
    if character != None:
        error = ""
        print ('character found')
        print character
    else:
        error = "Invalid character [%s]" % rawCharacter

    print "error0: "+error
    return (character, error)
Example #50
0
    def test_get_character_serialize_1(self):
        expected = {
            "birth": "31.5 BBY , Kamino",
            "description": "Boba Fett was a Mandalorian warrior and bounty hunter. He was the only unaltered clone of the famed Jango Fett, created in 32 BBY as unit A0050, one of the first of many Fett replicas designed to become part of the Grand Army of the Republic, and was raised as Jango's son. Jango taught Boba much, training him to become a skilled bounty hunter as was his father-figure before him. In 22 BBY, Jango was killed at the Battle of Geonosis, which opened the Clone Wars.",
            "gender": "Male",
            "height": "1.83 meters",
            "image": "http://img2.wikia.nocookie.net/__cb20130920001614/starwars/images/5/58/BobaFettMain2.jpg",
            "name": "Boba Fett",
            "planet": "Kamino",
            "species": "Human"
        }

        actual = Character.get("Boba Fett").serialize
        bool_result = actual["birth"] == expected["birth"] and \
                        actual["description"] == expected["description"] and \
                        actual["name"] == expected["name"] and \
                        actual["image"] == expected["image"] and \
                        actual["gender"] == expected["gender"] and \
                        actual["height"] == expected["height"] and \
                        actual["planet"] == expected["planet"] and \
                        actual["species"] == expected["species"]

        self.assertEqual(True, bool_result)        
Example #51
0
    def test_get_character_serialize_2(self):
        expected = {
            "birth": "200 BBY, Kashyyyk",
            "description": "Chewbacca (or \"Chewie\", as he was known by his friends) was a legendary Wookiee from Kashyyyk and co-pilot of Han Solo's ship, the Millennium Falcon. He was the son of Attichitcuk, the husband of Mallatobuck, and the father of Lumpawaroo. Chewbacca carried with him the name of an ancient Wookiee hero, the great Bacca, first of the great chieftains of Kashyyyk, and the creator of a sword that denoted leadership among the Wookiees. This name placed Chewbacca in a noble lineage.",
            "gender": "Male",
            "height": "2.28 meters",
            "image": "http://img4.wikia.nocookie.net/__cb20080815045819/starwars/images/thumb/7/73/Chewbaccaheadshot.jpg/500px-Chewbaccaheadshot.jpg",
            "name": "Chewbacca",
            "planet": "Kashyyyk",
            "species": "Wookiee"
        }

        actual = Character.get("Chewbacca").serialize
        bool_result = actual["birth"] == expected["birth"] and \
                        actual["description"] == expected["description"] and \
                        actual["name"] == expected["name"] and \
                        actual["image"] == expected["image"] and \
                        actual["gender"] == expected["gender"] and \
                        actual["height"] == expected["height"] and \
                        actual["planet"] == expected["planet"] and \
                        actual["species"] == expected["species"]

        self.assertEqual(True, bool_result)    
Example #52
0
 def test_character_repr_1(self):
     actual = str(Character.get("Boba Fett"))
     self.assertEqual(actual, "<name Boba Fett>")
Example #53
0
        row['rating'] += change
        row['ranking'] += change * 2
        data.append(row)
else:
    url = "http://us.battle.net/api/wow/leaderboard/3v3"
    r = requests.get(url)
    data = json.loads(r.text)['rows']

timestamp = datetime.now()

for row in data:
    key = row['name'] + str(row['realmId'])
    if key in cache:
        c = cache.get(key)
    else:
        c = Character(row['name'], row['realmId'])
    if row['seasonWins'] + row['seasonLosses'] > c.total_games:
        # Only save an Update object if this change was a single game
        if row['seasonWins'] + row['seasonLosses'] - c.total_games == 1:
            db.session.add(Update(c, row, timestamp))
        c.realm_name = row['realmName']
        c.realm_slug = row['realmSlug']
        c.race_id = row['raceId']
        c.class_id = row['classId']
        c.spec_id = row['specId']
        c.faction_id = row['factionId']
        c.gender_id = row['genderId']
        c.season_wins = row['seasonWins']
        c.season_losses = row['seasonLosses']
        c.weekly_wins = row['weeklyWins']
        c.weekly_losses = row['weeklyLosses']
Example #54
0
 def test_character_repr_2(self):
     actual = str(Character.get("Chewbacca"))
     self.assertEqual(actual, "<name Chewbacca>")
burst = Account()
burst.email = "*****@*****.**"
burst.real_name = "Travis A. Odom"
burst.nickname = "Burstaholic"
burst.save()

lordnull = Account()
lordnull.email = "*****@*****.**"
lordnull.real_name = "Micah Warren"
lordnull.nickname = "lordnull"
lordnull.save()

print "Finished Account."


liz = Character()
liz.account = morgul
liz.game = precursors
liz.first_name = "Lizbeth"
liz.middle_name = "Anne"
liz.last_name = "Locke"
liz.save()

simon = Character()
simon.account = morgul
simon.game = precursors
simon.first_name = "Jonathan"
simon.middle_name = "Robert"
simon.last_name = "Simon"
simon.save()
Example #56
0
def get_characters(char_set):
    character_sets_query = Character.all()
    character_sets_query.filter("character_set = ", char_set)
    return character_sets_query.fetch(1000)