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 renders_list(): if request.method == 'GET': renders = Render.query.order_by(desc(Render.id)).all() # for render in renders: # if render.streamable_short == None: # result = tasks.render.AsyncResult(render.celery_id) # if result.successful(): # render.streamable_short = result.get() db_session.commit() return render_template('renders.html', renders=renders) if request.method == 'POST': form = RenderForm(request.form) cut_form = CutForm(request.form) mp = None if cut_form.data['gtv_match_id']!='' and cut_form.data['client_num']!='': mp = MatchPlayer.query.filter(MatchPlayer.gtv_match_id == int(cut_form.data['gtv_match_id']),MatchPlayer.client_num == int(cut_form.data['client_num'])).first() if mp != None: db_player = Player.query.filter(Player.id == mp.player_id).first() else: db_player=None try: render_id = render_new('upload/' + cut_form.data['filename'], str(int(cut_form.data['start'])), cut_form.data['end'], cut_form.data['cut_type'], cut_form.data['client_num'], form.data['title'], cut_form.data['gtv_match_id'], cut_form.data['map_number'],db_player) except Exception as e: flash(str(e)) #return redirect(url_for('export')) return redirect(url_for('export',_anchor='render-form'), code=307) return redirect(url_for('render_get', render_id=render_id))
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 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 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 inviteMany(room, users): for user in users: room.users.append(user) for ot in room.oto: room.oto.remove(ot) db_session.delete(ot) 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 validate_and_save(self, update=False, pdf=None): """ Valida que el centro 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 = "" self.web = sql_and_tag_escape(self.web) self.name = sql_and_tag_escape(self.name) self.address = sql_and_tag_escape(self.address) self.municipio = sql_and_tag_escape(self.municipio) errors += self.validate_name() errors += self.validate_address() errors += self.validate_email() errors += self.validate_phone() errors += self.validate_url() errors += self.validate_opens_closes() errors += self.validate_coordinates() errors += self.validate_municipio() errors += self.validate_protocol(pdf) if not update: db_session.add(self) if errors: raise AssertionError(errors) db_session.commit()
def destroy(id): """ Elimina un turno especifico de la base de datos """ turno = Turno.query.filter_by(id=sql_and_tag_escape(str(id))).first() if not turno: abort(404) db_session.delete(turno) db_session.commit() return redirect(url_for('turns.index'))
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 despublicar(id): """ Metodo para cambiar el estado de publicacion de un metodo a 'Despublicado' """ center = Center.query.filter_by(id=id).first() if not center: abort(404) center.publication_state = False db_session.commit() return redirect(url_for('centers.show', id=id))
def delete_item(item_id, item): """Route to item's delete page + delete item""" # GET request if request.method == 'GET': return render_template('items/delete.html', item=item) # POST request item_name = item.name db_session.delete(item) db_session.commit() flash('Item %s is removed' % item_name, 'info') return redirect(url_for('catalog.home_page'))
def destroy(id): """ Eliminar un centro de la base de datos """ centers = Center.query.filter_by(id=id).first() if not centers: abort(404) centers.state = 4 centers.delete_date = datetime.now() centers.publication_state = False db_session.commit() return redirect(url_for('centers.index'))
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 render_get(render_id): render = Render.query.filter(Render.id == render_id).first() if render.streamable_short != None: return render_template('render.html', render=render) result = tasks.render.AsyncResult(render.celery_id) if request_wants_json(): data = result.result or result.state # print(data) return jsonify(data) if result.successful(): render.streamable_short = result.get() db_session.commit() return render_template('render.html', render=render)
def gconnect(): """Use google one time token to validate user""" code = request.data try: # Upgrade the authorization code into a credentials object oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(code) except FlowExchangeError: return render_json_error('Failed to upgrade the authorization code.', 401) # Check that the access token is valid. access_token = credentials.access_token url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token) result = json.loads(httplib2.Http().request(url, 'GET')[1]) # If there was an error in the access token info, abort. if result.get('error') is not None: return render_json_error(result.get('error'), 500) # Verify that the access token is valid for this app. if result['issued_to'] != CLIENT_ID: return render_json_error("Token's client ID does not match app's.", 401) # Get user info userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = answer.json() # Try to find user in our db user = db_session.query(User).filter(User.email == data['email']).first() # If user not in db, create new if not user: user = User(name=data['name'], email=data['email'], picture=data['picture']) db_session.add(user) db_session.commit() # Store the access token in the session for later use. session['access_token'] = credentials.access_token # Store user id for user authentication in next request session['user_id'] = user.id flash('Successfully login', 'info') return render_json({'message': 'Successfully login'})
def destroy(username): """ Eliminar un usuario de la base de datos """ users = User.query.filter_by(username=username).first() if not users: abort(404) # Si llega hasta aca para eliminarse, chequea que no se elimine a si mismo if users.username == session.get("username"): flash("No se puede eliminarse a si mismo.", "error") return redirect(url_for('users.index')) db_session.delete(users) db_session.commit() return redirect(url_for('users.index'))
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 get_task(message): tasks = Task.query.filter(Task.chat_id==message.chat.id).all() if len(tasks) == 0: bot.send_message(message.chat.id, "There's nothing for you to do.") return task = tasks[int(random()*len(tasks))] db_session.delete(task) db_session.commit() bot.send_message( message.chat.id, "Your next mission, should you choose to accept it, is:\n\n" + \ task.description)
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 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 update(): """ Actualiza la configuracion a partir de los campos rellenados en el formulario de configuracion o flashea un mensaje de error si falla alguna validacion """ if(check_token(request.form["csrf_token"])): CSRF_TOKEN = request.form["csrf_token"] form = request.form.copy() if "home.habilitado" in request.form.keys(): form["home.habilitado"] = "TRUE" else: form["home.habilitado"] = "FALSE" errors = "" del form["csrf_token"] for element in form: original = Configuration.query.filter_by(name=element).first() original.value = sql_and_tag_escape(form[element]) error = validate(original) if error: errors += error if not errors: flash("Configuración guardada correctamente", "success") db_session.commit() return redirect(url_for("configuration.index")) else: flash_messages(errors) configurations = Configuration.query.order_by( Configuration.name ).all() configs = {} first_name = '' for element in configurations: name = element.name.split('.') if first_name != name[0]: first_name = name[0] configs_content = [] configs[name[0]] = configs_content content_elements = [element.name, form[element.name]] configs[name[0]].append(content_elements) return(render_template( "configuration/configuration.html", configs=configs, CSRF_TOKEN_STRING=CSRF_TOKEN )) else: return render_template("configuration/configuration.html")
def getOneToOneRoom(first, second): current_user = first if first.id > second.id: first, second = second, first otor = db_session.query(OneToOneRoom).filter(OneToOneRoom.firstId == first.id)\ .filter(OneToOneRoom.secondId == second.id).first() if not otor: room = create(None, first) registerAsOneToOne(room, first, second) else: room = get(otor.roomId) if current_user not in room.users: room.users.append(current_user) db_session.commit() return room
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 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 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 reject(id): """ Método para rechazar un centro de ayuda. """ center = Center.query.filter_by(id=id).first() if not center: abort(404) center.publication_state = False estado = State.query.filter_by(name="Pendiente").first() estado.centers.remove(center) estado = State.query.filter_by(name="Rechazado").first() estado.centers.append(center) db_session.commit() from_page = request.form["from_page"] if from_page == "pending": return redirect(url_for('centers.pending_index')) elif from_page == "center_show": return redirect(url_for('centers.show', id=id))
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 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 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 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 reset_all_tasks(): today = dt.datetime.today() weekday = today.weekday() month = today.month hour = today.hour for task in db_session.query(Task).all(): if not task.hours: continue schedule = json.loads(task.hours.replace("\'", "\"")) if not (schedule['month_of_year'] == '*' or month in set( [int(mnt) for mnt in schedule['month_of_year'].split(',')])): continue if not (schedule['day_of_week'] == '*' or weekday in set( [int(week) for week in schedule['day_of_week'].split(',')])): continue hours = set([int(hr) for hr in schedule['hour'].split(',')]) if not hour in hours: continue print(task) task.completed = False db_session.flush() db_session.commit()
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 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 save(self, username, password): user = UserTable(username=username, password=password) db_session.add(user) db_session.commit()
def delete_having_no_template(self): items = Tag.query.all() for item in items: if len(item.templates)==0: db_session.delete(item) db_session.commit()
# 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 delete(self, template): db_session.delete(template) db_session.commit() delete_template_files(template.id) TagModel().delete_having_no_template()
def save(self, title, text, username): entry = EntryTable(title, text, username) db_session.add(entry) db_session.commit()