def edit(id): session = db.session() try: test = session.query(Test).filter(Test.id == id).one() except NoResultFound: return render_template('layout.html', error='No such test') form = TestEditingForm(request.form, test) all_attributes = db.session().query(Attribute).all() if request.method == 'POST' and form.validate(): # length of any of nested lists must be no less than that of respective form's list for i in range(len(form.questions)): if i >= len(test.questions): test.questions.append(Question()) for j in range(len(form.questions[i].choices)): if j >= len(test.questions[i].choices): test.questions[i].choices.append(Choice()) for k in range(len(form.questions[i].choices[j].associations)): if k >= len(test.questions[i].choices[j].associations): test.questions[i].choices[j].associations.append(Association()) form.populate_obj(test) session.add(test) session.commit() flash('Test updated') return redirect(url_for('general.admin')) attr_id_to_name = {a.id: a.name for a in all_attributes} return render_template('edit_test.html', form=form, all_attributes=all_attributes, attr_id_to_name=attr_id_to_name)
def test_expired_confirmation_token(self): u = User(password='******') db.session(u) db.session.commit() token = u.generate_confirmation_token(1) time.sleep(2) self.assertFalse(u.confirm(token))
def create(): form = AttributeEditingForm(request.form) if request.method == "POST" and form.validate(): db.session().add(Attribute(name=form.name.data)) db.session().commit() flash("Attribute added") return redirect(url_for("general.admin")) return render_template("edit_attribute.html", form=form, heading="New attribute")
def fixtures(): db.session() repo_names = ['6.0.devel', '6.1.devel', '6.0.release', '6.1.release'] for repo_name in repo_names: repo_path = os.path.join(app.config['BASE_PATH'], repo_name) repo = Repo(name=repo_name, path=repo_path, comment=repo_name) db.session.add(repo) db.session.commit() snapshot = Snapshot(name=repo_name, type='master', path=repo_path, comment="", repo_id=repo.id) db.session.add(snapshot) db.session.commit() generate_matadata(repo_path, repo_path)
def newsdetail(): news_id = request.args.get('news_id', 1, type=int) detail = db.Query([NewsBasic, NewsDetail], db.session()).filter(NewsBasic.id == news_id, NewsBasic.articleId == NewsDetail.id).first() if detail.NewsBasic.provinceId != 'all': provinceName = db.Query(Province.province_name, db.session()).filter(Province.province_id == detail.NewsBasic.provinceId).scalar() if detail.NewsBasic.majorId != 'all': majorId = str(detail.NewsBasic.majorId).split('_')[1] majorName = db.Query(Major.major_name, db.session()).filter(Major.major_id == majorId, Major.province_name == provinceName).first()[0] else: majorName = '全部' else: provinceName = '全部' majorName = '全部' return jsonify({'result':'true', 'msg':NewsDetailNode(detail, majorName, provinceName).pack_res()})
def add_part(self): session = db.session() prt = Material(self.part.data, self.vendor.data, self.qty.data, self.pitch.data, self.type.data) session.add(prt) session.commit() session.close() print('add part ok')
def result(id): session = db.session() try: test = session.query(Test).filter(Test.id == id).one() except NoResultFound: return render_template('layout.html', error='No such test') answers = request.form.to_dict() score = {} for question in answers.keys(): question, answer = int(question), int(answers[question]) assocs = test.questions[question].choices[answer].associations aids = [a.attribute.id for a in assocs] for a in aids: if a not in score: score[a] = 0 score[a] += 1 if score.values(): maxval, total = max(score.values()), sum(score.values()) else: maxval, total = 1, 1 flash("It looks like the test you've just tried to pass hasn't been set up correctly. Sorry for that!") attributes = session.query(Attribute).all() scorelist = [{'name': a.name, 'score': score[a.id]} for a in attributes if a.id in score and score[a.id] > 0] return render_template('result.html', scorelist=scorelist, maxval=maxval, total=total, heading=test.title, title="Test result")
def create_admin_user(): session = db.session() admin = User('0000001', 'admin', 'admin', role.admin, status.active) user = User('0000002', 'user', 'user', role.user, status.active) session.add(admin) session.add(user) session.commit()
def _delete_slide(slide_id): """ Helper function to delete a slide in SQLAlchemy """ db_session = db.session() # Get the slide if it exists first try: slide = db_session.query(Slide).get(slide_id) except Exception as ex: return jsonify( status='error', message='Delete slide exception: {}'.format(ex.message) ) # Delete the slide now db_session.delete(slide) # Commit db_session.commit() return jsonify( status='success', message='Deleted slide successfully' )
def slide_viewer(): """ Main slide viewer controller """ # Get all slides from the database slides = db.session().query(Slide).all() return render_template("slides/slide.html", slides=slides)
def create_material(): session = db.session() for tst in range(100): material_roll = Material('2007-000%s' % tst, 'GMT', 1000, 2, type.roll) material_pal = Material('3801-000%s' % tst, 'FCK', 72, 0, type.pallete) session.add(material_roll) session.add(material_pal) session.commit()
def save_part(self): session = db.session() part = session.query(Material).filter_by(part=self.part.data).first() part.vendor = self.vendor.data part.qty = self.qty.data part.pitch = self.pitch.data part.type = self.type.data session.commit() print('save part ok')
def material_delete(part_name): session = db.session() part = Material.query.filter_by(part=part_name).first() if part is not None: if path.exists(dir + '/app/static/img/material/%s_%s.png' % (part.part, part.vendor)): remove_file(dir + '/app/static/img/material/%s_%s.png' % (part.part, part.vendor)) session.delete(part) session.commit() return redirect(url_for("material_list"))
def remove(id): session = db.session() try: test = session.query(Test).filter(Test.id == id).one() except NoResultFound: return render_template('layout.html', error='No such test') session.delete(test) session.commit() flash('Test removed') return redirect(url_for('general.admin'))
def single_validation(topic_id): selected_topic = db.session.query(Topic).filter(Topic.topic_id == topic_id).first() speakers_list = list() speaker1 = db.session().query(User).filter(User.user_id == selected_topic.speaker1).first() speaker2 = db.session().query(User).filter(User.user_id == selected_topic.speaker2).first() speaker3 = db.session().query(User).filter(User.user_id == selected_topic.speaker3).first() speaker4 = db.session().query(User).filter(User.user_id == selected_topic.speaker4).first() speaker5 = db.session().query(User).filter(User.user_id == selected_topic.speaker5).first() if speaker1 is not None: speakers_list.append(speaker1) if speaker2 is not None: speakers_list.append(speaker2) if speaker3 is not None: speakers_list.append(speaker3) if speaker4 is not None: speakers_list.append(speaker4) if speaker5 is not None: speakers_list.append(speaker5) return render_template('topic/single_validation.html', topic=selected_topic, speakers_list=speakers_list)
def edit(id): try: attr = db.session().query(Attribute).filter(Attribute.id == id).one() except NoResultFound: return render_template("layout.html", error="No such atribute") form = AttributeEditingForm(request.form) if request.method == "GET": form.name.data = attr.name form.id.data = attr.id if request.method == "POST" and form.validate(): attr.name = form.name.data db.session().add(attr) db.session().commit() flash("Attribute saved") return redirect(url_for("general.admin")) return render_template("edit_attribute.html", form=form, heading="Edit attribute")
def get_images(): try: allImages = db.session().query(Image).all() res = [img.serialize for img in allImages] except Exception as e: import logging logging.error(e) res = None return res
def refresh_datasources(self): session = db.session() for cluster in session.query(models.Cluster).all(): cluster.refresh_datasources() cluster.metadata_last_refreshed = datetime.now() flash( "Refreshed metadata from cluster " "[" + cluster.cluster_name + "]", 'info') session.commit() return redirect("/datasourcemodelview/list/")
def create(): form = TestEditingForm(request.form) if request.method == 'POST' and form.validate(): session = db.session() t = Test(title=form.title.data, description=form.description.data) for qf in form.questions: q = Question(text=qf.text.data) t.questions.append(q) for of in qf.choices: o = Choice(text=of.text.data) q.choices.append(o) for af in of.associations: a = Association(attribute_id=af.attribute_id.data, choice_id=af.choice_id.data) o.associations.append(a) session.add(t) session.commit() flash("Test added") return redirect(url_for('general.admin')) all_attributes = db.session().query(Attribute).all() return render_template('edit_test.html', form=form, all_attributes=all_attributes)
def signup(): # If sign in form is submitted form = SignupForm(request.form) # Verify the sign in form if form.validate_on_submit(): user = User(name=form.name.data, email=form.email.data, password=generate_password_hash(form.password.data)) s = db.session() s.add(user) s.commit() return redirect(url_for('auth.signin')) return render_template("auth/signup.html", form=form)
def remove(id): try: attr = db.session().query(Attribute).filter(Attribute.id == id).one() except NoResultFound: return render_template("layout.html", error="No such atribute") for assoc in attr.associations: db.session().delete(assoc) db.session().delete(attr) db.session().commit() flash("Attribute removed") return redirect(url_for("general.admin"))
def validate_part(self, field): if len(field.data) != 11: raise ValidationError('Введите парт-номер в формате 1234-123456') else: if field.data[4] != '-': raise ValidationError('Введите парт-номер в формате 1234-123456') else: session = db.session() part = session.query(Material).filter_by(part=field.data).first() session.close() print(part) if part: raise ValidationError('Материал %s уже существует в системе!' % field.data) return
def get_member(cls, id): session = db.session() # set variables from id name = "" password = "" email = "" phone = "" reputation = "" try: existing_member = cls(name=name, password=password, email=email, phone=phone) except: return None existing_member.__reputation = reputation
def save_user(self): session = db.session() user_db = session.query(User).filter_by(gen=self.gen.data).first() user_db.login = self.login.data user_db.full_name = self.full_name.data user_db.user_role = self.role.data user_db.email = self.email.data user_db.birthday = self.birthday.data user_db.invite_date = self.invite_date.data user_db.status = self.status.data if self.reset_pw.data is True: user_db.password = generate_password_hash(user_db.login) session.commit() print('save ok')
def replyComment(): if request.form['user_id']: topic_id = int(request.form['topic_id']) reply_id = int(request.form['reply_id']) parentcomment = Comments.query.get(reply_id) reply_floor_no = db.Query(func.count(Comments.comment_id), db.session()).filter(Comments.topic_id == topic_id, Comments.comment_id <= reply_id).first()[0] comment = Comments(content=request.form['content'], pub_time=func.unix_timestamp(), images=request.form['images'], status=1, \ topic_id=topic_id, forum_id=int(request.form['forum_id']), user_id=request.form['user_id'], user_name=request.form['user_name'], \ reply_id=reply_id, reply_floor_no=reply_floor_no, reply_user_id=parentcomment.user_id, reply_user_name=parentcomment.user_name, \ reply_content=parentcomment.content) db.session.add(comment) db.session.commit() return jsonify({'result':'true'}) else: return jsonify({'result':'false', 'msg':'The request does not have a user_id'})
def getcomments(): articleId = request.args.get('articleId', 1, type=int) page = request.args.get('page', 1, type=int) perpage = request.args.get('perpage', 10, type=int) #子查询方法 ParentComment = aliased(NewsComment) ParentUser = aliased(Account) query = db.Query([NewsComment, Account.nickname, Account.profileUrl, ParentComment.content.label('parentcomment'), \ ParentUser.nickname.label('parentuser')],db.session()).filter(NewsComment.articleId == articleId) \ .outerjoin(Account, Account.uid == NewsComment.uid).outerjoin(ParentComment, ParentComment.id == NewsComment.parentId). \ outerjoin(ParentUser, ParentUser.uid == ParentComment.uid).order_by(NewsComment.id).paginate(page, perpage, False) comments = query.items pagenum = query.pages return jsonify({'result':'true', 'msg':{'comments':[CommentNode(c).pack_res() for c in comments]}, 'page':page, 'pagenum':pagenum})
def generarMediciones(x): i = 1 a = datetime.utcnow() s = db.session() v = random.randint(10, 20) while i < 199: m = models.Medicion() i=i+1 m.sensor = x m.timestamp = a + timedelta(seconds=i*30) v =random.randint(v-3, v+2) if v <= 1: v = 1 m.valor = v s.add(m) s.commit()
def get_slides(): """ Gets all slides stored in the database and returns them in json format """ db_session = db.session() slides = db_session.query(Slide).all() json_ret = [] for slide in slides: json_ret.append( { 'id': slide.id, 'title': slide.title, 'bg_image': slide.bg_image_uri, 'bg_color': slide.bg_color, 'text': slide.text, }) return jsonify(slides=json_ret)
def run(self, pid=None): if pid is None: logging.critical("Please set --pid param") sys.exit() # Project info project_info = CobraProjects.query.filter_by(id=pid).first() if project_info.repository[0] == '/': project_directory = project_info.repository else: project_directory = Git(project_info.repository).repo_directory # Third-party ID vuln_all = CobraVuls.query.all() vuln_all_d = {} for vuln in vuln_all: vuln_all_d[vuln.id] = vuln.third_v_id # Not fixed vulnerabilities result_all = db.session().query(CobraRules, CobraResults).join(CobraResults, CobraResults.rule_id == CobraRules.id).filter( CobraResults.project_id == pid, CobraResults.status < 2 ).all() for index, (rule, result) in enumerate(result_all): # Rule result_info = { 'task_id': result.task_id, 'project_id': result.project_id, 'project_directory': project_directory, 'rule_id': result.rule_id, 'result_id': result.id, 'file_path': result.file, 'line_number': result.line, 'code_content': result.code, 'third_party_vulnerabilities_name': rule.description, 'third_party_vulnerabilities_type': vuln_all_d[rule.vul_id] } # White list white_list = [] ws = CobraWhiteList.query.with_entities(CobraWhiteList.path).filter_by(project_id=result.project_id, rule_id=result.rule_id, status=1).all() if ws is not None: for w in ws: white_list.append(w.path) Core(result_info, rule, project_info.name, white_list).repair()
def update_db(): with app.app_context(): session = db.session() db.metadata.create_all(db.engine) session.merge( Player( id=1, name="Tom Manley", goals=0, picture="images/tom.manley.jpg" ) ) session.merge( Player( id=2, name="Peter Yamashiro", goals=0, picture="images/unknown.jpg" ) ) session.commit()
def create_role_permission(): payload = request.get_json() role = Role.query.filter_by(role_code=payload['role_code']).first() if not role: return jsonify({'error' : 'Invalid role code!','status': 400}), 400 try: permission = Permission( read = payload['read'] write = payload['write'] add = payload['add'] delete = payload['delete'] role_code = role.role_code controller = payload['controller'] status = 1 updated_by = 'admin') db.session.add(permission) db.session.commit() except exc.IntegrityError as e: db.session().rollback() return jsonify({'error' : str(e.args),'status': 400}), 400 pass return jsonify({'message' : 'New Role Permission has created!','status': 200}), 200 # update a permission for role @app.route('/role/permissions/<role_code>/<controller>', methods=['PUT']) @jwt_required def update_role_permission(role_code, controller): role = Role.query.filter_by(role_code=role_code).first() if not role: return jsonify({'error' : 'Invalid role code!','status': 400}), 400 if controller == "": return jsonify({'error' : 'Role controller not fount!','status': 404}), 404 permission = Permission.query.filter_by(role_code=role_code, controller=controller).first() if not permission: return {'message': 'Data not found!','status': 404}, 404 else: payload = request.get_json() try: permission.read = payload['read'] permission.write = payload['write'] permission.add = payload['add'] permission.delete = payload['delete'] permission.role_code = payload['role_code'] permission.controller = payload['controller'] permission.status = payload['status'] permission.updated_by = get_jwt_identity() db.session.add(permission) db.session.commit() except exc.IntegrityError: db.session().rollback() return jsonify({'error' : 'Something error!','status': 400}), 400 pass return jsonify({'message' : 'Role Permission updated!','status': 200}), 200
def get_teacher(name, surname, patronymic): teacher = db.session().query(Teacher).filter( Teacher.name.like(name), Teacher.surname.like(surname), Teacher.patronymic.like(patronymic)).one() return teacher
def login(): form = LoginForm() if request.method == 'POST': if g.user is not None and g.user.is_authenticated: return redirect(url_for('index')) if form: username = form.username.data password = form.password.data remember_me = form.remember_me.data try: userObj = db.session.query( models.User).filter_by(username=username).first() passval = userObj.check_password(password) if passval: app.logger.info("User %s logged in" % userObj.username) login_user(userObj, remember=remember_me) g.current_user = userObj flash('You have logged in successfully') return redirect(url_for('index')) except AttributeError: ''' If LDAP auth is enabled, check the directory ''' try: dn = search_ldap(basedn=config.ldap_base_dn, username=username) if dn: sesh = db.session() check_credentials(user=dn, plaintext_pw=password) try: #TODO: We shouldn't be calling Sync here, another function proably needs to be created to sync a single user, but this works for now sync_roles() user_object = login_from_dn(sesh, dn) login_user(user_object) except AttributeError: flash( "You entered correct LDAP credentials, " "but this user is not authorized to access any pages. " "Check your LDAP group membership and MADST configuration." ) return render_template( 'login.html', title='Sign In', version_number=version_number, form=form) g.current_user = user_object flash("Directory Login successful.") return redirect(url_for('index')) except LdapBindError: flash("Incorrect username or password.") app.logger.info( "User {} attempted domain login with incorrect information." .format(username)) except LdapConnectError: flash( "The Directory server failed to respond, please contact your administrator." ) app.logger.info( "User {} loookup on directory server {} failed.". format(username, config.ldap_server)) flash("Account information not found or password incorrect.") return render_template('login.html', title='Sign In', version_number=version_number, form=form) # app.logger.info('User {0} attempted to login with incorrect password'.format(form.username.data)) # flash("Incorrect password") else: app.logger.info( 'User attempted to login with unknown username {0}'.format( form.username.data)) elif request.method == 'GET': return render_template('login.html', title='Sign In', version_number=version_number, form=form)
import socket import select from operator import itemgetter from app import app, db from app.models import System, newSystem session = db.session() with socket.socket() as server: server.bind(('192.168.10.11', 5002)) server.listen(50) to_read = [server] # add server to list of readable sockets. clients = {} while True: # check for a connection to the server or data ready from clients. # readers will be empty on timeout. readers, _, _ = select.select(to_read, [], [], 0.5) for reader in readers: if reader is server: client, address = reader.accept() #print('connected',address) clients[client] = address # store address of client in dict to_read.append( client) # add client to list of readable sockets else: # Simplified, really need a message protocol here. # For example, could receive a partial UTF-8 encoded sequence. data = reader.recv(4096) data = data.decode('utf-8') if not data: # No data indicates disconnect #print('disconnected',clients[reader]) to_read.remove(reader) # remove from monitoring del clients[reader] # remove from dict as well
def xtm(): form = MyForm() if form.validate_on_submit(): tm = False states = parser1.dict_parse(form.states.data) states_dict = literal_eval(states) input_s = parser1.dict_parse(form.input_symbols.data) input_symbols_dict = literal_eval(input_s) tape_s = parser1.dict_parse(form.tape_symbols.data) tape_symbols_dict = literal_eval(tape_s) initial_state_d = form.initial_state.data if form.left_end.data: left_end_d = form.left_end.data else: left_end_d = '>' try: transitions_d = literal_eval(form.prechody.data) except: transitions_d = {} success_message = ("Neočakávaná chyba v prechodovej funkcii") flash(success_message) if form.blank_symbol.data: blank_symbol_d = form.blank_symbol.data else: blank_symbol_d = '#' reject_state_d = form.reject_state.data final_states_d = form.final_states.data try: xdtm = XDTM( states = states_dict, input_symbols= input_symbols_dict, tape_symbols= tape_symbols_dict, left_end = left_end_d, transitions = transitions_d, initial_state = initial_state_d, blank_symbol = blank_symbol_d, reject_state = reject_state_d, final_states = final_states_d ) if xdtm: tm = True except(exceptions.InvalidStateError,exceptions.InvalidSymbolError,exceptions.MissingStateError,exceptions.MissingSymbolError, exceptions.InitialStateError,exceptions.FinalStateError,exceptions.RejectStateError,exceptions.LeftEndError, exceptions.RejectionError,exceptions.InvalidDirectionError,exceptions.Badcounttapes) as err: tm = False success_message = (err) flash(success_message) if tm: try: tmachine = Tmachine(definicia= form.funkcia.data,tm_d_n_x='xtm', states =states,input_symbols = input_s, tape_symbols = tape_s,left_end = left_end_d, transitions = form.prechody.data, initial_state = initial_state_d, blank_symbol = blank_symbol_d,reject_state = reject_state_d, final_states = final_states_d) db.session.add(tmachine) db.session.commit() success_message = ('Nový viac páskový DTM: '+form.funkcia.data+' je vytvorený') flash(success_message) return redirect(url_for('index')) except exc.IntegrityError: db.session().rollback() tm = False success_message = ("Definícia/Názov TM už existuje prosím zvolte iný názov") flash(success_message) return render_template('xtm.html', title='XTM', form=form)