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 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)
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()
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))
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)
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")
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")
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)
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"])
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()
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()
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)
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()
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)
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)
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)
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
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"))
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')
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()
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()
def create_sheet(): sheet = { 'name': 'New Character', 'class': '', 'archetype': '', 'level': 1, 'background': '', 'species': '', 'alignment': '', 'attributes': { 'strength': 10, 'dexterity': 10, 'constitution': 10, 'intelligence': 10, 'wisdom': 10, 'charisma': 10 }, 'baseAc': 10, 'armorType': 'none', 'shieldBonus': 0, 'proficiencies': [], 'expertise': [], 'bonuses': { 'armorClass': 0, 'attacks': 0, 'damage': 0, 'savingThrows': 0, 'strengthSave': 0, 'dexteritySave': 0, 'constitutionSave': 0, 'intelligenceSave': 0, 'wisdomSave': 0, 'charismaSave': 0, 'skills': 0, 'passivePerception': 0, 'techSaveDC': 0, 'techAttackBonus': 0, 'darkSaveDC': 0, 'darkAttackBonus': 0, 'lightSaveDC': 0, 'lightAttackBonus': 0, 'athletics': 0, 'acrobatics': 0, 'sleightOfHand': 0, 'stealth': 0, 'investigation': 0, 'lore': 0, 'nature': 0, 'piloting': 0, 'technology': 0, 'animalHandling': 0, 'insight': 0, 'medicine': 0, 'perception': 0, 'survival': 0, 'deception': 0, 'intimidation': 0, 'performance': 0, 'persuasion': 0, 'initiative': 0, 'hitPointsPerLevel': 0 }, 'deathSaves': { 'succeeded': 0, 'failed': 0 }, 'hitDice': { 'type': 8, 'left': 1 }, 'hitPoints': { 'current': 1, 'max': 1, 'temporary': 0 }, 'features': [], 'attacks': [], 'languages': [], 'otherProficiencies': [], 'speed': 30, 'personalityTraits': '', 'ideal': '', 'bond': '', 'flaw': '', 'notes': '', 'credits': 0, 'equipment': [], 'powerPointsLeft': 0, 'powerPointsMax': 0, 'powers': { 'level0': [], 'level1': [], 'level2': [], 'level3': [], 'level4': [], 'level5': [], 'level6': [], 'level7': [], 'level8': [], 'level9': [] } } char = Character(owner_id=current_user.id, sheet=json.dumps(sheet)) db.session.add(char) db.session.commit() return redirect(url_for('index'))
def create_character(): form = CharacterForm() form['csrf_token'].data = request.cookies['csrf_token'] # if form.validate_on_submit(): if form.validate_on_submit(): # s3 image helper functions. Steps: test if image is in files, # grab image, check if it is required type, # give it a unique name so aws does not overwrite, # then upload to aws, returning any errors if upload fails. if "image" not in request.files: return {"errors": ["image required"]} image = request.files["image"] if not allowed_file(image.filename): return {"errors": ["file type not permitted"]} image.filename = get_unique_filename(image.filename) upload = upload_file_to_s3(image) if "url" not in upload: return {"errors": [upload['errors']]} url = upload["url"] # create a new instance of the character class character = Character() # populate character instance with data from form & aws url character = Character(userId=form.data['userId'], name=form.data['name'], level=form.data['level'], race=form.data['race'], characterClass=form.data['characterClass'], subclass=form.data['subclass'], hitpoints=form.data['hitpoints'], speed=form.data['speed'], imgURL=url, proficiencies=form.data['proficiencies'], background=form.data['background'], alignment=form.data['alignment'], attributes=form.data['attributes'], traits=form.data['traits'], ideals=form.data['ideals'], bonds=form.data['bonds'], flaws=form.data['flaws'], inventory=form.data['inventory'], description=form.data['description'], languages=form.data['languages'], tools=form.data['tools']) # Take care of tag creation # grab tags and query to check if they are created already if len(form.data['tags']) > 0: tagsFormatted = [ tag.strip() for tag in form.data['tags'].split(",") ] for tag in tagsFormatted: queriedTag = Tag.query.filter(Tag.name == tag).first() if (queriedTag): character.tags.append(queriedTag) else: tag = Tag(name=tag) character.tags.append(tag) classTag = Tag.query.filter( Tag.name == form.data['characterClass']).first() raceTag = Tag.query.filter(Tag.name == form.data['race']).first() character.tags.append(classTag) character.tags.append(raceTag) # Take care of abilites and ability appending for feature in json.loads(form.data['features']): feature_to_add = (Ability.query.filter( Ability.name == feature['name']).first()) if (feature_to_add): character.abilities.append(feature_to_add) else: return {"errors": "Failed to add ability"} # add and commit character db.session.add(character) db.session.commit() return character.to_dict() return {'errors': validation_errors_to_error_messages(form.errors)}
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()
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")
def setUp(self): self.new_character = Character(1, 'thor', 'he is amazing', '/hsfhdhgd')
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)
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
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()
def seed_characters(): demoCharacter = Character() db.session.add(demoCharacter) db.session.commit()