def update(self, template, form, user): filename = secure_filename(form.archive.file.filename) template.subject = form.subject.data template.description = form.description.data template.tags = [] for tag_name in form.tags.data: tag = Tag.query.filter( Tag.name == tag_name).first() or Tag(tag_name) template.tags.append(tag) template.modified_date = datetime.datetime.now() if len(filename) > 0: delete_template_files(template.id) template.filename = filename fileinfo = save_template_file(template.id, form.archive.file, filename) template.compressed_filelist = fileinfo.compressed_filelist template.index_filename = fileinfo.index_filename uncompress_template(template.id, filename) make_thumbnail(template.id, template.index_filename) db_session.add(template) db_session.commit()
def init(): """initialize database and directories""" try: remakedir(settings.DATA_DIR_PATH) remakedir(settings.DEMO_DIR_PATH) remakedir(settings.THUMBNAIL_DIR_PATH) except: print sys.exc_info() try: if os.path.exists(settings.DB_PATH): os.remove(settings.DB_PATH) init_db() if getpwuid(os.getuid())[0] == 'root': os.chown(settings.DB_PATH, apache_uid, apache_gid) except: print sys.exc_info() try: role_admin = UserRole('admin', 'for administrators') db_session.add(role_admin) user_admin = User('admin', role=role_admin) db_session.add(user_admin) db_session.commit() db_session.remove() except: print sys.exc_info()
def init(): """initialize database and directories""" try: remakedir(settings.DATA_DIR_PATH) remakedir(settings.DEMO_DIR_PATH) remakedir(settings.THUMBNAIL_DIR_PATH) except: print sys.exc_info() try: if os.path.exists(settings.DB_PATH): os.remove(settings.DB_PATH) init_db() if getpwuid(os.getuid())[0] == "root": os.chown(settings.DB_PATH, apache_uid, apache_gid) except: print sys.exc_info() try: role_admin = UserRole("admin", "for administrators") db_session.add(role_admin) user_admin = User("admin", role=role_admin) db_session.add(user_admin) db_session.commit() db_session.remove() except: print sys.exc_info()
def new(self, form, user): filename = secure_filename(form.archive.file.filename) # add Template to db newtemp = Template(form.subject.data, user, filename, len(form.archive.file.stream.getvalue())/1024, description=form.description.data, tags=form.tags.data ) if not newtemp: flash("db error") abort(401) db_session.add(newtemp) db_session.commit() fileinfo = save_template_file(newtemp.id, form.archive.file, filename) newtemp.compressed_filelist = fileinfo.compressed_filelist newtemp.index_filename = fileinfo.index_filename db_session.commit() uncompress_template(newtemp.id, filename) make_thumbnail(newtemp.id, newtemp.index_filename)
def edit_item(item_id, item): """Route to item edit form + update item""" catalogs = Catalog.get_all() # GET request if request.method == 'GET': return render_template('items/edit.html', item=item, catalogs=catalogs, name=item.name, catalog_id=item.catalog_id, description=item.description) # POST request name, description, catalog_id = convert_item_fields(request.form.get('name'), request.form.get('description'), request.form.get('catalog_id')) if name and description and catalog_id: item.name = name item.description = description item.catalog_id = catalog_id db_session.add(item) db_session.commit() flash('Item %s is updated' % item.name, 'info') return redirect(url_for('item.get_item', item_id=item.id)) else: flash('Name, description and catalog are required', 'warning') return render_template('items/edit.html', catalogs=catalogs, item=item, name=name, catalog_id=catalog_id, description=description)
def load_items(n=50): """ :param n: number of items to insert into database :return: None """ conditions = ['clean', 'okay', 'torn', 'incomplete'] description = ["A test description\nThis sheet is cool"] sheets = db_session.query(Sheetmusic).all() users = db_session.query(User).all() random.seed(0) for i in range(n): sm = random.choice(sheets) user = random.choice(users) item = Item() item.user = user item.sheetmusic = sm item.condition = random.choice(conditions) item.description = random.choice(description) # add 4 images to each item item.images = [ItemImage("{}_{}".format(user.username, uuid.uuid4())) for _ in range(4)] db_session.add(item) # print(item) db_session.commit()
def add_task(self, task: TODOTask) -> TODOTask: task.id = str(uuid.uuid4()) with db_session().begin(): db_session.add(task) return task
def create(name, host, users=None): room = Room(name, host.id) room.users.append(host) if users: for user in users: room.users.append(user) db_session.add(room) db_session.commit() return room
def wrapper_register(*args, **kwargs): message = args[0] if message is not None: chat = message.chat if Chat.query.filter(Chat.id == chat.id).first() is None: name = chat.first_name if chat.type == 'private' else chat.title new_chat = Chat(id=chat.id, name=name) db_session.add(new_chat) db_session.commit() func(*args, **kwargs)
def registerAsOneToOne(room, first, second): if first.id > second.id: first, second = second, first otor = OneToOneRoom(room.id, first.id, second.id) room.users.append(first) room.users.append(second) db_session.add(otor) db_session.commit() return otor
def some_todo_tasks(): tasks = [ TODOTask(str(uuid.uuid4()), 'Task 1'), TODOTask(str(uuid.uuid4()), 'Task 2'), TODOTask(str(uuid.uuid4()), 'Task 3'), ] for t in tasks: db_session.add(t) db_session.commit() return tasks
def client(app): client = app.test_client() with app.app_context(): if not db_session.query(User)\ .filter(User.username == 'test').one_or_none(): init_db() db_session.add(User( username='******', password='******', )) db_session.commit() yield client
def add_task(message): chat = Chat.query.filter(Chat.id==message.chat.id).first() text = message.text.split(' ', 1) if len(text) <= 1: bot.send_message(message.chat.id, "Gimme something to work with, man.") return task = Task(description=text[1], chat_id=chat.id) db_session.add(task) db_session.commit() bot.send_message(message.chat.id, f'Added task "{task}"')
def validate_and_save(self, update=False): """ Valida y guarda un turno, si falla levanta AssertionError con los errores encontrados """ errors = "" errors += validate_turno_tomado(self) errors += validate_email(self) errors += validate_phone_number(self) errors += validate_hora_correcta(self) errors += validate_centro_disponible(self) if errors: raise AssertionError(errors) if not update: db_session.add(self) db_session.commit()
def load_sheet_music(): with open(path.join(DATA_DIRECTORY, 'sheet_music.json'), 'r') as fh: data = json.load(fh) for sheet_music in data['sheet_music']: if not db_session.query(Sheetmusic).filter_by(title=sheet_music['title']).first(): instrumentation = sheet_music.pop('instrumentation', None) genres = sheet_music.pop('genre_tags', None) new_obj = Sheetmusic(**sheet_music) new_obj.parse_tags(instrumentation, Instrument, 'instrumentation') new_obj.parse_tags(genres, Genre, 'genre_tags') db_session.add(new_obj) # print("added", new_obj) db_session.commit()
def load_users(): with open(path.join(DATA_DIRECTORY, 'auth.json')) as fh: data = json.load(fh) for user in data['users']: if db_session.query(User).filter_by(email=user['email']).one_or_none() is None: addresses = user.pop('addresses') new_user_obj = User(**user) new_address_objs = [Address(**address) for address in addresses] new_user_obj.addresses = new_address_objs db_session.add(new_user_obj) # print("added", new_user_obj, new_address_objs) db_session.commit()
def load_trades(n=10): """ Create and store several trade items. :param n: number of trades to insert into database :return: None """ random.seed(0) users = db_session.query(User).all() for i in range(n): from_user, to_user = random.sample(users, 2) from_item, to_item = random.choice(from_user.items), random.choice(to_user.items) trade = Trade(user_from_id=from_user.id, user_to_id=to_user.id, item_from=from_item, item_to=to_item) db_session.add(trade) db_session.commit()
def render_new(filename, start, end, cut_type, client_num, title, gtv_match_id, map_number, player): if gtv_match_id == '': filename_orig = filename else: filename_orig = 'upload/' + str(gtv_match_id) + '_' + str(map_number) + '.tv_84' filename_cut = 'download/' + str(gtv_match_id) + '_' + str(map_number) + '_' + str(client_num) + '_' + str( start) + '_' + str(end) + '.dm_84' if gtv_match_id != '' and not os.path.exists(filename_orig): demo_url = app.gamestv.getDemosLinks(app.gamestv.getMatchDemosId(gtv_match_id))[int(map_number)] urllib.request.urlretrieve(demo_url, filename_orig) app.Libtech3.cut(flask_app.config['PARSERPATH'], filename_orig, filename_cut, int(start) - 2000, end, cut_type, client_num) result = tasks.render.delay(flask_app.config['APPHOST'] + '/' + filename_cut, start,end, title, player.name if (player!=None) else None, player.country if (player!=None) else None,etl=False) r = Render(result.id, title, gtv_match_id, map_number, client_num, player.id if (player!=None) else None ) db_session.add(r) db_session.flush() db_session.commit() return r.id
def create_view(): json_data = request.get_json() if not json_data: return return_non_success_json(400, {'message': 'No input data provided'}) # Validate and deserialize input message_schema = MessageSchema(only=('recipient_address', 'sender_address', 'subject', 'body')) try: data = message_schema.load(json_data) except ValidationError as err: return return_non_success_json(422, err.messages) message = Message(**data.data) db_session.add(message) db_session.flush() db_session.commit() return jsonify({'messages': 'ok'})
def cut(): print(request.form.get("longUrl")) longUrl = utils.convert(str(request.form.get("longUrl"))) req = u.query.filter(u.longUrl == longUrl).first() print(req) if (req != None): shortUrl = req.shortUrl else: shortUrl = utils.random_string(size=4) db_session.add(Urls(shortUrl, longUrl)) db_session.commit() response = {"status": True, "shortUrl": shortUrl, "longUrl": longUrl} print(longUrl) try: requests.get(response["longUrl"]) except: response["status"] = False return render_template('cut.html', response=response)
def update_view(): json_data = request.json if not json_data: return return_non_success_json(400, {'message': 'No input data provided'}) # Validate and deserialize input summary_schema = ExerciseSummarySchema(only=('created_at', 'subject')) try: data = summary_schema.load(json_data) except ValidationError as err: return return_non_success_json(422, err.messages) summary = ExerciseSummary(**data.data) db_session.add(summary) db_session.flush() db_session.commit() return jsonify({'messages': 'ok'})
def adminpassword(): """set admin password""" admin_username = "******" password = getpass.getpass() if len(password)<8: print "dame" return admin = User.query.get(1) if not admin: userrole = UserRole.query.get('admin') admin = User(admin_username, userrole) db_session.add(admin) admin.set_password(password) db_session.commit() db_session.remove() print "update successfully"
def adminpassword(): """set admin password""" admin_username = "******" password = getpass.getpass() if len(password) < 8: print "dame" return admin = User.query.get(1) if not admin: userrole = UserRole.query.get("admin") admin = User(admin_username, userrole) db_session.add(admin) admin.set_password(password) db_session.commit() db_session.remove() print "update successfully"
def validate_and_save(self, update=False, password_change=False): """ Valida que el usuario creado/modificado tenga formato válido. Si es válido lo actualiza en la base de datos, caso contrario devuelve los errores que existieron en las validaciones. """ errors = "" errors += validate_first_name(self) errors += validate_last_name(self) if not update: errors += validate_username(self) errors += validate_email(self) errors += validate_password(self) self.password = generate_password_hash(self.password) db_session.add(self) elif password_change: errors += validate_password(self) self.password = generate_password_hash(self.password) if errors: raise AssertionError(errors) db_session.commit()
def new(self, form, user): filename = secure_filename(form.archive.file.filename) # add Template to db newtemp = Template(form.subject.data, user, filename, len(form.archive.file.stream.getvalue()) / 1024, description=form.description.data, tags=form.tags.data) if not newtemp: flash("db error") abort(401) db_session.add(newtemp) db_session.commit() fileinfo = save_template_file(newtemp.id, form.archive.file, filename) newtemp.compressed_filelist = fileinfo.compressed_filelist newtemp.index_filename = fileinfo.index_filename db_session.commit() uncompress_template(newtemp.id, filename) make_thumbnail(newtemp.id, newtemp.index_filename)
def add_new_item(): """Route to new item page + create item""" catalogs = Catalog.get_all() # GET request if request.method == 'GET': return render_template('items/new.html', catalogs=catalogs) # POST request name, description, catalog_id = convert_item_fields(request.form.get('name'), request.form.get('description'), request.form.get('catalog_id')) if name and description and catalog_id: item = CatalogItem(name=name, description=description, catalog_id=catalog_id, user_id=g.current_user.id) db_session.add(item) db_session.commit() flash('Item %s is created' % item.name, 'info') return redirect(url_for('item.get_item', item_id=item.id)) else: flash('Name, description and catalog are required', 'warning') return render_template('items/new.html', name=name, catalog_id=catalog_id, description=description, catalogs=catalogs)
def update(self, template, form, user): filename = secure_filename(form.archive.file.filename) template.subject = form.subject.data template.description = form.description.data template.tags = [] for tag_name in form.tags.data: tag = Tag.query.filter(Tag.name==tag_name).first() or Tag(tag_name) template.tags.append(tag) template.modified_date = datetime.datetime.now() if len(filename) > 0: delete_template_files(template.id) template.filename = filename fileinfo = save_template_file(template.id, form.archive.file, filename) template.compressed_filelist = fileinfo.compressed_filelist template.index_filename = fileinfo.index_filename uncompress_template(template.id, filename) make_thumbnail(template.id, template.index_filename) db_session.add(template) db_session.commit()
def seed_db(): user1 = User(name='user1', email='*****@*****.**') user2 = User(name='user2', email='*****@*****.**') db_session.add(user1) db_session.add(user2) db_session.commit() catalog_datas = [ { 'name': 'Skating' }, { 'name': 'Hockey' }, ] for catalog in catalog_datas: new_catalog = Catalog(name=catalog['name']) db_session.add(new_catalog) db_session.commit()
def save(self, username, password): user = UserTable(username=username, password=password) db_session.add(user) db_session.commit()
def process_match(match_id, render=True, parse_players=False): hs = '' for map_num, demo_url in enumerate( app.gamestv.getDemosLinks(app.gamestv.getMatchDemosId(match_id))): try: parser_out = web.export_get(str(match_id), str(map_num), False, False) except (HTTPError, URLError): print('not on ftp') urllib.request.urlretrieve(demo_url, 'upload/demo.tv_84') #except HTTPError: arg = flask_app.config['INDEXER'] % ('demo.tv_84') subprocess.call([flask_app.config['PARSERPATH'], 'indexer', arg]) try: web.export_save(str(match_id), map_num) except TimeoutError: print("ftp timeout") parser_out = web.parse_output( open('download/out.json', 'r').readlines()) if parse_players: g_players = app.gamestv.getPlayers(match_id) db_players = [] for g_player in g_players: p = Player.query.filter(Player.name.ilike( g_player['name'])).first() if p == None: p = Player(g_player['name'], g_player['country']) db_session.add(p) db_players.append(p) g_player['db'] = p db_session.flush() db_session.commit() for player in parser_out['players']: player['db'] = None for g_player in g_players: if player['szCleanName'].lower().find( g_player['name'].lower()) != -1: #todo: this will not work now player['db'] = { 'id': g_player['db'].id, 'name': g_player['db'].name, 'country': g_player['db'].country } break max_hs_player = max(parser_out['players'], key=lambda x: x['hits'][1]) hs += 'Most headshots on ' + parser_out['demo'][ 'szMapName'] + ': ' + max_hs_player['szCleanName'] + ' - ' + str( max_hs_player['hits'][1]) hs += ' [url=' + flask_app.config['APPHOST'] + '/export/' + str( match_id) + '/' + str(map_num) + ']more stats...[/url]' + '\n' if render: for player in parser_out['players']: for spree in player['sprees']: web.render_new( None, spree[0]['dwTime'] - 2000, 2000 + spree[len(spree) - 1]['dwTime'], 1, player['bClientNum'], player['szCleanName'] + 's ' + str(len(spree)) + '-man kill', match_id, map_num, player['db']) return i = Render.query.filter(Render.gtv_match_id == match_id).count() comment = 'Rendered [url=' + flask_app.config['APPHOST'] + '/export/' + str( match_id) + ']' + str(i) + ' highlights[/url] from this match\n' comment += hs print(comment) if flask_app.config['APPHOST'] != 'http://localhost:5111': app.gamestv.postComment(comment, match_id)
def save(self): db_session.add(self) self._flush() return self
def save(self): if self.id is None: db_session.add(self) db_session.flush()
# coding=utf-8 from app.db.project import ProjectTable from app.db import db_engine, db_session try: ProjectTable.__table__.create(bind=db_engine) db_session.add(ProjectTable('Hello World!')) db_session.add(ProjectTable(u'こんにちは、世界!')) db_session.commit() except: pass
def create(room, user, content): message = Message(room.id, user.id, content) db_session.add(message) db_session.commit() return message
def save(self, title, text, username): entry = EntryTable(title, text, username) db_session.add(entry) db_session.commit()
def load_database(): """ Carga los datos iniciales en la base de datos """ start = time.time() data_loaded = False for row in states: row_exists = s.query.filter(s.name == row).first() if not row_exists: data_loaded = True new_state = s(name=row) db_session.add(new_state) for row in config_tables: columns = row.split("||") row_exists = c.query.filter(c.name == columns[0]).first() if not row_exists: data_loaded = True new_config = c(name=columns[0], value=columns[1]) db_session.add(new_config) for row in permissions_table: row_exists = p.query.filter(p.name == row).first() if not row_exists: data_loaded = True new_permission = p(name=row) db_session.add(new_permission) for row in roles_table: row_exists = r.query.filter(r.name == row).first() if not row_exists: data_loaded = True new_role = r(name=row) db_session.add(new_role) for row in types_table: row_exists = t.query.filter(t.name == row).first() if not row_exists: data_loaded = True new_type = t(name=row) db_session.add(new_type) if data_loaded: db_session.commit() admin_role = r.query.filter(r.name == "administrador_del_sistema").first() for row in permissions_table: permission = p.query.filter(p.name == row).first() if permission not in admin_role.permissions: admin_role.permissions.append(permission) data_loaded = True operator_role = r.query.filter( r.name == "operador_centro_de_ayuda").first() for row in operator_permissions_table: permission = p.query.filter(p.name == row).first() if permission not in operator_role.permissions: operator_role.permissions.append(permission) data_loaded = True admin_exists = u.query.filter(u.username == "admin").first() if not admin_exists: data_loaded = True new_user = u(first_name="Admin", password=generate_password_hash("admin123"), email="*****@*****.**", last_name="Gonzalez", username="******") db_session.add(new_user) if data_loaded: db_session.commit() admin_exists = u.query.filter(u.username == "admin").first() role = r.query.filter(r.name == "administrador_del_sistema").first() admin_exists.roles.append(role) db_session.commit() end = time.time() if data_loaded: print("Tiempo de carga de base de datos inicial: " + str(end - start))
def save_to_db(self): """ Save the change to the database """ db_session.add(self) db_session.commit()
def add_to_db(params, db_session, current_order): update_stmt = update(Inventory).where( Inventory.product_id == bindparam('prod')).values( {Inventory.quantity: Inventory.quantity - bindparam('qty')}) db_session.execute(update_stmt, params) db_session.add(current_order)