Пример #1
0
 def get(self, character_id=None):
     if not character_id:
         character_list = Character.read_all()
         return Response(character_list).to_dict()
     
     character = Character.read(character_id)
     return Response(character).to_dict()
Пример #2
0
def create_character():
    """ Renders the create character page. Submission of the character
    form adds form data to database and associates with user. """

    form = CreateCharacterForm()
    if form.is_submitted():
        char = Character(
            name=form.characterName.data,
            vocation=form.characterClass.data,
            owner=current_user,
        )
        db.session.add(char)

        if form.characterClass.data == "Knight":
            char.vigor = 12
            char.endurance = 11
            char.strength = 13
            char.intelligence = 9
        else:
            char.vigor = 6
            char.endurance = 9
            char.strength = 7
            char.intelligence = 16

        db.session.commit()

        return render_template("character.html", character=form)
    return render_template("create_character.html",
                           name="Adrian",
                           form=form,
                           title="Create Character")
def createCharacter():
    form = CharacterForm()
    character = Character(userId=form.data['userId'],
                          name=form.data['name'],
                          level=form.data['level'],
                          characterClass=form.data['characterClass'],
                          race=form.data['race'],
                          alignment=form.data['alignment'],
                          proficiencies=form.data['proficiencies'],
                          personality__traits=form.data['traits'],
                          ideals=form.data['ideals'],
                          bonds=form.data['bonds'],
                          flaws=form.data['flaws'],
                          strength=form.data['strength'],
                          dex=form.data['dex'],
                          constitution=form.data['constitution'],
                          intelligence=form.data['intelligence'],
                          wisdom=form.data['wisdom'],
                          charisma=form.data['charisma'],
                          saving__throw__one=form.data['savingThrowOne'],
                          saving__throw__two=form.data['savingThrowTwo'],
                          skill_one=form.data['skillOne'],
                          skill_two=form.data['skillTwo'],
                          skill_three=form.data['skillThree'],
                          skill_four=form.data['skillFour'])
    db.session.add(character)
    db.session.commit()
    return character.to_dict()
Пример #4
0
def index():
    user = User.query.filter_by(username=current_user.username).first_or_404()
    c = Character()
    characters = c.get_characters(user_id=current_user.id)
    return render_template("index.html",
                           title='Home Page',
                           characters=characters,
                           user=user)
Пример #5
0
def new_character():
    form = CharacterForm()
    if form.validate_on_submit():
        character = Character(
            name=form.name.data,
            lvlclass=form.lvlclass.data,
            armor=int(form.armor.data),
            speed=int(form.speed.data),
            race=form.race.data,
            stats=
            f'[{int(form.stat1.data)},{int(form.stat2.data)},{int(form.stat3.data)},{int(form.stat4.data)},{int(form.stat5.data)},{int(form.stat6.data)}]',
            willsave=
            f'[{int(form.sw1.data)},{int(form.sw2.data)},{int(form.sw3.data)},{int(form.sw4.data)},{int(form.sw5.data)},{int(form.sw6.data)}]',
            skills=
            f'[{int(form.sk1.data)},{int(form.sk2.data)},{int(form.sk3.data)},{int(form.sk4.data)},{int(form.sk5.data)},{int(form.sk6.data)},{int(form.sk7.data)},{int(form.sk8.data)},{int(form.sk9.data)},{int(form.sk10.data)},{int(form.sk11.data)},{int(form.sk12.data)},{int(form.sk13.data)},{int(form.sk14.data)},{int(form.sk15.data)},{int(form.sk16.data)},{int(form.sk17.data)},{int(form.sk18.data)}]',
            abilities=form.abilities.data,
            inventory=form.inventory.data,
            health=form.health.data,
            author=current_user)
        db.session.add(character)
        db.session.commit()
        flash('Персонаж успешно создан!', 'success')
        return redirect(url_for('chars'))
    return render_template('new_character.html',
                           title='Создать персонажа',
                           form=form,
                           image_file_small=current_user.avatar(32))
Пример #6
0
def add_character():
    """
    Presents a form to create a character that is added to the database.
    Flashes success and redirects to the page of that character.
    """
    if not current_user.is_authenticated:
        flash('Please login or register to add entries.')
        return redirect(url_for('index'))

    form = AddCharacterForm()

    if form.validate_on_submit():
        s = Session()

        if form.char_class.data == 'Select a Class':
            form.char_class.data = None
        if form.race.data == 'Select a Race':
            form.race.data = None

        character = Character(
            name=form.name.data,
            desc=form.desc.data,
            race=form.race.data,
            char_class=form.char_class.data,
            player_character=form.player_character.data
        )
        s.add(character)
        s.commit()
        s.close()
        flash('"{}" has been added as a character!'.format(form.name.data))
        return redirect(url_for('view_character', pc_id=form.name.data))

    return render_template('characters/add_char_form.html', form=form)
Пример #7
0
def main():

    try:
        if sys.argv[1] == 'delete':

            from app.scrape.models import db
            from app.models import Character, Comic, Creator, Event, Series

            db.drop_all()
            db.create_all()

            newCharacter = Character(
                1009146, "Abomination (Emil Blonsky)",
                "This is a test description",
                "http://i.annihil.us/u/prod/marvel/i/mg/9/50/4ce18691cbf04.jpg",
                44, 2, 4)

            newCreator = Creator(
                621, "Adriana Melo",
                "http://i.annihil.us/u/prod/marvel/i/mg/c/40/4bb45e7cc293b.jpg",
                25, 4, 11)

            newSeries = Series(
                7524, "Adam: Legend of the Blue Marvel (2008)", "Testing 123",
                2008, 2015,
                "http://i.annihil.us/u/prod/marvel/i/mg/9/20/4bb4f0966a26a.jpg",
                12, 16, 11, 8)

            newEvent = Event(
                306, "Gene Colan Tribute (2008)", "This is a test description",
                "http://i.annihil.us/u/prod/marvel/i/mg/3/03/5109a0811486f.jpg",
                23, 22, 11, 1)

            newComic = Comic(
                428, "Ant-Man (2003) #4", 4, "This is a test description",
                "12345", 0, 2.99,
                "http://i.annihil.us/u/prod/marvel/i/mg/4/20/4bc697c680890.jpg",
                2, 0, 0)

            db.session.add(newCharacter)
            db.session.add(newComic)
            db.session.add(newCreator)
            db.session.add(newSeries)
            db.session.add(newEvent)

            db.session.commit()

            print(
                "\nDatabase erased, reinitialized and prepped for TravisCI Build\n"
            )

        else:

            print("\nNothing deleted.  Have a good day.\n")
    except Exception:

        print("\nNothing deleted.  Have a good day.\n")
Пример #8
0
 def post():
     name = request.data.get('name', None)
     try:
         hp = int(request.data.get('hp', ''))
         mana = int(request.data.get('mana', ''))
         attack = int(request.data.get('attack', ''))
         defense = int(request.data.get('defense', ''))
         intelligence = int(request.data.get('intelligence', ''))
         luck = int(request.data.get('luck', ''))
     except ValueError:
         return {
         'message' : "Invalid stat data. All stats must be integers"
     }, 400
     if name is not None:
         character = Character(name=name, hp=hp, mana=mana, attack=attack, defense=defense, intelligence=intelligence, luck=luck)
         character.save()
         response = jsonify(makeCharacterObject(character))
         response.status_code = 201
         return response
Пример #9
0
def commit_charactes():
    trimmed_character_list = load_listing('data/trimmed_characters.json')
    char_id_set = set()
    for char in trimmed_character_list:
        char_id_set.add(char['id'])
        # char.pop('id')
        char_model = Character(**char)
        # print(str(char_model.toJSON()))
        database.session.add(char_model)
    database.session.commit()
    print("Character Data Loaded")
Пример #10
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('name', location='json', required=True)
        parser.add_argument('scenario_id', location='json', required=False, type=int)
        parser.add_argument('description', location='json', default='')
        parser.add_argument('xp', location='json', default=0, type=int)
        parser.add_argument('agility', location='json', default=2, type=int)
        parser.add_argument('smarts', location='json', default=2, type=int)
        parser.add_argument('spirit', location='json', default=2, type=int)
        parser.add_argument('strength', location='json', default=2, type=int)
        parser.add_argument('vigor', location='json', default=2, type=int)
        parser.add_argument('pace', location='json', default=2, type=int)
        parser.add_argument('parry', location='json', default=2, type=int)
        parser.add_argument('toughness', location='json', default=2, type=int)
        parser.add_argument('charisma', location='json', default=0, type=int)
        parser.add_argument('wounds', location='json', default=0, type=int)
        parser.add_argument('fatigue', location='json', default=0, type=int)
        data = parser.parse_args()

        character = Character(**data)
        character.create()
        return Response(character, 201).to_dict()
Пример #11
0
 def get():
     characters = Character.get_all()
     if len(characters) == 0:
         response = jsonify([])
         response.status_code = 200
         return response
     results = []
     for c in characters:
         obj = makeCharacterObject(c)
         results.append(obj)
         response = jsonify(results)
         response.status_code = 200
     return response
Пример #12
0
def add_character():
    form = AddCharacterForm()
    user = User.query.filter_by(username=current_user.username).first_or_404()
    if form.validate_on_submit():
        character = Character(name=form.name.data,
                              level=form.level.data,
                              char_class=form.char_class.data,
                              char_race=form.char_race.data,
                              specialization=form.specialization.data,
                              profession0=form.profession0.data,
                              profession1=form.profession1.data,
                              needs=form.needs.data,
                              user_id=current_user.id)
        db.session.add(character)
        db.session.commit()
        flash('Character Created!')
        return redirect(url_for('main.index'))
    c = Character()
    characters = c.get_characters(user_id=current_user.id)
    return render_template('addcharacter.html',
                           title="Add Character",
                           form=form,
                           characters=characters)
Пример #13
0
def add_characters(characters):
    for c in characters:
        path = c['thumbnail']['path']
        if path == 'http://i.annihil.us/u/prod/marvel/i/mg/f/60/4c002e0305708.gif':
            continue
        if 'image_not_available' in path.split('/'):
            continue
        path = path + '.' + c['thumbnail']['extension']
        stories = ", ".join([s["name"] for s in c['stories']['items']])
        new_character = Character(c["id"], c["name"], c["description"][:1500],
                                  path, stories)
        db.session.merge(new_character)
        db.session.commit()
        print("Added " + c["name"])
Пример #14
0
 def test_character_model_4(self):
     data = peopledata
     d = data['1']
     d2 = data['2']
     id = 1
     id2 = 2
     character = Character(
         id, d['name'], d['gender'], d['birth_year'], d['height'],
         d['mass'],
         "http://starwarscardtraderapp.com/wp-content/uploads/2015/12/99-1-7-Award-Luke-Skywalker.png"
     )
     character2 = Character(
         id2, d2['name'], d2['gender'], d2['birth_year'], d2['height'],
         d2['mass'],
         "http://starwarscardtraderapp.com/wp-content/uploads/2015/12/99-1-7-Award-Luke-Skywalker.png"
     )
     test_db.session.add(character)
     test_db.session.add(character2)
     s = test_db.session.query(Character).get(str(2))
     name = s.name
     self.assertEqual(d2['name'], name)
     test_db.session.delete(character)
     test_db.session.delete(character2)
     test_db.session.commit()
Пример #15
0
    def put(self, character_id):
        parser = reqparse.RequestParser()
        parser.add_argument('name', location='json')
        parser.add_argument('scenario_id', location='json', type=int)
        parser.add_argument('description', location='json')
        parser.add_argument('xp', location='json', type=int)
        parser.add_argument('agility', location='json', type=int)
        parser.add_argument('smarts', location='json', type=int)
        parser.add_argument('spirit', location='json', type=int)
        parser.add_argument('strength', location='json', type=int)
        parser.add_argument('vigor', location='json', type=int)
        parser.add_argument('pace', location='json', type=int)
        parser.add_argument('parry', location='json', type=int)
        parser.add_argument('toughness', location='json', type=int)
        parser.add_argument('charisma', location='json', type=int)
        parser.add_argument('wounds', location='json', type=int)
        parser.add_argument('fatigue', location='json', type=int)
        data = parser.parse_args()
        Functions.validate_params(data)

        data.update({'id': character_id})
        character = Character(**data)
        character.update()
        return Response(character, 200, 'Successfuly updated').to_dict()
Пример #16
0
 def test_character_model_1(self):
     """Test querying the database by attribute using simple keywords"""
     data = peopledata
     d = data['1']
     id = 1
     character = Character(
         id, d['name'], d['gender'], d['birth_year'], d['height'],
         d['mass'],
         "http://starwarscardtraderapp.com/wp-content/uploads/2015/12/99-1-7-Award-Luke-Skywalker.png"
     )
     test_db.session.add(character)
     s = test_db.session.query(Character).all()
     count = len(s)
     self.assertEqual(1, count)
     test_db.session.delete(character)
     test_db.session.commit()
Пример #17
0
    def on_new_character(data):
        name = data['name']

        character = db.session.query(Character).filter_by(name=name).first()
        if character:
            return

        initiative = int(data['initiative'])
        secret_initiative = data.get('secret_initiative', False)
        print('Creating new character: {}/{}'.format(name, initiative))
        encounter = db.session.query(Encounter).first()
        character = Character(name=name, initiative=initiative, secret_initiative=secret_initiative,
                              encounter=encounter)
        db.session.add(character)
        db.session.commit()
        InitiativeNamespace.emit_new_state(broadcast=True)
Пример #18
0
def create_database():
    db.drop_all()
    db.session.commit()
    db.create_all()
    user = User(
        username='******',
        email='*****@*****.**',
        password=bcrypt.generate_password_hash('testuser').decode('utf-8'),
        activated=True)
    db.session.add(user)
    db.session.commit()
    with open('./app/sheets/1.json') as f:
        content = f.read()
    char = Character(sheet=f"{content}", owner_id=user.id)
    db.session.add(char)
    db.session.commit()
Пример #19
0
def create_character():
    form = CreateCharacterForm()
    form.game.choices = [(0, "None")] + [
        (g.id, g.name)
        for g in current_user.owned_games + current_user.joined_games
    ]
    if form.validate_on_submit():
        g = Game.query.get(form.game.data)
        c = Character(name=form.name.data,
                      player=current_user,
                      game=g,
                      public=form.public.data)
        db.session.add(c)
        db.session.commit()
        flash('Congratulations, you created a character called "{}"!'.format(
            c.name))
        return redirect(url_for('game.character', characterid=c.id))
    return render_template('game/create_character.html', form=form)
Пример #20
0
def join(gameid):
    g = Game.query.get_or_404(gameid)
    if g.has_member(current_user):
        return redirect(url_for('game.game', gameid=gameid))
    if g.is_full():
        flash("That game is already full!")
        return redirect(url_for('game.game', gameid=gameid))
    form = JoinGameForm(g)
    if form.validate_on_submit():
        c = Character(name=form.name.data,
                      player=current_user,
                      game=g,
                      public=form.visible.data)
        g.players.append(current_user)
        db.session.add(c)
        db.session.commit()
        flash('Welcome to the game!')
        return redirect(url_for('game.game', gameid=gameid))
    return render_template('game/join.html', game=g, form=form)
Пример #21
0
def new_character(history_id):
    form = CharacterForm()
    if form.validate_on_submit():
        story = History.query.filter_by(id=history_id).first()
        character = Character(name=form.name.data,
                              info=form.info.data,
                              author=current_user,
                              story=story)
        db.session.add(character)
        db.session.commit()
        flash('Вы создали персонажа', 'success')
        return redirect(
            url_for('character',
                    history_id=history_id,
                    character_id=character.id))

    return render_template('create_character.html',
                           title='New History',
                           form=form)
Пример #22
0
def create():
    form = CreateCharacterForm()

    if form.validate_on_submit():
        char = Character(name=form.name.data,
                         race=form.race.data,
                         class_=form.class_.data,
                         description=form.description.data,
                         private_notes=form.private_notes.data,
                         user_id=current_user.id)

        db.session.add(char)
        db.session.commit()
        flash("Character was created.", "success")

        return redirect(url_for("character.view", id=char.id))
    else:
        return render_template("character/create.html",
                               form=form,
                               title=page_title("Add Character"))
Пример #23
0
def create_new_char(username):
    user = User.query.filter_by(username=username).first_or_404()
    form = NewCharacterForm()
    form.sub_class.choices = [(sub_class.name, sub_class.name)
                              for sub_class in Sub_Class.query.filter_by(
                                  char_class='Barbarian').all()]
    form.sub_race.choices = [
        (sub_race.name, sub_race.name)
        for sub_race in Sub_Race.query.filter_by(race='Aarakocra').all()
    ]
    if request.method == 'POST':
        character = Character(name=form.name.data, race=form.race.data,\
         char_class=form.char_class.data, sub_class=form.sub_class.data, sub_race=form.sub_race.data, level=form.level.data, hp=form.hp.data, user_id=user.id)
        db.session.add(character)
        db.session.commit()
        flash('Your character has been created!')
        return redirect(url_for('user', username=current_user.username))
    return render_template('create_new_char.html',
                           user=user,
                           form=form,
                           title='Create New Character')
Пример #24
0
def seed_characters():

    grydal = Character(
        userId=1,
        name="Grydal",
        level=2,
        race="Dwarf",
        characterClass="Barbarian",
        hitpoints=28,
        imgURL=
        "https://martialsheets-image-bucket.s3.amazonaws.com/dwarf_berzerker.jpg",
        proficiencies="Athletics,Insight,History,Perception,Survival",
        background="Sailor",
        alignment="Chaotic Good",
        attributes=json.dumps({
            "str": 17,
            "dex": 10,
            "con": 16,
            "int": 8,
            "wis": 15,
            "cha": 8
        }),
        traits="Hates giants, dislikes elves, likes other short races",
        ideals="fight til death",
        bonds="Silverbeard, House Branka",
        flaws="quick to judge, kind of an asshole",
        inventory=
        " Handaxe, Javelin, Explorer's Pack, Greataxe, Smith's Tools, Tinkerer's Tools, Healing Potion, Keen Whetson, Rope(100ft), Pendant, Troll Skull(for reasons), Scale Armor",
        description=
        "A mean dwarf but good to have at your side. Gets real angry.",
        languages="Common, Dwarven, Orcish",
        tools="Blacksmith's Tools, Harmonica")

    isabella = Character(
        userId=1,
        name="Isabella",
        level=1,
        race="Halfling",
        characterClass="Rogue",
        proficiencies="Athletics,Insight,History,Perception,Survival",
        hitpoints=11,
        background="Sailor",
        alignment="Chaotic Good",
        attributes=json.dumps({
            "str": 17,
            "dex": 10,
            "con": 16,
            "int": 12,
            "wis": 12,
            "cha": 12
        }),
        traits="Hates giants, dislikes elves, likes other short races",
        ideals="fight til death",
        imgURL=
        "https://martialsheets-image-bucket.s3.amazonaws.com/isabella.jpg",
        bonds="Silverbeard, House Branka",
        flaws="quick to judge, kind of an asshole",
        inventory="Too many stolen goods",
        description="Sticky fingers embodied.")

    laten = Character(
        userId=1,
        name="LatenKull",
        level=1,
        race="Human",
        characterClass="Fighter",
        hitpoints=13,
        proficiencies="Athletics,Insight,History,Perception,Survival",
        background="Soldier",
        alignment="True Neutral",
        attributes=json.dumps({
            "str": 17,
            "dex": 10,
            "con": 16,
            "int": 12,
            "wis": 12,
            "cha": 12
        }),
        traits="Hates giants, dislikes elves, likes other short races",
        ideals="fight til death",
        imgURL=
        "https://martialsheets-image-bucket.s3.amazonaws.com/latenkull.png",
        bonds="Silverbeard, House Branka",
        flaws="quick to judge, kind of an asshole",
        inventory="Lots of swords.",
        description="A weary soldier.")

    irelia = Character(
        userId=1,
        name="Irelia of the Flaming Fist",
        level=1,
        race="Human",
        characterClass="Monk",
        hitpoints=11,
        proficiencies="Athletics,Insight,History,Perception,Survival",
        background="Sailor",
        alignment="Chaotic Good",
        imgURL="https://martialsheets-image-bucket.s3.amazonaws.com/Irelia.png",
        attributes=json.dumps({
            "str": 17,
            "dex": 10,
            "con": 16,
            "int": 12,
            "wis": 12,
            "cha": 12
        }),
        traits="Hates giants, dislikes elves, likes other short races",
        ideals="fight til death",
        bonds="Silverbeard, House Branka",
        flaws="quick to judge, kind of an asshole",
        inventory="Lots of knick knacks.",
        description="Very naive, but a good heart.")

    db.session.add_all([grydal, isabella, laten, irelia])
    db.session.commit()
Пример #25
0
def create_db():
    with app.app_context():
        db.init_app(app)

        db.create_all()

        created_anime = []
        created_characters = []
        created_actors = []
        created_manga = []

        existing_character = {}
        existing_actor = {}
        existing_manga = {}

        for anime_file_num in os.listdir(data_folder + jikan_anime):
            with open(data_folder + jikan_anime +
                      anime_file_num) as anime_datafile:
                print("anime: " + anime_file_num)
                anime_json_data = json.load(anime_datafile)

                anime_title = anime_json_data['title']
                anime_aired = anime_json_data['aired']
                anime_score = anime_json_data['score'][0]
                anime_episodes = anime_json_data['episodes']
                anime_synopsis = anime_json_data['synopsis']

                anime_type = anime_json_data['type']
                if anime_type == None:
                    anime_type = 'Unknown'

                anime_pic = anime_json_data['image']
                anime_status = anime_json_data['status']
                anime_youtube = None
                try:
                    if anime_json_data['youtubeVideoId'] != '':
                        anime_youtube = anime_json_data['youtubeVideoId']

                except KeyError:
                    pass

                genre_list = []
                for genre in anime_json_data['genre']:
                    genre_list.append(genre[1])

                anime_genre = ', '.join(genre_list)

                anime_rating = anime_json_data['rating']

                final_anime = Anime(title=anime_title,
                                    aired=anime_aired,
                                    score=anime_score,
                                    num_episodes=anime_episodes,
                                    synopsis=anime_synopsis,
                                    media_type=anime_type,
                                    picture=anime_pic,
                                    status=anime_status,
                                    youtube_id=anime_youtube,
                                    rating=anime_rating,
                                    genre=anime_genre)
                created_anime.append(final_anime)

                # Character
                if 'character' in anime_json_data:
                    for character_list_object in anime_json_data['character']:
                        if character_list_object['role'] == 'Main':
                            anime_character_id = (
                                character_list_object['url'].split('/'))[4]
                            if anime_character_id in existing_character:
                                final_anime.characters.add(created_characters[
                                    existing_character[anime_character_id]])
                                continue

                            if os.path.exists(data_folder + jikan_character +
                                              anime_character_id):
                                with open(data_folder + jikan_character +
                                          anime_character_id
                                          ) as character_datafile:
                                    character_json_data = json.load(
                                        character_datafile)

                                    try:
                                        character_name = character_json_data[
                                            'name']
                                    except KeyError:
                                        continue

                                    character_japanese_name = character_json_data[
                                        'name-japanese']
                                    character_about = character_json_data[
                                        'about']
                                    character_pic = character_json_data[
                                        'image']
                                    if not character_pic:
                                        character_pic = None

                                    print("Creating character with MAL ID:" +
                                          anime_character_id)
                                    final_character = Character(
                                        name=character_name,
                                        japanese_name=character_japanese_name,
                                        about=character_about,
                                        picture=character_pic)
                                    created_characters.append(final_character)
                                    existing_character[
                                        anime_character_id] = len(
                                            created_characters) - 1

                                    final_anime.characters.add(final_character)

                                    # Voice actor
                                    if 'voice-actor' in character_list_object:
                                        for actor_list_object in character_list_object[
                                                'voice-actor']:
                                            actor_id = (
                                                actor_list_object['url'].split(
                                                    '/'))[4]

                                            if actor_id in existing_actor:
                                                final_character.actors.add(
                                                    created_actors[
                                                        existing_actor[
                                                            actor_id]])
                                                final_anime.actors.add(
                                                    created_actors[
                                                        existing_actor[
                                                            actor_id]])
                                                continue

                                            actor_name = actor_list_object[
                                                'name']

                                            if os.path.exists(data_folder +
                                                              jikan_person +
                                                              actor_id):
                                                print("actor id: " + actor_id)
                                                with open(data_folder +
                                                          jikan_person +
                                                          actor_id
                                                          ) as actor_datafile:
                                                    actor_json_data = json.load(
                                                        actor_datafile)

                                                    actor_language = actor_json_data[
                                                        'language']
                                                    actor_given_name = None

                                                    try:
                                                        actor_given_name = actor_json_data[
                                                            'given-name']
                                                    except KeyError:
                                                        pass

                                                    actor_birthday = actor_json_data[
                                                        'birthday']
                                                    actor_pic = None if actor_json_data[
                                                        'image'] == "" else actor_json_data[
                                                            'image']
                                                    actor_website = None if actor_json_data[
                                                        'website'] == "" else actor_json_data[
                                                            'website']

                                                    final_actor = Actor(
                                                        name=actor_name,
                                                        language=actor_language,
                                                        given_name=
                                                        actor_given_name,
                                                        birthday=actor_birthday,
                                                        picture=actor_pic,
                                                        website=actor_website)
                                                    created_actors.append(
                                                        final_actor)
                                                    existing_actor[
                                                        actor_id] = len(
                                                            created_actors) - 1

                                                    final_character.actors.add(
                                                        final_actor)
                                                    final_anime.actors.add(
                                                        final_actor)

                # Manga
                if 'related' in anime_json_data:
                    related = anime_json_data['related']
                    if 'Adaptation' in anime_json_data['related']:
                        adaptation_obj = related['Adaptation']

                        manga_id_list = []
                        if isinstance(adaptation_obj[0], list):
                            for list_obj in related['Adaptation']:
                                tokens = list_obj[1].split('/')
                                manga_id_list.append(tokens[2])

                        else:
                            manga = related['Adaptation']
                            manga = manga[1].split('/')
                            manga_id_list.append(manga[2])

                        for manga_id in manga_id_list:
                            if manga_id in existing_manga:
                                final_anime.mangas.add(
                                    created_manga[existing_manga[manga_id]])

                            elif os.path.exists(data_folder + jikan_manga +
                                                manga_id):
                                print("manga id: " + manga_id)
                                with open(data_folder + jikan_manga +
                                          manga_id) as manga_datafile:
                                    manga_json_data = json.load(manga_datafile)

                                    manga_title = None
                                    if manga_json_data['type'] == 'Novel':
                                        manga_title = manga_json_data[
                                            'title'] + ' - (Novel)'
                                    else:
                                        manga_title = manga_json_data['title']

                                    manga_title_english = None
                                    try:
                                        manga_title_english = manga_json_data[
                                            'title-english']
                                    except KeyError:
                                        pass

                                    manga_title_japanese = None
                                    try:
                                        manga_title_japanese = manga_json_data[
                                            'japanese']
                                    except KeyError:
                                        pass

                                    list_authors = []
                                    for json_author in manga_json_data[
                                            'author']:
                                        list_authors.append(
                                            json_author['name'])
                                    manga_author = ', '.join(list_authors)

                                    manga_published = manga_json_data[
                                        'published']

                                    manga_score = None
                                    try:
                                        manga_score = manga_json_data['score'][
                                            0]
                                    except KeyError:
                                        pass

                                    manga_chapters = manga_json_data[
                                        'chapters']
                                    manga_synopsis = manga_json_data[
                                        'synopsis']
                                    manga_type = manga_json_data['type']
                                    manga_picture = manga_json_data['image']
                                    manga_status = manga_json_data['status']

                                    manga_genre_list = []
                                    for genre in manga_json_data['genre']:
                                        manga_genre_list.append(genre[1])

                                    manga_genre = ', '.join(manga_genre_list)

                                    final_manga = Manga(
                                        title=manga_title,
                                        title_english=manga_title_english,
                                        title_japanese=manga_title_japanese,
                                        author=manga_author,
                                        published=manga_published,
                                        score=manga_score,
                                        num_chapters=manga_chapters,
                                        synopsis=manga_synopsis,
                                        media_type=manga_type,
                                        picture=manga_picture,
                                        status=manga_status,
                                        genre=manga_genre)
                                    created_manga.append(final_manga)
                                    existing_manga[manga_id] = len(
                                        created_manga) - 1

                                    final_anime.mangas.add(final_manga)

                                    for manga_character in manga_json_data[
                                            'character']:
                                        manga_character_id = (
                                            manga_character['url'].split('/')
                                        )[4]

                                        if manga_character_id in existing_character:
                                            final_manga.characters.add(
                                                created_characters[
                                                    existing_character[
                                                        manga_character_id]])
                                        else:
                                            if os.path.exists(
                                                    data_folder +
                                                    jikan_character +
                                                    manga_character_id):
                                                with open(
                                                        data_folder +
                                                        jikan_character +
                                                        manga_character_id
                                                ) as manga_character_datafile:
                                                    manga_character_json_data = json.load(
                                                        manga_character_datafile
                                                    )

                                                    try:
                                                        manga_character_name = manga_character_json_data[
                                                            'name']
                                                    except KeyError:
                                                        continue

                                                    manga_character_japanese_name = manga_character_json_data[
                                                        'name-japanese']
                                                    manga_character_about = manga_character_json_data[
                                                        'about']
                                                    manga_character_pic = manga_character_json_data[
                                                        'image']

                                                    print(
                                                        "Creating manga character: "
                                                        + manga_character_id)
                                                    final_manga_character = Character(
                                                        name=
                                                        manga_character_name,
                                                        japanese_name=
                                                        manga_character_japanese_name,
                                                        about=
                                                        manga_character_about,
                                                        picture=
                                                        manga_character_pic)
                                                    created_characters.append(
                                                        final_manga_character)
                                                    existing_character[
                                                        manga_character_id] = len(
                                                            created_characters
                                                        ) - 1

                                                    final_manga.characters.add(
                                                        final_manga_character)

        for anime in created_anime:
            db.session.add(anime)

        for character in created_characters:
            db.session.add(character)

        for actor in created_actors:
            db.session.add(actor)

        for manga in created_manga:
            db.session.add(manga)

        db.session.commit()
        print("I HAVE COMITTED")
Пример #26
0
 def delete(self, character_id):
     result = Character.delete(character_id)
     return Response(result, 200, 'Successfuly deleted').to_dict()
Пример #27
0
from app.views import load_listing
from app.models import Character

trimmed_character_list = load_listing('data/trimmed_characters.json')
for char in trimmed_character_list:
    # char.pop('id')
    char_model = Character(**char)
    break
Пример #28
0
 def create_character():
     character_info = request.json or request.form or request.values
     character = Character(name=character_info.get('name'),
                           comic_id=character_info.get('comic'))
     db.session.add(character)
     db.session.commit()
Пример #29
0
    def setUp(self):

        self.new_character = Character(1, 'thor', 'he is amazing', '/hsfhdhgd')
Пример #30
0
def user(username):
    user = User.query.filter_by(username=current_user.username).first_or_404()
    c = Character()
    characters = c.get_characters(user_id=current_user.id)
    return render_template('user.html', user=user, characters=characters)