def get_single_preprocessor(instance_id=None, **kw): instance_user_id = Expense.query.get(instance_id) if instance_user_id.user_id and current_user.get_id(): if int(instance_user_id.user_id) != int(current_user.get_id()): raise flask.ext.restless.ProcessingException(description='Not Authorized', code=401) else: raise flask.ext.restless.ProcessingException(description='Not Authorized', code=401)
def unfollow(type, id): """ Removes current user as follower Returns JSON """ if type == 'collection': model = Collection.objects.get_or_404(id=id) elif type == 'queue': model = Queue.objects.get_or_404(id=id) elif type == 'maker': model = Maker.objects.get_or_404(id=id) elif type == 'thread': model = Thread.objects.get_or_404(id=id) elif type == 'thing': model = Thing.objects.get_or_404(id=id) else: abort(404) user = User.objects(id=current_user.get_id()).first() model.remove_follower(user) if type == 'collection': cached = Cache.objects(name="collections-for-%s" % current_user.get_id()).first() if cached: cached.delete() return jsonify({ 'result': 'success', 'message': unicode( get_template_attribute('frontend/macros.html', 'follow')(model)) })
def build_flat_hierarchy(self): """ The query set is only top level collections - the "hierarchy" is basically a query set including subcollections """ # first try the cache cached = Cache.objects(name="collections-for-%s" % current_user.get_id()).first() if cached: self.hierarchy = cached.value return True # not in cache, so we have to build it, which is expensive self.hierarchy = {} def recurse(objs, depth, group): for obj in objs: # if not obj.has_thing(self.thing): label = self.label_attr and getattr(obj, self.label_attr) or obj self.hierarchy[group].append((obj, depth)) if obj.subcollections: recurse(obj.subcollections, depth + 1, group) for group in self.queryset: self.hierarchy[group] = [] self.queryset[group].rewind() recurse(self.queryset[group], 0, group) cached = Cache(name="collections-for-%s" % current_user.get_id(), value=self.hierarchy) cached.save()
def unfollow(type, id): """ Removes current user as follower Returns JSON """ if type == 'collection': model = Collection.objects.get_or_404(id=id) elif type == 'queue': model = Queue.objects.get_or_404(id=id) elif type == 'maker': model = Maker.objects.get_or_404(id=id) elif type == 'thread': model = Thread.objects.get_or_404(id=id) elif type == 'thing': model = Thing.objects.get_or_404(id=id) else: abort(404) user = User.objects(id=current_user.get_id()).first() model.remove_follower(user) if type == 'collection': cached = Cache.objects(name="collections-for-%s" % current_user.get_id()).first() if cached: cached.delete() return jsonify({ 'result': 'success', 'message': unicode(get_template_attribute('frontend/macros.html', 'follow')(model)) })
def __init__(self, *args, **kwargs): super(CollectionQuerySetSelectField, self).__init__(*args, **kwargs) self.queryset = {} self.queryset["following"] = Collection.objects.filter( supercollection__exists=False, followers=current_user.get_id() ).order_by("title") self.queryset["contributing"] = Collection.objects.filter( supercollection__exists=False, editors=current_user.get_id() ).order_by("title") self.queryset["created"] = Collection.objects.filter( supercollection__exists=False, creator=current_user.get_id() ).order_by("title")
def create(): m = request.args.get('mode', None) v = request.args.get('value', None) if not m and not v: user_id = current_user.get_id() annotations = Reference.objects.filter( creator=user_id).order_by('-created_at') # if there are no annotations this way, then just fetch recent ones if not annotations: annotations = Reference.objects( pos_end__gt=0).order_by('-created_at').limit(20) elif m == 'tag' and v is not None: annotations = Reference.objects.filter(tags=v).order_by('-created_at') elif m == 'from' and v is not None: u = Upload.objects.filter(md5=v).first() if not u: abort(404) annotations = Reference.objects.filter(upload=u).order_by('pos') else: annotations = Reference.objects( pos_end__gt=0).order_by('-created_at').limit(20) clips = build_clips(annotations) return render_template('compiler/create.html', title="compiler", clips=clips )
def user_clips(user_id=None): if user_id is None: user_id = current_user.get_id() annotations = Reference.objects.filter( creator=user_id).order_by('-created_at') clips = [] for a in annotations: if a.pos_end: u = a.upload link = url_for("reference.figleaf", md5=a.upload.md5, _anchor='%s-%s' % (a.pos, a.pos_end)) y1, y2 = (a.pos, a.pos_end) if a.pos_end - \ a.pos < 1 else (int(a.pos), int(a.pos)) if a.pos_end - a.pos > 1: a.note = '%s (%s pages)' % ( a.note, int(a.pos_end) - int(a.pos) + 1) img = url_for("reference.preview", filename=u.preview( filename='%s-%sx%s.jpg' % (y1, y2, 500))) clips.append((link, img, a.note, a.tags)) return render_template('reference/clips.html', title="clips", thing=thing, compiler=url_for('compiler.create'), clips=clips )
def connect_handler(cv, provider): """Shared method to handle the connection process :param connection_values: A dictionary containing the connection values :param provider_id: The provider ID the connection shoudl be made to """ cv.setdefault('user_id', current_user.get_id()) connection = _datastore.find_connection(**cv) if connection is None: after_this_request(_commit) connection = _datastore.create_connection(**cv) msg = ('Connection established to %s' % provider.name, 'success') connection_created.send(current_app._get_current_object(), user=current_user._get_current_object(), connection=connection) else: msg = ('A connection is already established with %s ' 'to your account' % provider.name, 'notice') connection_failed.send(current_app._get_current_object(), user=current_user._get_current_object()) redirect_url = session.pop(config_value('POST_OAUTH_CONNECT_SESSION_KEY'), get_url(config_value('CONNECT_ALLOW_VIEW'))) do_flash(*msg) return redirect(redirect_url)
def reset_password(self): parser = self.get_parser() parser.add_argument('password', type=StringParam.check, required=True, location='json', min=6, max=20) if not current_user.get_id(): parser.add_argument('token', type=str, required=True, location='json', min=6, max=20) token, pwd = self.get_params('token', 'password') user = User.get(verify_token=token) if not user: self.bad_request(errorcode.BAD_REQUEST) user.password = hashlib.md5(pwd).hexdigest().upper() user.verify_token = '' else: user = current_user pwd = self.get_param('password') user.password = hashlib.md5(pwd).hexdigest().upper() user.save() return self.ok('ok')
def collections(letter=None): """ See a list of collections the user has created or is following """ following = Collection.objects.filter( supercollection__exists=False, followers=current_user.get_id()).order_by('title') contributing = Collection.objects.filter( supercollection__exists=False, editors=current_user.get_id()).order_by('title') created = Collection.objects.filter( supercollection__exists=False, creator=current_user.get_id()).order_by('title') return render_template('collection/user_list.html', title='Collections', following=following, contributing=contributing, created=created)
def profile(page=1): """ A person's own profile """ things = Thing.objects.filter(creator=current_user.get_id()).order_by( '-created_at').paginate(page=page, per_page=10) collections = Collection.objects.filter( creator=current_user.get_id(), supercollection__exists=False) return render_template('profiles/profile.html', title='Uploads', things=things.items, pagination=things, collections=collections, endpoint='user.profile', params={}, public=False)
def index(): recent_collections = Collection.objects( accessibility__ne='private').limit(3).order_by('-things.created_at') recent_comments = Thread.objects(origin__exists=False).exclude( 'comments').order_by('-priority', '-last_comment').limit(3) recent_things = Thing.objects(files__0__exists=True).order_by( '-modified_at', '-created_at').paginate(page=1, per_page=10) rt = render_template('frontend/home.html', title=app.config['SITE_NAME'], things=recent_things.items, collections=recent_collections, comments=recent_comments, pagination=recent_things, endpoint='thing.list_nonrequests') resp = make_response(rt) if current_user.get_id(): resp.set_cookie('id', current_user.get_id()) return resp
def index(): recent_collections = Collection.objects( accessibility__ne='private').limit(3).order_by('-things.created_at') recent_comments = Thread.objects( origin__exists=False).exclude('comments').order_by( '-priority', '-last_comment').limit(3) recent_things = Thing.objects(files__0__exists=True).order_by( '-modified_at', '-created_at').paginate(page=1, per_page=10) rt = render_template('frontend/home.html', title=app.config['SITE_NAME'], things=recent_things.items, collections=recent_collections, comments=recent_comments, pagination=recent_things, endpoint='thing.list_nonrequests') resp = make_response(rt) if current_user.get_id(): resp.set_cookie('id', current_user.get_id()) return resp
def circles(): #variables = {'name': 'name', 'age': 'age', 'sex': 'sex', 'studying': 'study', 'working': 'work'} name = current_user.name age = str(current_user.age) sex = current_user.sex work = current_user.work study = current_user.study tedx_id = str(current_user.get_id()) params = 'name=' + name + '&age=' + age + '&sex=' + sex + '&work=' + work + '&study=' + study + '&tedx_user_id=' + tedx_id return redirect('http://circles-experiment.meteor.com?' + params, 303)
def list_mine(page=1): """ See a list of comment threads """ threads = Thread.objects(comments__creator=current_user.get_id()).paginate( page=page, per_page=10) return render_template('talk/list.html', title='Discussions with you', threads=threads.items, pagination=threads, endpoint='talk.list_mine')
def count_pages(self): user_id = current_user.get_id() bibtex_dir = app.config['UPLOAD_FOLDER'] + '/' + str(user_id) + '/bibtex' num_by_page = app.config['NUM_BY_PAGE'] pages = 0 for f in os.listdir(bibtex_dir)[::-1]: if not os.path.isfile(bibtex_dir + '/' + f): continue pages += 1 return math.ceil(float(pages) / num_by_page)
def edit_profile(): """ Edit one's own profile """ user = User.objects.get_or_404(id=current_user.get_id()) form = UserForm(formdata=request.form, obj=user) if form.validate_on_submit(): user.email = form.email.data user.username = form.username.data user.save() flash("Your profile has been updated!") return render_template('profiles/edit.html', title='Edit your account', form=form)
def sort_actions(id): hide = request.args.get('hide', '') model = Thing.objects.get_or_404(id=id) if not hide == 'collections': form = AddThingToCollectionsForm() form.set_thing(model) else: form = None queues = Queue.objects.filter(creator=current_user.get_id()) return render_template( 'thing/sort_actions.html', form=form, queues=queues, thing=model )
def get(self, user_id, file): user = current_user if user_id != current_user.get_id(): user = user_datastore.find_user(id=user_id) if not user: self.bad_request(errorcode.NOT_FOUND) path = os.path.join(current_app.config['FILE_STORE_BASE'], user.photo_path) try: f = open(path, 'rb') data = f.read() f.close() return Response(data, mimetype='image/png') except: self.bad_request(errorcode.NOT_FOUND)
def cronotipos_results(): form = CronotiposForm(csrf_enabled=False) if form.validate(): crono = Cronotipos() crono.user_id = current_user.get_id() crono.pregunta_1 = form.pregunta_1.data['hours_field'] + u':' + form.pregunta_1.data['minutes_field'] #crono.pregunta_2 = form.pregunta_2.data['hours_field'] + u':' + form.pregunta_2.data['minutes_field'] crono.pregunta_2 = form.pregunta_2.data crono.pregunta_3 = form.pregunta_3.data['hours_field'] + u':' + form.pregunta_3.data['minutes_field'] crono.pregunta_4 = form.pregunta_4.data crono.pregunta_5 = form.pregunta_5.data['hours_field'] + u':' + form.pregunta_5.data['minutes_field'] # crono.pregunta_6 = form.pregunta_6.data['hours_field'] + u':' + form.pregunta_6.data['minutes_field'] crono.pregunta_6 = form.pregunta_6.data crono.pregunta_7 = form.pregunta_7.data['hours_field'] + u':' + form.pregunta_7.data['minutes_field'] crono.pregunta_8 = form.pregunta_8.data crono.pregunta_9 = form.pregunta_9.data['hours_field'] + u':' + form.pregunta_9.data['minutes_field'] crono.pregunta_10 = form.pregunta_10.data['hours_field'] + u':' + form.pregunta_10.data['minutes_field'] crono.pregunta_11 = form.pregunta_11.data crono.pregunta_12 = form.pregunta_12.data crono.pregunta_13 = form.pregunta_13.data crono.pregunta_14 = form.pregunta_14.data crono.pregunta_15 = form.pregunta_15.data crono.pregunta_16 = form.pregunta_16.data crono.pregunta_17 = form.pregunta_17.data crono.pregunta_18 = form.pregunta_18.data['hours_field'] + u':' + form.pregunta_18.data['minutes_field'] crono.pregunta_19 = form.pregunta_19.data crono.pregunta_20 = form.pregunta_20.data crono.pregunta_21 = form.pregunta_21.data crono.pregunta_22 = form.pregunta_22.data crono.pregunta_23 = form.pregunta_23.data crono.pregunta_24 = form.pregunta_24.data crono.pregunta_25 = form.pregunta_25.data['hours_field'] + u':' + form.pregunta_25.data['minutes_field'] crono.pregunta_26 = form.pregunta_26.data['hours_field'] + u':' + form.pregunta_26.data['minutes_field'] crono.pregunta_27 = form.pregunta_27.data crono.result = crono.process_data() crono.result_type = crono.get_crono_type(crono.process_data()) crono.date = datetime.now() db.session.add(crono) db.session.commit() crono_dict = dict(get_crono_chart()) crono_dict = defaultdict(lambda: 0, crono_dict) return render_template('cronotipos_results.html', crono_result=crono.get_crono_type_human(crono.process_data()), crono_chart=crono_dict) flash(u'Por favor completa todos los campos') return render_template('cronotipos.html', form=form)
def change_password(): error = None old_password = request.form['oldPassword'] new_password = flask_bcrypt.generate_password_hash(request.form['newPassword'], rounds=12) #Retrieve logged-in doctor document, to populate his profile page doctor_doc = Users.objects.get(id=current_user.get_id()) if not flask_bcrypt.check_password_hash(doctor_doc["password"], old_password): error = 'Fjalekalimi gabim! Kerkesa juaj per ndryshim te fjalekalimit nuk u ekzekutua.' return render_template('doc_profile/doc_profile.html', message=error,type="error", doctor_doc=doctor_doc) elif request.form['newPassword'] != request.form['passwordConfirm']: error = 'Fjalekalimet nuk jane te njejta! Kerkesa juaj per ndryshim te fjalekalimit nuk u ekzekutua.' return render_template('doc_profile/doc_profile.html', message=error, type="error", doctor_doc=doctor_doc) else: doctor_doc.update(password=new_password) success = "Ndryshimi fjalekalimit u krye me sukses!" return render_template('doc_profile/doc_profile.html', message=success, type="success", doctor_doc=doctor_doc)
def add_record(): form = TasksAddForm(request.form) if request.method == 'POST': if form.validate(): new_expense = SampleTasksTable() title = form.title.data description = form.description.data logging.info("adding " + title) new_expense.add_data(current_user.get_id(), title, description) flash("Expense added successfully", category="success") return render_template("add_record.html", form=form)
def create_or_login(resp): session['openid'] = resp.identity_url current_app.logger.debug("User: %s", current_user) try: user = current_app.security.auth_provider.authenticate_openid(session['openid']) if user and _do_login(user): flash(u'Successfully signed in') return redirect(get_post_login_redirect()) except BadCredentialsError, UserNotFoundError: if current_user.get_id() is not None: # Looks like the openid token changed... not sure how, so we'll wipe it and start over current_user['openid'] = None security.datastore._save_model(current_user) return redirect(url_for('login'))
def add_record(): form = ExpensesInfoForm(request.form) if request.method == 'POST': if form.validate(): new_expense = Expense() title = form.title.data description = form.description.data color_code = form.color_code.data logging.info("adding " + title + " " + color_code) new_expense.add_data(current_user.get_id(), title, description, color_code) flash("expense added successfully", category="success") return render_template("add_record.html", form=form)
def get_connection_values(self, response): if not response: return None access_token = response["access_token"] graph = facebook.GraphAPI(access_token) profile = graph.get_object("me") profile_url = "http://facebook.com/profile.php?id=%s" % profile["id"] image_url = "http://graph.facebook.com/%s/picture" % profile["id"] return dict( user_id=current_user.get_id(), provider_id=self.provider_id, provider_user_id=profile["id"], access_token=access_token, secret=None, display_name=profile["username"], profile_url=profile_url, image_url=image_url, )
def remove_all_connections(provider_id): """Remove all connections for the authenticated user to the specified provider """ provider = get_provider_or_404(provider_id) ctx = dict(provider=provider.name, user=current_user) deleted = _datastore.delete_connections(user_id=current_user.get_id(), provider_id=provider_id) if deleted: after_this_request(_commit) msg = ('All connections to %s removed' % provider.name, 'info') connection_removed.send(current_app._get_current_object(), user=current_user._get_current_object(), provider_id=provider_id) else: msg = ('Unable to remove connection to %(provider)s' % ctx, 'error') do_flash(*msg) return redirect(request.referrer)
def remove_all_connections(provider_id): """Remove all connections for the authenticated user to the specified provider """ display_name = get_display_name(provider_id) ctx = dict(provider=display_name, user=current_user) try: method = connection_datastore.remove_all_connections method(current_user.get_id(), provider_id) current_app.logger.debug("Removed all connections to " "%(provider)s for %(user)s" % ctx) do_flash("All connections to %s removed" % display_name, "info") except: current_app.logger.error("Unable to remove all connections to " "%(provider)s for %(user)s" % ctx) msg = "Unable to remove connection to %(provider)s" % ctx do_flash(msg, "error") return redirect(request.referrer)
def get_photo(self): parser = self.get_parser() parser.add_argument('user_id', type=int, required=True, location='args') user_id = self.get_param('user_id') user = current_user if user_id != current_user.get_id(): user = user_datastore.find_user(id=user_id) if not user: self.bad_request(errorcode.NOT_FOUND) path = os.path.join(current_app.config['FILE_STORE_BASE'], user.photo_path) try: f = open(path, 'rb') data = f.read() f.close() return Response(data, mimetype='image/png') except: self.bad_request(errorcode.NOT_FOUND)
def patients(self): # First, let's find doctor id doctor_id = utils.encrypt_id(str(current_user.get_id())) #Now let's retrieve our list of patients based on docotor id. patient_doc = mongo.db.patients.find({'doctor_id': doctor_id , 'delete': "false"}).sort([("_id", -1)]) patient_docs = build_cursor('true' ,patient_doc) form = ModalDiagnosis() patientsArray = [] for patient in patient_docs['results']: line = [ patient['emri'], patient['mbiemri'], patient['personal_number'], patient['gjinia'], patient['komuna'], Markup("<a class='glyphicon glyphicon-search' href='"+url_for('patient_directory.view_patient', doc_id=patient['_id'])+"'/>"+\ "<a class='glyphicon glyphicon-edit' href='"+url_for('patient_directory.edit_patient', doc_id=patient['_id'])+"'/>"+\ "<a class='glyphicon glyphicon-plus plusbtn' href='' id='"+patient['_id']+"' href='#' name='"+patient['emri']+"' surname='"+patient['mbiemri']+"' data-toggle='modal' data-target='#add_diagnosis_dialog' data-backdrop='false' />"+ \ "<a class='glyphicon glyphicon-remove removebtn' id='"+patient['_id']+"' href='#' name='"+patient['emri']+"' surname='"+patient['mbiemri']+"' data-toggle='modal' data-target='#delete_dialog' data-backdrop='false' />") ] patientsArray.append(line) # Render the templates. return render_template('patient_directory/patient_page.html', patients=json.dumps(patientsArray),form=form )
def get_connection_values(self, response=None): if not response: return None api = twitter.Api( consumer_key=self.consumer_key, consumer_secret=self.consumer_secret, access_token_key=response["oauth_token"], access_token_secret=response["oauth_token_secret"], ) user = api.VerifyCredentials() return dict( user_id=current_user.get_id(), provider_id=self.provider_id, provider_user_id=str(user.id), access_token=response["oauth_token"], secret=response["oauth_token_secret"], display_name="@%s" % user.screen_name, profile_url="http://twitter.com/%s" % user.screen_name, image_url=user.profile_image_url, )
def remove_connection(provider_id, provider_user_id): """Remove a specific connection for the authenticated user to the specified provider """ display_name = get_display_name(provider_id) ctx = dict(provider=display_name, user=current_user, provider_user_id=provider_user_id) try: connection_datastore.remove_connection(current_user.get_id(), provider_id, provider_user_id) current_app.logger.debug( "Removed connection to %(provider)s " "account %(provider_user_id)s for %(user)s" % ctx ) do_flash("Connection to %(provider)s removed" % ctx, "info") except ConnectionNotFoundError: current_app.logger.error( "Unable to remove connection to %(provider)s account " "%(provider_user_id)s for %(user)s" % ctx ) do_flash("Unabled to remove connection to %(provider)s" % ctx, "error") return redirect(request.referrer)
def invite(): """ Invite a new person """ form = InviteForm(request.form) if form.validate_on_submit(): from flask_application import user_datastore, app, mail user = User.objects(id=current_user.get_id()).first() password = binascii.b2a_hex(os.urandom(15)) # create an account user_datastore.create_user(username="******", email=form.email.data, password=encrypt_password(password), roles=['contributor'], active=True, invited_by=user) user_datastore.commit() invitee = User.objects(email=form.email.data).first() # set inviter data user.add_invitation(invitee) # send an email msg = Message("An invitation to %s" % app.config['SITE_NAME'], sender=app.config['DEFAULT_MAIL_SENDER'], recipients=[form.email.data]) msg.body = ''' You have been invited to %s by %s. Your can log in with the following username/ password: %s %s You can change this random, complicated password after you have logged in. ''' % (app.config['SITE_NAME'], user.email, form.email.data, password) mail.send(msg) # @todo: set invited and invited by flash("An account has been created for %s and an email has been sent. You may want to let them know that it is coming." % form.email.data) return render_template('profiles/invite.html', register_user_form=form)
def figleaf(md5, user_id=None): """ The filename here is the structured filename """ u = Upload.objects.filter(md5=md5).first() if not u: abort(404) thing = Thing.objects.filter(files=u).first() if thing.takedown: return thing.takedown preview = u.preview() preview_url = url_for('reference.preview', filename=preview) if preview else False #preview_url = preview_url.replace('/pages', 'http://127.0.0.1:8484') if not preview_url: abort(404) # load annotations #annotations = Reference.objects.filter(upload=u, ref_url__exists=True) annotations = Reference.objects.filter(upload=u).order_by('ref_pos') # create a list of referenced things references = {} # the annotations/ reference that the user can edit editable = [] for a in annotations: if can_edit_reference(a): editable.append(a) if a.ref_thing and a.ref_pos and a.ref_url: if not a.ref_thing in references: references[a.ref_thing] = { 'md5': a.ref_upload.md5, 'pages': []} references[a.ref_thing]['pages'].append((a.ref_pos, a.id)) # for back references back_annotations = Reference.objects.filter(ref_upload=u).order_by('pos') back_references = {} for a in back_annotations: if a.thing and a.pos: if not a.thing in back_references: back_references[a.thing] = {'md5': a.upload.md5, 'pages': []} back_references[a.thing]['pages'].append((a.pos, a.id)) # if we pass a user id then we try and load highlights & notes created by # the user if user_id: notes = Reference.objects.filter(upload=u, creator=user_id) else: notes = Reference.objects.filter( upload=u, creator=current_user.get_id()) # if there is a query specified, do it is_searchable = False search_results = {} query = request.args.get('query', '') if not query == '': subqueries = query.split(',') q_idx = 0 for q in subqueries: if q_idx == 3: continue new_query = "'%s'" % q.strip() results = elastic.search('page', query={'searchable_text': q}, filter={'md5': md5}, fields=['page'], num=100) max_score = 0 min_score = 100 search_results[q_idx] = {} for id, score, fields in results: is_searchable = True search_results[q_idx][fields['page'][0] - 1] = score max_score = score if score > max_score else max_score min_score = score if score < min_score else min_score min_score = min_score - 0.1 search_results[q_idx].update( (x, (y - min_score) / (max_score - min_score)) for x, y in search_results[q_idx].items()) q_idx += 1 # check if this is searchable if not is_searchable: count = elastic.count('page', filter={'md5': md5}) if count > 0: is_searchable = True return render_template('reference/figleaf.beta.html', preview=preview_url, upload=u, thing=thing, annotations=annotations, references=references, back_annotations=back_annotations, back_references=back_references, notes=notes, editable=editable, search_results=search_results, searchable=is_searchable )
def update_preferences(): if not current_user.is_authenticated: return jsonify(respo='user not authenticated') cur_id = current_user.get_id() cur_user = db_session.query(User).filter(User.id == cur_id).first() if cur_user is None: return jsonify(respo='user not found') cur_report_preferences = db_session.query(ReportPreferences).filter(User.id == cur_id).first() cur_general_preferences = db_session.query(GeneralPreferences).filter(User.id == cur_id).first() if request.method == "GET": if cur_report_preferences is None and cur_general_preferences is None: return jsonify(accident_severity='0', pref_accidents_lms=True, pref_accidents_ihud=True, produce_accidents_report=False) else: resource_types = cur_general_preferences.resource_type.split(',') if cur_report_preferences is None: return jsonify(accident_severity=cur_general_preferences.minimum_displayed_severity, pref_resource_types=resource_types, produce_accidents_report=False) else: return jsonify(accident_severity=cur_general_preferences.minimum_displayed_severity, pref_resource_types=resource_types, produce_accidents_report=True, \ lat=cur_report_preferences.latitude, lon=cur_report_preferences.longitude, pref_radius=cur_report_preferences.radius, \ pref_accident_severity_for_report=cur_report_preferences.minimum_severity, how_many_months_back=cur_report_preferences.how_many_months_back) else: json_data = request.get_json(force=True) accident_severity = json_data['accident_severity'] resources = json_data['pref_resource_types'] produce_accidents_report = json_data['produce_accidents_report'] lat = json_data['lat'] lon = json_data['lon'] pref_radius = json_data['pref_radius'] pref_accident_severity_for_report = json_data['pref_accident_severity_for_report'] history_report = json_data['history_report'] is_history_report = (history_report != '0') resource_types = ','.join(resources) cur_general_preferences = db_session.query(GeneralPreferences).filter(User.id == cur_id).first() if cur_general_preferences is None: general_pref = GeneralPreferences(user_id = cur_id, minimum_displayed_severity = accident_severity, resource_type = resource_types) db_session.add(general_pref) db_session.commit() else: cur_general_preferences.minimum_displayed_severity = accident_severity cur_general_preferences.resource_type = resource_types db_session.add(cur_general_preferences) db_session.commit() if produce_accidents_report: if lat == '': lat = None if lon == '': lon = None if cur_report_preferences is None: report_pref = ReportPreferences(user_id = cur_id, line_number=1, historical_report=is_history_report,\ how_many_months_back=history_report, latitude=lat,longitude=lon,\ radius=pref_radius, minimum_severity=pref_accident_severity_for_report) db_session.add(report_pref) db_session.commit() else: cur_report_preferences.historical_report = is_history_report cur_report_preferences.latitude = lat cur_report_preferences.longitude = lon cur_report_preferences.radius = pref_radius cur_report_preferences.minimum_severity = pref_accident_severity_for_report cur_report_preferences.how_many_months_back = history_report db_session.add(cur_report_preferences) db_session.commit() else: if cur_report_preferences is not None: db_session.delete(cur_report_preferences) db_session.commit() return jsonify(respo='ok', )
def get_current_user_first_name(): cur_id = current_user.get_id() cur_user = db_session.query(User).filter(User.id == cur_id).first() if cur_user is not None: return cur_user.first_name return "User"
def current_user_queues(): return Queue.objects.filter(creator=current_user.get_id())