def post(self): parser = reqparse.RequestParser(bundle_errors=True) parser.add_argument('volumne_id', required=True) parser.add_argument('start_time', required=True) parser.add_argument('end_time', required=True) args = parser.parse_args() vol_id = args['volumne_id'] start_s = args['start_time'] end_s = args['end_time'] if vol_id is None or start_s is None or end_s is None: abort(400, message='must supply volumne_id, start_time, end_time') vol = Volumne.query.get(vol_id) if vol is None: abort(400, message='volumne not exist') old_apply_fors = ApplyFor.query.filter_by(volumne_id=vol_id, user_id=g.user.id) for old_apply_for in old_apply_fors: if old_apply_for.denied: continue abort(400, message=u'you already have a request on volumne:{}'.format(vol.name)) start_t = datetime.datetime.strptime(start_s, '%Y-%m-%d %H:%M:%S') end_t = datetime.datetime.strptime(end_s, '%Y-%m-%d %H:%M:%S') now = datetime.datetime.now() if end_t <= now or start_t >= end_t: print "%s:%s:%s" % (now, start_t, end_t) abort(400, message="end time:{} must after start time:{}, and after now{}".format(end_s, start_s, now)) apply_for = ApplyFor(g.user.id, vol_id, start_t, end_t) db.session.add(apply_for) db.session.commit() log_info = u'{} 申请借阅档案卷:{}, {}'.format(g.user.username, apply_for.volumne.name, apply_for.volumne.id) Log.logging(g.user.id, datetime.datetime.now(), 'borrow authority', log_info) return '', 204
def add_post(title, content, tag): username = session['username'] person_id = session['id'] post = Blogpost(title=title, username=username, content=content, date=datetime.now(), user_id=person_id, tag=tag) post_exists = db.session.query(Blogpost.id).filter_by(title=title).first() if title == '' or username == '' or content == '' or tag == '': log = Log("All fields of the form must be filled in!") interceptor_manager.execute(log) raise Exception elif post_exists: log = Log("This title already exists, choose another!") interceptor_manager.execute(log) raise Exception else: composite = add_content_composite.Composite() composite.add(post) pub_sub = notifications.PublisherSubscriber() pub_sub.notify_subscribed_users() log = Log("Post added!") interceptor_manager.execute(log)
def approval(): user = User.objects.get(email=request.form['email']) if request.form['approval'] == 'True': # Registrierungsanfrage akzeptieren user.authorized = True user.save() # save in log user = User.objects.get(email=current_user.email) Log(user=user, category='approval', text='Hat die Anfrage von {} {} akzeptiert.'.format( user['firstname'], user['lastname'])).save() elif request.form['approval'] == 'False': # Registrierungsanfrage ablehnen user.delete() # save in log user = User.objects.get(email=current_user.email) Log(user=user, category='approval', text='Hat die Anfrage von {} {} abgelehnt.'.format( user['firstname'], user['lastname'])).save() return redirect(url_for('main.verwaltung'))
def add_song(self, **kwargs): artist_name = kwargs.get('title')[0] artist = Artist.objects(name=artist_name) song_name = kwargs.get('title')[-1] if not artist or Song.objects(name=song_name): self.add_artist(**kwargs) if self.is_song_exist(song_name): Log(type_added='song', name_added=song_name).save() return False self.download(kwargs.get('download_url')) size = kwargs.get('duration_size') size = ' '.join((size[2], size[3])) song = Song(artist=artist.get(), name=song_name, duration=kwargs.get('duration_size')[0], download_url=kwargs.get('download_url'), size=size) with open(TEMP_FILE, 'rb') as binary_file: song.audio_file.put(binary_file) shutil.rmtree(TEMP) if song: song.save() Log(type_added='song', name_added=song_name, added=True).save() return True Log(type_added='song', name_added=song_name).save() return False
def register_new_user(first_name, last_name, email, username, password): person_builder = models.PersonBuilder() person_builder.set_variables(username, email, password, first_name, last_name) person_manager = models.PersonManager() person_manager.set_builder(person_builder) person = person_manager.get_person() email_exists = db.session.query(Person.id).filter_by(email=email).first() username_exists = db.session.query( Person.id).filter_by(username=username).first() if first_name == '' or last_name == '' or email == '' or username == '' or password == '': log = Log("All fields of the form must be filled in!") interceptor_manager.execute(log) raise Exception elif email_exists: log = Log( "This email already exists in the database. Please choose another!" ) interceptor_manager.execute(log) raise Exception elif username_exists: log = Log( "This username already exists in the database. Please choose another!" ) interceptor_manager.execute(log) raise Exception else: db.session.add(person) db.session.commit() log = Log("Registration completed successfully!") interceptor_manager.execute(log)
def put(self, d_id): parser = reqparse.RequestParser(bundle_errors=True) parser.add_argument('values', action='append', default=[]) args = parser.parse_args() if g.user.id != 1: abort(403, message='not admin') doc = Doc.query.get(d_id) if doc is None: abort(404, message="doc id:{} not exist".format(d_id)) for k_v in args['values']: k, v = k_v.split('=') changed = False for vals in doc.values: if vals.property_name == k: vals.value = v changed = True break if not changed: prop = DocProperty.query.filter_by( name=k, volumne_id=doc.volumne.id).first() if prop is None: continue new_value = DocValue(v, prop.id, doc.id, prop.name, prop.order) db.session.add(new_value) db.session.commit() log_info = u'{} 修改了档案件:{}, {}'.format(g.user.username, doc.volumne.name, doc.name, doc.id) Log.logging(g.user.id, datetime.datetime.now(), 'modify doc', log_info) return doc.to_json(), 200
def dataAnalyse(): r = requests.get("http://127.0.0.1:5000/movies/analysis/best_movie_year") movie = json.loads(r.text, object_hook=BestMovie.dict2movie) r = requests.get("http://127.0.0.1:5000/movies/analysis/country") country = json.loads(r.text, object_hook=CountryNum.dict2counNum) r = requests.get("http://127.0.0.1:5000/movies/analysis/general") genre = json.loads(r.text, object_hook=TypeNum.dict2typeNum) headers = {'Content-Type': 'application/json'} log = Log(request.remote_addr, time(), 'Get /movies/analysis/best_movie_year/') r = requests.post('http://127.0.0.1:5000/movies/logging', headers=headers, data=json.dumps(log, default=Log.log2json)) log = Log(request.remote_addr, time(), 'Get /movies/analysis/movies/analysis/country/') r = requests.post('http://127.0.0.1:5000/movies/logging', headers=headers, data=json.dumps(log, default=Log.log2json)) log = Log(request.remote_addr, time(), 'Get /movies/analysis/movies/analysis/general') r = requests.post('http://127.0.0.1:5000/movies/logging', headers=headers, data=json.dumps(log, default=Log.log2json)) return render_template('home/analyse.html', movies=movie, countries=country, genres=genre, genreNum=len(genre))
def register(): if request.method == 'POST': name = request.form['name'] email = request.form['email'] password1 = request.form['password1'] password2 = request.form['password2'] user = db.session.query(User).filter_by(email=email).first() if user: flash(" 此邮箱已被注册") return render_template('register.html') if password1 != password2: flash("两次输入密码不一致") return render_template('register.html') user = User() user.name = name user.email = email user.password = password1 user.role_id = 2 db.session.add(user) db.session.commit() log = Log() log.user = name log.operate = '帐号注册' db.session.add(log) db.session.commit() return redirect(url_for('auth.login')) return render_template('register.html')
def logout(): log = Log() log.user = current_user.name log.operate = '帐号登出' db.session.add(log) db.session.commit() logout_user() return redirect(url_for('auth.login'))
def decorated_function(*args, **kwargs): user = args[0] if app.config.get('PRESENTATION_MODE') and \ user.card_id == app.config.get('PRESENTATION_ID'): prize = Prize.get_random() Log.add(user_id=user.id, win=True, prize_id=prize.id) user.set_last_spin() abort(msg(True, prize=prize.name, prize_id=prize.id)) return f(*args, **kwargs)
def exam_submit(): current_user = tokenAuth.current_user() logs = request.get_json()['log_json'] log = Log.query.filter_by(token=current_user.token).first() if log is None: log = Log(token=current_user.token) db.session.add(log) log.proctoring_logs = logs current_user.submitted = True db.session.commit() return make_response({'msg':'done', "id":current_user.id}, 200)
def delete(self, a_id): apply = ApplyFor.query.get(a_id) if apply is None or (apply.user_id != g.user.id and g.user.id != 1): abort(403, message='no apply or you have no permission to del this applyfor') db.session.delete(apply) db.session.commit() log_info = u'{} 删除了申请借阅档案卷:{}, {}'.format(g.user.username, apply.volumne.name, apply.volumne.id) Log.logging(g.user.id, datetime.datetime.now(), 'borrow authority', log_info) return '', 204
def application(current_user, application_id): application_id = int(application_id) application = Application.find_by(user_id=current_user._id, _id=application_id) if application is None: return Response("{'errors: ['Record not found']'}", status=404) if request.method == 'GET': return ApplicationSerializer(application, extra_fields=['secret']).serialize() else: application.remove() Log.remove(application_id=application._id) return Response("{'status': 'deleted'}")
def engpass(): form = EngpassForm() if request.method == 'POST': # Erststellung eines Engpass Document Engpass(producer=Producer.get_by_employee(current_user.email), drug=Drug.get_by_enr(int(request.form['enr'])), alternative=request.form['alternative'], inform_expert_group=request.form['inform_expert_group'], telephone=request.form['telephone'], email=request.form['email'] if request.form['email'] is None else current_user.email, end=datetime(int(request.form['year']), int(request.form['month']), int(request.form['day'])), reason=request.form['reason'], other_reasons=request.form['other_reasons']).save() # save in log user = User.objects.get(email=current_user.email) Log(user=user, category='engpass', text='Hat einen Erstmeldung für einen Engpass gemeldet.').save() flash('Engpass wurde gemeldet.') return redirect(url_for('main.index')) return render_template('hersteller/engpass_form.html', form=form)
def delete(self, d_id): if g.user.id != 1: abort(403, message='not admin') doc = Doc.query.get(d_id) if doc is None: abort(404, message="doc id:{} not exist".format(d_id)) shutil.rmtree(doc.path) db.session.delete(doc) db.session.commit() log_info = u'{} 删除了档案件:{}, {}'.format(g.user.username, doc.volumne.name, doc.name, doc.id) Log.logging(g.user.id, datetime.datetime.now(), 'delete doc', log_info) return '', 204
def gameover(log_id): # event.py收到gameserver的 'score'訊息後, redirect到此遊戲結束的 route, update log, 顯示分數 # get record_content from gameserver or local var ? # record display in many jpeg 為學習影像處理存擋, 也用來做回顧播放 log = Log.query.with_entities(Log.game_id).filter_by(id=log_id).first() print(Log.get_rank_list(Log, str(log[0]))) # log[1]=game_id return render_template('games/index.html', title='Register')
def create_log(self): log = Log(user_id=self.user_id, action_type_id=self.action_type_id) db.session.add(log) if (self.action_type_id > 3): db.session.flush() db.session.refresh(log) if self.movie_id is None: return detail1 = LogDetail(log_id=log.id, action_parameter_id=1, value=self.movie_id) db.session.add(detail1) if self.action_type_id == 5: if self.rating is None: return detail2 = LogDetail(log_id=log.id, action_parameter_id=2, value=self.rating) db.session.add(detail2) if self.action_type_id == 7: if self.headline is None or self.body is None: return detail2 = LogDetail( log_id=log.id, action_parameter_id=3, value=self.headline) db.session.add(detail2) detail3 = LogDetail( log_id=log.id, action_parameter_id=4, value=self.body) db.session.add(detail3) db.session.commit()
def start_new_online_check(): form = NewOnlineCheckForm() if form.validate_on_submit(): form = request.form.to_dict() if current_user.is_authenticated: supervisor_id = current_user.id else: supervisor_id = None oc = Onlinecheck(device_name=form['device_name'], device_issue=form['device_issue'], customer_name=form['customer_name'], customer_email=form['customer_email'], customer_tel=form['customer_tel'], supervisor_id=supervisor_id) db.session.add(oc) db.session.commit() log = Log(caption='Neu', online_check_id=oc.id, user_id=supervisor_id, type='action', state='new') db.session.add(log) db.session.commit() text = 'Ein neuer Onlinecheck wurde erstellt: *' + oc.device_name + '* \n https://q01.reparaturcafe.online/onlinecheck/' + str( oc.id) send_message(str(Config.TELEGRAM_CHAT_ID), text=text, parse_mode='Markdown') flash('Neuer Online Check wurde erstellt.', 'success') return redirect(url_for('main.index')) return render_template('online_check/new_online_check_form.html', title='Online Check erstellen', form=form)
def pin(): id = request.args.get('id', '') if not id: return redirect(url_for('login')) id = jwt_decode(id) if request.method == 'POST': password = request.form.get('PINbox', '') if hashlib.md5(password.encode()).hexdigest() == \ db.session.query(Card.password).filter(Card.number == id['card']).one_or_none()[0]: data = dict( card=id['card'], timestamp=datetime.now().timestamp() ) data = jwt_encode(data) return redirect(url_for('operations', id=data)) else: id['attempt'] += 1 if id['attempt'] >= 3: db.session.query(Card).filter(Card.number == id['card'])\ .update({Card.lock: True}) db.session.add( Log( card_id=db.session.query(Card.id).filter(Card.number == id['card']).one_or_none()[0], date=datetime.now(), details='Card was blocked.' ) ) db.session.commit() message = 'Too many attempts, card blocked!' return redirect(url_for('error', message=message)) else: id = jwt_encode(id) return redirect(url_for('pin', id=id)) return render_template('pin.html')
def winner_update(log_id): form = WinnerForm() if form.validate_on_submit(): winner = Log.get(log_id) winner.hand_over(True if form.handed_over.data == "1" else False) return redirect(url_for('app.index'))
def handle_mqtt_message(client, userdata, message): app.logger.info(message.topic + ' ' + message.payload.decode()) match = hydro_json_re.match(message.topic) if match: name = match.group(1) data = json.loads(message.payload.decode()) dev = Device.query.filter_by(name=name).first() if not dev: dev = Device(name=name) db.session.add(dev) db.session.commit() log = Log( device=dev.id, session=dev.cur_session, bat_v=data['bat_v'], temp_f=data['temp_f'], light_vis=data['light_vis'], light_ir=data['light_ir'], light_uv=data['light_uv'], accel_x=data['accel_x'], accel_y=data['accel_y'], accel_z=data['accel_z'], tilt=data['tilt'], wifi_conn_fail=data['wifi_conn_fail'], mqtt_conn_fail=data['mqtt_conn_fail'], last_run_time=data['last_run_time'] ) db.session.add(log) db.session.commit()
def test(): f = Faction(name='celery test') db.session.add(f) log = Log(message='Running test') db.session.add(log) db.session.commit() print('Print** a test task running') return 'Running a celery task'
def get_user(user, card_id): return msg(True, name=user.name, nickname=user.nickname, maconomy_id=user.maconomy_id, avatar=user.avatar, already_played=Log.already_played(user.id), last_spin=user.last_spin_date)
def logs(current_user, application_id): application_id = int(application_id) application = Application.find_by(user_id=current_user._id, _id=application_id) if application is None: return Response("{'errors: ['Record not found']'}", status=404) if request.method == 'GET': logs = Log.where(application_id=application_id) return LogSerializer(logs).serialize() else: params = request.get_json() log = Log.create(_id=Log.count() + 1, application_id=application_id, request=params['request'], ip_address=params['ip_address'], created_at=datetime.datetime.now()) return LogSerializer(log).serialize()
def api_post(url_path): """Check key""" if 'Authorization' not in request.headers: return abort(403) authorization = request.headers['authorization'] key = Key.query.filter(Key.key == authorization).first() if not key or not key.active: return abort(403) log = Log() log.date_time = datetime.now() log.key_id = key.id log.request_type = 'POST' log.request_url = url_path db.session.add(log) db.session.commit() data = request.get_json() if not data: data = {} alt = request.args.get('alt') if alt and alt.lower() == 'true': result = alt_rrclient.post(url_path, data=data) else: result = rrclient.post(url_path, data=data) log.succes = True db.session.commit() return result
def api_send_conference_message(conference_id): """Check key""" if 'Authorization' not in request.headers: return abort(403) authorization = request.headers['authorization'] key = Key.query.filter(Key.key == authorization).first() if not key or not key.active: return abort(403) if 'message' not in request.form: return abort(400) message = request.form['message'] log = Log() log.date_time = datetime.now() log.key_id = key.id log.request_type = 'CM' log.request_url = conference_id db.session.add(log) db.session.commit() alt = request.args.get('alt') if alt and alt.lower() == 'true': alt_rrclient.send_conference_message(conference_id, message) else: rrclient.send_conference_message(conference_id, message) log.succes = True db.session.commit() return json.dumps(True)
def write_logs(video1, timecode1, video2, timecode2): """Function to write results of search""" log = Log(video1_id=video1, time_code1=timecode1, video2_id=video2, time_code2=timecode2) db.session.add(log) db.session.commit()
def add_log(request): pid = request.POST['pid'] tid = request.POST['tid'] module = request.POST['module'] action = request.POST['action'] message = request.POST['message'] params = request.POST['params'] video = request.POST['video'] log = Log(pid=pid, tid=tid, module=module, action=action, message=message, params=params, video=video) log.save() results = {'success': True} return HttpResponse(simplejson.dumps(results), mimetype='application/json')
def save_log(filename, submission_id, user_id): """Inserts a new log in the database.""" log = Log(name=filename, sub_date=datetime.now().strftime("%d/%m/%Y %H:%M:%S"), submission_id=submission_id, user_id=user_id) db.session.add(log) db.session.commit()
def save_comment_to_database(post_id, content): username = session['username'] comment = Comment(post_id=post_id, username=username, content=content) comment_exists = db.session.query(Comment.id).filter_by(content=content).first() if username == '' or content == '' or post_id == '': log = Log("All fields of the form must be filled in!") interceptor_manager.execute(log) raise Exception elif comment_exists: log = Log("This comment already exists, choose another!") interceptor_manager.execute(log) raise Exception else: composite = add_content_composite.Composite() composite.add(comment) log = Log("Comment added.") interceptor_manager.execute(log)
def index(request): newLogg = Log(remote_addr=request.META["REMOTE_ADDR"], http_user_agent=request.META["HTTP_USER_AGENT"], name=request.META['LOGNAME']) newLogg.save() loggs = Log.objects.all().order_by("-date") return render_to_response('start.html', {'Loggs':loggs})