def post(self, course_key): """Updates a specific Course""" b_course = ndb.Key(urlsafe=course_key).get() if b_course and util.param('name') and util.param('lessons'): b_name = util.param('name') b_description = util.param('description') b_topics = [ ndb.Key(urlsafe=topic_key_url) for topic_key_url in util.param('topics', list) ] b_lessons = helpers.connected_entities_constructor( util.param('lessons', list)) b_contributors = b_course.contributors #add new contributors to the list of course contributors. if auth.current_user_key() not in b_contributors: b_contributors += [auth.current_user_key()] b_course.name = b_name b_course.description = b_description b_course.topics = b_topics b_course.contributors = b_contributors b_course.lessons = b_lessons b_course = b_course.put() response = { 'status': 'success', 'count': 1, 'now': helpers.time_now(), 'result': { 'message': 'Course was successfuly created!!', 'view_url': flask.url_for('course', course_key=b_course.urlsafe()) }, } return response return helpers.make_bad_request_exception("Unsifificient parameters")
def post(self, course_key): """Updates a specific Course""" b_course = ndb.Key(urlsafe=course_key).get() if b_course and util.param('name') and util.param('lessons'): b_name = util.param('name') b_description = util.param('description') b_topics = [ ndb.Key(urlsafe=topic_key_url) for topic_key_url in util.param('topics', list)] b_lessons = helpers.connected_entities_constructor(util.param('lessons', list)) b_contributors = b_course.contributors #add new contributors to the list of course contributors. if auth.current_user_key() not in b_contributors: b_contributors += [auth.current_user_key()] b_course.name=b_name b_course.description=b_description b_course.topics=b_topics b_course.contributors=b_contributors b_course.lessons=b_lessons b_course = b_course.put() response = { 'status': 'success', 'count': 1, 'now': helpers.time_now(), 'result': {'message': 'Course was successfuly created!!', 'view_url': flask.url_for('course', course_key=b_course.urlsafe()) }, } return response return helpers.make_bad_request_exception("Unsifificient parameters")
def update_weekly(): results = model.weekly.query( model.weekly.user_key == auth.current_user_key()).fetch(1) today = datetime.date(datetime.now()) week_num = today.strftime("%U") year_num = today.strftime("%G") count = 0 for result in results: count += 1 if count < 1: user_db = auth.current_user_db() name = user_db.name weekly_db = model.weekly(user_key=auth.current_user_key(), player_name=name, week=week_num, year=year_num) else: weekly_db = result if (weekly_db.week != week_num) or (weekly_db.year != year_num): weekly_db.wins = 0 weekly_db.week = week_num weekly_db.year = year_num weekly_db.wins += 1 weekly_db.put() return "success"
def comment_update(comment_id=0): if comment_id: comment_db = model.Comment.get_by_id(comment_id) else: comment_db = model.Comment(user_key=auth.current_user_key()) if not comment_db or comment_db.user_key != auth.current_user_key(): flask.abort(404) form = CommentUpdateForm(obj=comment_db) user_dbs, user_cursor = model.User.get_dbs(limit=-1) post_dbs, post_cursor = model.Post.get_dbs(limit=-1) form.post_key.choices = [(c.key.urlsafe(), c.title) for c in post_dbs] if flask.request.method == 'GET' and not form.errors: form.post_key.data = comment_db.post_key.urlsafe() if comment_db.post_key else None if form.validate_on_submit(): form.post_key.data = ndb.Key(urlsafe=form.post_key.data) if form.post_key.data else None form.populate_obj(comment_db) comment_db.put() return flask.redirect(flask.url_for('comment_view', comment_id=comment_db.key.id())) return flask.render_template( 'comment/comment_update.html', title=comment_db.content if comment_id else 'New Comment', html_class='comment-update', form=form, comment_db=comment_db, )
def person_update(person_id=0): if person_id: person_db = model.Person.get_by_id(person_id) else: person_db = model.Person(user_key=auth.current_user_key()) if not person_db or person_db.user_key != auth.current_user_key(): flask.abort(404) form = PersonUpdateForm(obj=person_db) user_dbs, user_cursor = model.User.get_dbs(limit=-1) if flask.request.method == 'GET' and not form.errors: form.tags.data = config.TAG_SEPARATOR.join(form.tags.data) form.timestamp.data = datetime.utcnow() if form.validate_on_submit(): form.tags.data = util.parse_tags(form.tags.data) form.populate_obj(person_db) person_db.put() return flask.redirect(flask.url_for('person_view', person_id=person_db.key.id())) return flask.render_template( 'person/person_update.html', title=person_db.name if person_id else 'New Person', html_class='person-update', form=form, person_db=person_db, )
def album_create_carousel(): parsed_request = urlparse(flask.request.url) hostname = parsed_request.hostname if 'www.' in hostname: hostname = hostname.split('www.')[1] query = model.Album.query( ndb.AND( user_key==auth.current_user_key(), hostname==hostname, isCarousel==True ) ) album_db = query.fetch(1) if album_db: if album_db.user_key != auth.current_user_key(): return flask.abort(404) else: resource_dbs = album_db.get_resource_dbs() if not album_db: album_db = model.Album( user_key=auth.current_user_key(), hostname=hostname, isCarousel=True ) album_db.put() return flask.redirect(flask.url_for( 'album_update', album_id=album_db.key.id(), ))
def update_weekly(): results = model.weekly.query(model.weekly.user_key == auth.current_user_key()).fetch(1) today=datetime.date(datetime.now()) week_num = today.strftime("%U") year_num = today.strftime("%G") count = 0 for result in results: count += 1 if count < 1: user_db = auth.current_user_db() name = user_db.name weekly_db = model.weekly(user_key=auth.current_user_key(), player_name=name, week=week_num, year=year_num) else: weekly_db = result; if (weekly_db.week != week_num) or (weekly_db.year != year_num): weekly_db.wins = 0 weekly_db.week = week_num weekly_db.year = year_num weekly_db.wins += 1 weekly_db.put() return "success"
def create(cls,size,creator=None,start_nr=1): """ If creator is None the current user is used, creator set to an email adress this user is used or set to "random" in order to use different, random users""" print "===================================================" print "Create collections" print fake = Factory.create() # description length desc_min = 0 desc_max = 120 creator_random = False import auth if not creator: # DOES NOT work, WHY? print "Take current user key as creator" print auth.current_user_key() creator = auth.current_user_key() elif not creator == "random": print "User by email: {}".format(creator) user_db = model.User.get_by_email_or_username(creator) if not user_db: print "ERROR: No user found by this email" return False else: print user_db.key creator = user_db.key else: # random user creator_random = True user_keys = model.User.query().fetch(limit=5000, keys_only=True) for i in range(size): if creator_random: creator = random.choice(user_keys) sentence_length = int(desc_min+\ random.random()*(desc_max-desc_min)) if sentence_length <= 5: desc = "" else: desc = fake.text(max_nb_chars=sentence_length) name="{} {}".format(start_nr+i,fake.city()) if len(name) > 20: name = name[0:19] elif len(name) < 2: name = name+" Longer" model.Collection.create(name=name, creator=creator, description=desc, active=True, public=False, private=False, avatar_url='https://robohash.org/{key}?set=set1&bgset=bg2&size=150x150'.format(key=random.randint(1,10000)) ) print "Collection {} '{}' for user '{}'".format(i, name, creator) print "---------------------------------------------------" print "{} collections created".format(i + 1) print
def add_starred_to_posts(post_dbs): if auth.current_user_key(): user_db = auth.current_user_key().get() for post_db in post_dbs: stars = model.Star.query( model.Star.post_key == post_db.key, model.Star.user_key == user_db.key).fetch() if len(stars) > 0: post_db.starred = True return post_dbs
def post(self, vote_key): """Update a specific vote""" vote_db = ndb.Key(urlsafe=vote_key).get() upvote = 0 downvote = 0 if util.param('data', str) == 'upvote': upvote = 1 elif util.param('data', str) == 'downvote': downvote = 1 else: flask.abort(505) if auth.current_user_key() and (upvote or downvote): vote_db.vote(auth.current_user_key().urlsafe(), upvote, downvote) return "Success"
def post(self, lesson_key): if util.param('name') and util.param('is_a'): b_is_a = util.param('is_a') b_data = helpers.data_scheme_constructor(b_is_a, helpers.rerieve_content_fields(util)) b_topics = [ ndb.Key(urlsafe=topic_key_url) for topic_key_url in util.param('topics', list)] b_name = util.param('name') b_description = util.param('description') b_contributor = auth.current_user_key() b_lesson = ndb.Key(urlsafe=lesson_key).get() if not b_lesson: return helpers.make_not_found_exception('Lesson %s not found' % b_lesson) b_lesson_version = model.LessonVersion(data=b_data,name=b_name,is_a=b_is_a,description=b_description,topics=b_topics,lesson=b_lesson.key,contributor=b_contributor).put() b_lesson.contributors += [b_contributor] b_lesson.lesson_versions += [b_lesson_version] b_lesson.put() response = { 'status': 'success', 'count': 1, 'now': helpers.time_now(), 'result': {'message': 'Lesson Version update proposal was successfuly created!!', 'view_url': flask.url_for('lesson_version', version_key=b_lesson_version.urlsafe()) }, } return response return helpers.make_bad_request_exception("Unsifificient parameters")
def make_home_template(isEditMode): parsed_request = urlparse(flask.request.url) hostname = parsed_request.hostname if 'www.' in hostname: hostname = hostname.split('www.')[1] # get carousel resources query = model.Album.query( model.Album.hostname==hostname, model.Album.isCarousel==True ) carousel_album_db = query.get() if not carousel_album_db and isEditMode: carousel_album_db = model.Album( user_key=auth.current_user_key(), hostname=hostname, isCarousel=True ) carousel_album_db.put() carousel_resource_dbs = None if carousel_album_db: carousel_resource_dbs, cursors = carousel_album_db.get_resource_dbs() # get site albums query = model.Album.query( model.Album.hostname==hostname, model.Album.isCarousel==False ) album_dbs = query.fetch(30) # limit site albums to 30 album_list = [] for album_db in album_dbs: query = model.Resource.query( model.Resource.album_key==album_db.key ) album_image_db = query.get() if album_image_db: album_info = {'album_db': album_db, 'image_url': album_image_db.image_url} else: album_info = {'album_db': album_db, 'image_url': None} album_list.append(album_info) get_upload_url = None if carousel_album_db and isEditMode: get_upload_url=flask.url_for('api.album.resource.upload', key=carousel_album_db.key.urlsafe()) return flask.render_template( 'welcome.html', html_class='welcome', isEditMode=isEditMode, album_list=album_list, carousel_resource_dbs=carousel_resource_dbs, get_upload_url=get_upload_url, has_json=True, upload_url=blobstore.create_upload_url( flask.request.path, gs_bucket_name=config.CONFIG_DB.bucket_name or None, ), )
def admin_project_update(project_id=0): if project_id: project_db = model.Project.get_by_id(project_id) else: project_db = model.Project(user_key=auth.current_user_key()) if not project_db: flask.abort(404) form = ProjectUpdateAdminForm(obj=project_db) if form.validate_on_submit(): form.populate_obj(project_db) project_db.put() return flask.redirect(flask.url_for('admin_project_list', order='-modified')) return flask.render_template( 'project/admin_project_update.html', title=project_db.name, html_class='admin-project-update', form=form, project_db=project_db, back_url_for='admin_project_list', api_url=flask.url_for('api.admin.project', project_key=project_db.key.urlsafe() if project_db.key else ''), )
def admin_comment_update(comment_id=0): if comment_id: comment_db = model.Comment.get_by_id(comment_id) else: comment_db = model.Comment(user_key=auth.current_user_key()) if not comment_db: flask.abort(404) form = CommentUpdateAdminForm(obj=comment_db) user_dbs, user_cursor = model.User.get_dbs(limit=-1) post_dbs, post_cursor = model.Post.get_dbs(limit=-1) form.post_key.choices = [(c.key.urlsafe(), c.title) for c in post_dbs] if flask.request.method == 'GET' and not form.errors: form.post_key.data = comment_db.post_key.urlsafe() if comment_db.post_key else None if form.validate_on_submit(): form.post_key.data = ndb.Key(urlsafe=form.post_key.data) if form.post_key.data else None form.populate_obj(comment_db) comment_db.put() return flask.redirect(flask.url_for('admin_comment_list', order='-modified')) return flask.render_template( 'comment/admin_comment_update.html', title=comment_db.content, html_class='admin-comment-update', form=form, comment_db=comment_db, back_url_for='admin_comment_list', api_url=flask.url_for('api.admin.comment', comment_key=comment_db.key.urlsafe() if comment_db.key else ''), )
def resource_update(resource_id): resource_db = model.Resource.get_by_id(resource_id) if not resource_db or resource_db.user_key != auth.current_user_key(): return flask.abort(404) form = ResourceUpdateForm() if form.validate_on_submit(): resource_db.name = form.name.data resource_db.put() return flask.redirect(flask.url_for( 'resource_view', resource_id=resource_db.key.id(), )) if not form.errors: form.name.data = resource_db.name if flask.request.path.startswith('/_s/'): if form.errors: return flask.abort(400) return util.jsonify_model_db(resource_db) return flask.render_template( 'resource/resource_update.html', html_class='resource-update', title='%s' % (resource_db.name), resource_db=resource_db, form=form, has_json=True, )
def get(self, transaction_key): transaction_db = ndb.Key(urlsafe=transaction_key).get() if not transaction_db or transaction_db.user_key != auth.current_user_key( ): helpers.make_not_found_exception('Transaction %s not found' % transaction_key) return helpers.make_response(transaction_db, model.Transaction.FIELDS)
def addComment(): commentBody = request.form['commentBody'] tagsArr = request.form['tags'].split(',') print "tags: ", tagsArr print "comment body ", request.form['commentBody'] print "verrrdsflkfdskl ", request.form['verseId'] print "comment type", request.form['commentType'] print "verse id ", request.form['verseId'] print "in reply to", request.form['inReplyToCommentId'] comment_db = model.Comment( user_key=auth.current_user_key(), comment=request.form['commentBody'], verse_id=int(request.form['verseId']), commentType=request.form['commentType'], tags=tagsArr, ) try: comment_db.inReplyToCommentId = int(request.form['inReplyToCommentId']) print "did have a reply" except: print "didn't have a reply to id" comment_db.put() flask.flash('New comment was successfuly created!', category='success') print commentBody return commentBody
def resource_db_from_upload(): try: uploaded_file = flask.request.files['file'] except: return None headers = uploaded_file.headers['Content-Type'] blob_info_key = werkzeug.parse_options_header(headers)[1]['blob-key'] blob_info = blobstore.BlobInfo.get(blob_info_key) image_url = None if blob_info.content_type.startswith('image'): try: image_url = images.get_serving_url(blob_info.key()) except: pass resource_db = model.Resource( user_key=auth.current_user_key(), blob_key=blob_info.key(), name=blob_info.filename, content_type=blob_info.content_type, size=blob_info.size, image_url=image_url, bucket_name=config.CONFIG_DB.bucket_name or None, ) resource_db.put() return resource_db
def contact_view(contact_id): contact_db = model.Contact.get_by_id(contact_id) if not contact_db or contact_db.user_key != auth.current_user_key(): flask.abort(404) return flask.render_template( "contact_view.html", html_class="contact-view", title=contact_db.name, contact_db=contact_db )
def admin_person_update(person_id=0): if person_id: person_db = model.Person.get_by_id(person_id) else: person_db = model.Person(user_key=auth.current_user_key()) if not person_db: flask.abort(404) form = PersonUpdateAdminForm(obj=person_db) user_dbs, user_cursor = model.User.get_dbs(limit=-1) if flask.request.method == 'GET' and not form.errors: form.tags.data = config.TAG_SEPARATOR.join(form.tags.data) if form.validate_on_submit(): form.tags.data = util.parse_tags(form.tags.data) form.populate_obj(person_db) person_db.put() return flask.redirect(flask.url_for('admin_person_list', order='-modified')) return flask.render_template( 'person/admin_person_update.html', title=person_db.name, html_class='admin-person-update', form=form, person_db=person_db, back_url_for='admin_person_list', api_url=flask.url_for('api.admin.person', person_key=person_db.key.urlsafe() if person_db.key else ''), )
def put(self, collection): """Updates waypoint properties""" print "Update waypoint property" update_properties = ['name', 'creator', 'description', 'key'] # TODO urls update_properties = ['collection', 'key','name','description','tags','geo'] data = _.pick(request.json, update_properties) if 'collection' not in data: if data['collection'] != collection: return make_bad_request_exception("Wrong collection key") else: data['collection'] = collection if 'creator' not in data: data['creator'] = auth.current_user_key() else: data['creator'] = ndb.Key(urlsafe=data['creator']) if 'geo' in data: data['geo'] = ndb.GeoPt(data['geo']) try: data['key'] = ndb.Key(urlsafe=data['key']) except: data['key'] = None try: data['collection'] = ndb.Key(urlsafe=data['collection']) except: return make_bad_request_exception("Wrong collection key") #print data # TODO key from new data or as argument key = model.WayPoint.create_or_update(**data) return {'key':key.urlsafe(),'id':key.id()}
def addComment(): commentBody = request.form['commentBody'] tagsArr = request.form['tags'].split(',') print "tags: ", tagsArr; print "comment body ", request.form['commentBody'] print "verrrdsflkfdskl ", request.form['verseId'] print "comment type", request.form['commentType'] print "verse id ", request.form['verseId'] print "in reply to", request.form['inReplyToCommentId'] comment_db = model.Comment( user_key=auth.current_user_key(), comment=request.form['commentBody'], verse_id= int(request.form['verseId']), commentType=request.form['commentType'], tags=tagsArr, ) try: comment_db.inReplyToCommentId = int (request.form['inReplyToCommentId']) print "did have a reply" except: print "didn't have a reply to id" comment_db.put() flask.flash('New comment was successfuly created!', category='success') print commentBody return commentBody
def post(self): """ name = ndb.StringProperty(required=True,indexed=True) description = ndb.TextProperty() lessons = ndb.TextProperty() topics = ndb.KeyProperty(kind='Topic', repeated=True) contributors = ndb.KeyProperty(kind='User', repeated=True) approved = ndb.BooleanProperty(default=False) deadlock = ndb.BooleanProperty(default=False) color = ndb.StringProperty() vote = ndb.KeyProperty(kind='Vote') """ if util.param('name') and util.param('lessons'): b_name = util.param('name') b_description = util.param('description') b_topics = [ ndb.Key(urlsafe=topic_key_url) for topic_key_url in util.param('topics', list)] b_lessons = helpers.connected_entities_constructor(util.param('lessons', list)) b_contributor = auth.current_user_key() b_course = model.Course(name=b_name,description=b_description,topics=b_topics, contributors=[b_contributor], lessons=b_lessons).put() response = { 'status': 'success', 'count': 1, 'now': helpers.time_now(), 'result': {'message': 'Course was successfuly created!!', 'view_url': flask.url_for('course', course_key=b_course.urlsafe()) }, } return response return helpers.make_bad_request_exception("Unsifificient parameters")
def album_update(album_id): album_db = model.Album.get_by_id(album_id) if not album_db or album_db.user_key != auth.current_user_key(): return flask.abort(404) form = AlbumUpdateForm(obj=album_db) if form.validate_on_submit(): form.populate_obj(album_db) album_db.put() return flask.redirect(flask.url_for( 'album_view', album_id=album_db.key.id(), )) resource_dbs, cursors = album_db.get_resource_dbs() return flask.render_template( 'album/album_update.html', html_class='album-update', title='%s' % (album_db.name), album_db=album_db, form=form, resource_dbs=resource_dbs, get_upload_url=flask.url_for('api.album.resource.upload', key=album_db.key.urlsafe()), has_json=True, upload_url=blobstore.create_upload_url( flask.request.path, gs_bucket_name=config.CONFIG_DB.bucket_name or None, ), # api_url=flask.url_for('api.album.resource.upload', key=album_db.key.urlsafe()), )
def tournament_register(tournament_id, register_flag): tournament_db = model.Tournament.get_by_id(tournament_id) if not tournament_db: flask.abort(404) # TODO: Check if it's open for registrations first - george -> should we add an [open_for_registration] field ??? user_tournament_db = model.UserTournament.get_or_insert( str(auth.current_user_id()), parent=tournament_db.key, tournament_key=tournament_db.key, user_key=auth.current_user_key(), ) body = 'name: %s\nusername: %s\nemail: %s' % ( auth.current_user_db().name, auth.current_user_db().username, auth.current_user_db().email, ) creator_user_db = model.User.get_by_id(tournament_db.user_key.id()) if register_flag == 'register': user_tournament_db.put() flask.flash('Awesome! You are in..', category='success') # how to send an email to -> creator_user_db.email # task.send_mail_notification('%s entered tournament %s' % (auth.current_user_db().name, tournament_db.name), body) elif register_flag == 'unregister': user_tournament_db.key.delete() flask.flash('Bummer! You are out..', category='info') # how to send an email to -> creator_user_db.email # task.send_mail_notification('%s left tournament %s' % (auth.current_user_db().name, tournament_db.name), body) return flask.redirect(flask.url_for('tournament_view', tournament_id=tournament_id))
def delete(self, key): resource_db = ndb.Key(urlsafe=key).get() if not resource_db or (resource_db.user_key != auth.current_user_key() and not auth.current_user_db().admin): helpers.make_not_found_exception('Resource %s not found' % key) delete_resource_key(resource_db.key) return helpers.make_response(resource_db, model.Resource.FIELDS)
def resource_download(resource_id): resource_db = model.Resource.get_by_id(resource_id) if not resource_db or resource_db.user_key != auth.current_user_key(): return flask.abort(404) name = urllib.quote(resource_db.name.encode('utf-8')) url = '/serve/%s?save_as=%s' % (resource_db.blob_key, name) return flask.redirect(url)
def resource_upload(): form = PostUpdateForm() if form.validate_on_submit(): img_ids_list = [ int(id) for id in form.image.data.split(';') if id != '' ] post_db = model.Post(user_key=auth.current_user_key(), title=form.title.data, content=form.content.data, keywords=form.keywords.data, image_ids_string=form.image.data, img_ids=img_ids_list, image_url=get_img_url(img_ids_list[0])) post_db.put() flask.flash('New post was successfully created!', category='success') return flask.redirect(flask.url_for('post_list', order='-created')) return flask.render_template( 'resource/resource_upload.html', title='Resource Upload', html_class='resource-upload', get_upload_url=flask.url_for('api.resource.upload'), has_json=True, form=form, upload_url=blobstore.create_upload_url( flask.request.path, gs_bucket_name=config.CONFIG_DB.bucket_name or None, ), )
def user_update(user_id=0): if user_id: user_db = model.User.get_by_id(user_id) else: user_db = model.User(name='', username='') if not user_db: flask.abort(404) form = UserUpdateForm(obj=user_db) for permission in user_db.permissions: form.permissions.choices.append((permission, permission)) form.permissions.choices = sorted(set(form.permissions.choices)) if form.validate_on_submit(): if not util.is_valid_username(form.username.data): form.username.errors.append(_('This username is invalid.')) elif not model.User.is_username_available(form.username.data, user_db.key): form.username.errors.append(_('This username is already taken.')) else: form.populate_obj(user_db) if auth.current_user_key() == user_db.key: user_db.admin = True user_db.active = True user_db.put() return flask.redirect(flask.url_for( 'user_list', order='-modified', active=user_db.active, )) return flask.render_template( 'user/user_update.html', title=user_db.name or _('New User'), html_class='user-update', form=form, user_db=user_db, api_url=flask.url_for('api.admin.user', user_key=user_db.key.urlsafe()) if user_db.key else '' )
def resource_update(resource_id): resource_db = model.Resource.get_by_id(resource_id) if not resource_db or resource_db.user_key != auth.current_user_key(): return flask.abort(404) form = ResourceUpdateForm(obj=resource_db) if form.validate_on_submit(): form.populate_obj(resource_db) resource_db.put() return flask.redirect( flask.url_for( 'resource_view', resource_id=resource_db.key.id(), )) return flask.render_template( 'resource/resource_update.html', html_class='resource-update', title='%s' % (resource_db.name), resource_db=resource_db, form=form, api_url=flask.url_for('api.resource', key=resource_db.key.urlsafe()), )
def resource_db_from_upload(album_db): try: uploaded_file = flask.request.files['file'] except: return None headers = uploaded_file.headers['Content-Type'] blob_info_key = werkzeug.parse_options_header(headers)[1]['blob-key'] blob_info = blobstore.BlobInfo.get(blob_info_key) image_url = None if blob_info.content_type.startswith('image'): try: image_url = images.get_serving_url(blob_info.key()) except: pass resource_db = model.Resource( album_key=album_db.key, user_key=auth.current_user_key(), blob_key=blob_info.key(), name=blob_info.filename, content_type=blob_info.content_type, size=blob_info.size, image_url=image_url, bucket_name=config.CONFIG_DB.bucket_name or None, ) resource_db.put() return resource_db
def resource_update(resource_id): resource_db = model.Resource.get_by_id(resource_id) if not resource_db or resource_db.user_key != auth.current_user_key(): return flask.abort(404) form = ResourceUpdateForm() if form.validate_on_submit(): resource_db.name = form.name.data resource_db.put() return flask.redirect( flask.url_for( 'resource_view', resource_id=resource_db.key.id(), )) if not form.errors: form.name.data = resource_db.name if flask.request.path.startswith('/_s/'): if form.errors: return flask.abort(400) return util.jsonify_model_db(resource_db) return flask.render_template( 'resource/resource_update.html', html_class='resource-update', title='%s' % (resource_db.name), resource_db=resource_db, form=form, )
def get_resource(collection,category,name): # TODO auth.is_admin and collectio permission does not work !!! -> used True or if True or auth.is_admin() or model.Collection.has_permission(collection,auth.current_user_key().urlsafe(),'read',urlsafe=True): adr = BUCKET + '/' + collection + '/' + category + '/' + name blob_key = blobstore.create_gs_key('/gs' + adr) img_url = images.get_serving_url(blob_key=blob_key) print img_url return flask.redirect(img_url)
def update_alltime(): results = model.alltime.query(model.alltime.user_key == auth.current_user_key()).fetch(1) count = 0 for result in results: count += 1 if count < 1: user_db = auth.current_user_db() name = user_db.name alltime_db = model.alltime(user_key=auth.current_user_key(), player_name=name) else: alltime_db = result; alltime_db.wins += 1 alltime_db.put() return "success"
def delete(self, key): album_db = ndb.Key(urlsafe=key).get() if not album_db or album_db.user_key != auth.current_user_key(): helpers.make_not_found_exception('Album %s not found' % key) resource_dbs, cursors = album_db.get_resource_dbs() delete_resource_dbs(resource_dbs) delete_album_key(album_db.key) return helpers.make_response(album_db, model.Album.FIELDS)
def transaction_update(transaction_id=0): if transaction_id: transaction_db = model.Transaction.get_by_id(transaction_id) else: transaction_db = model.Transaction(user_key=auth.current_user_key()) if not transaction_db or transaction_db.user_key != auth.current_user_key( ): flask.abort(404) form = TransactionUpdateForm(obj=transaction_db) currency_dbs, currency_cursor = model.Currency.get_dbs(limit=-1) form.spent_currency_key.choices = [ (c.key.urlsafe(), '%s (%s)' % (c.name, c.code)) for c in currency_dbs ] form.acquired_currency_key.choices = [ (c.key.urlsafe(), '%s (%s)' % (c.name, c.code)) for c in currency_dbs ] if flask.request.method == 'GET' and not form.errors: form.spent_currency_key.data = transaction_db.spent_currency_key.urlsafe( ) if transaction_db.spent_currency_key else None form.acquired_currency_key.data = transaction_db.acquired_currency_key.urlsafe( ) if transaction_db.acquired_currency_key else None if form.validate_on_submit(): form.spent_currency_key.data = ndb.Key( urlsafe=form.spent_currency_key.data ) if form.spent_currency_key.data else None form.acquired_currency_key.data = ndb.Key( urlsafe=form.acquired_currency_key.data ) if form.acquired_currency_key.data else None form.spent_amount.data = form.spent_amount.data or 0 form.acquired_amount.data = form.acquired_amount.data or 0 form.fee.data = form.fee.data or 0 form.populate_obj(transaction_db) transaction_db.put() return flask.redirect(flask.url_for('welcome')) return flask.render_template( 'transaction/transaction_update.html', title='%s' % 'Investment' if transaction_id else 'New investment', html_class='transaction-update', form=form, transaction_db=transaction_db, )
def post(self, key): album_db = ndb.Key(urlsafe=key).get() if album_db and album_db.user_key == auth.current_user_key(): resource_db = resource_db_from_upload(album_db=album_db) if resource_db: return helpers.make_response(resource_db, model.Resource.FIELDS) flask.abort(500)
def my_favorites(): fav_db, fav_cursor = model.tvShows.get_dbs( user_key=auth.current_user_key()) #todayShows = getAirsToday() return flask.render_template('favorites.html', html_class='my-favorites', show=fav_db, back_url='my_favorites')
def remove_favorite(id): favorite_db = model.tvShows.get_by_id(id) if not favorite_db or favorite_db.user_key != auth.current_user_key(): flask.abort(404) else: favorite_db.key.delete() flask.flash("Removed from favorites.", category='success') return flask.redirect(flask.url_for('my_favorites'))
def resource_db_from_upload(): try: uploaded_file = flask.request.files['file'] except: return None bucket_name, origin_dir, object_name = extract_cloud_storage_meta_data( uploaded_file) headers = uploaded_file.headers['Content-Type'] blob_info_key = werkzeug.parse_options_header(headers)[1]['blob-key'] blob_info = blobstore.BlobInfo.get(blob_info_key) gcs_object_path = "{}/{}/{}".format(bucket_name, origin_dir, object_name) image_url = None public_url = None if blob_info.content_type.startswith('image'): try: image_url = images.get_serving_url(blob_info.key(), secure_url=True) except: pass else: response = storage.objects().patch( bucket=bucket_name, object="{}/{}".format(origin_dir, object_name), body={ 'acl': [{ "entity": "project-owners-825037505474", "role": "OWNER" }, { "entity": "project-editors-825037505474", "role": "OWNER" }, { "entity": "project-viewers-825037505474", "role": "READER" }, { "entity": "allUsers", "role": "READER" }] }).execute() public_url = "https://storage.googleapis.com/{}?content_type={}".format( gcs_object_path, blob_info.content_type) resource_db = model.Resource( user_key=auth.current_user_key(), blob_key=blob_info.key(), name=blob_info.filename, content_type=blob_info.content_type, size=blob_info.size, image_url=image_url, public_url=public_url, bucket_name=get_bucket_and_path_name() or None, gcs_object_path=gcs_object_path, ) resource_db.put() return resource_db
def resource_delete(resource_id): resource_db = model.Resource.get_by_id(resource_id) if not resource_db or resource_db.user_key != auth.current_user_key(): return flask.abort(404) blobstore.BlobInfo.get(resource_db.blob_key).delete() resource_db.key.delete() return util.jsonify_model_db(resource_db)
def person_list(): person_dbs, person_cursor = model.Person.get_dbs(user_key=auth.current_user_key()) return flask.render_template( 'person/person_list.html', html_class='person-list', title=u'People I’ve met', person_dbs=person_dbs, next_url=util.generate_next_url(person_cursor), api_url=flask.url_for('api.person.list'), )
def update_alltime(): results = model.alltime.query( model.alltime.user_key == auth.current_user_key()).fetch(1) count = 0 for result in results: count += 1 if count < 1: user_db = auth.current_user_db() name = user_db.name alltime_db = model.alltime(user_key=auth.current_user_key(), player_name=name) else: alltime_db = result alltime_db.wins += 1 alltime_db.put() return "success"
def project_list(): project_dbs, project_cursor = model.Project.get_dbs(user_key=auth.current_user_key()) return flask.render_template( 'project/project_list.html', html_class='project-list', title='Projects', project_dbs=project_dbs, next_url=util.generate_next_url(project_cursor), api_url=flask.url_for('api.project.list'), )
def contact_view(contact_id): contact_db = model.Contact.get_by_id(contact_id) if not contact_db or contact_db.user_key != auth.current_user_key(): flask.abort(404) return flask.render_template( 'contact_view.html', html_class='contact-view', title=contact_db.name, contact_db=contact_db, )
def get(self, username): parser = reqparse.RequestParser() parser.add_argument('cursor', type=ArgumentValidator.create('cursor')) parser.add_argument('q', type=str,default='') parser.add_argument('size', type=int,default=10) args = parser.parse_args() # current user key user_key = g.user_db.key if auth.is_admin() or user_db.key == auth.current_user_key(): query = model.CollectionUser.qry(user=user_key) collection_keys_future = query.fetch_async(limit=args.size*4,keys_only=True) # do something else here? collection_keys = collection_keys_future.get_result() collection_keys = [key.parent() for key in collection_keys] # Search for users in this collections users = []; for key in collection_keys: query = model.CollectionUser.query(ancestor=key) if len(args.q) > 2: query = query \ .filter(model.CollectionUser.user.username >= args.q) \ .filter(model.CollectionUser.user.username <= unicode(args.q) + u"\ufffd")\ .order(model.CollectionUser.user.username) else: query = query.order(model.CollectionUser.modified) users_future = query.fetch_async( limit=args.size, projection=['modified','user.username','user.email','user.avatar_url','user_key']) users = users + users_future.get_result() #users = users + [{'key':u.key,'modified':u.modified} for u in users_future.get_result()] # check if a user with this name or email exists: user_db = model.User.get_by_email_or_username(args.q) if len(args.q)>2 else None if user_db: # create temp user with modified now -> first in list user = model.CollectionUser( user_key= user_db.key, user = model.User(username = user_db.username, email = user_db.email, avatar_url = user_db.avatar_url), name = "Just Temp User", modified = datetime.datetime.now(), created = datetime.datetime.now() ) users.append(user) # sort users after its last modification users = util.sort_uniq(users,'modified','user_key',reverse=False) #users = [u.urlsafe() for u in users] users = [u.to_dict(include=['modified','user','user_key']) for u in users] total = len(users) if total > args.size: users = users[:args.size] return make_list_response(users, None, total > args.size, total)
def store_module_config(config, meta, module_id): module_config_db = find_by_module_id(module_id) if not module_config_db: module_config_db = model.ModuleConfig(user_key=auth.current_user_key()) fill_module_config(module_config_db, config, module_id) fill_module_config_meta(module_config_db, meta) save_to_db(module_config_db) if module_id in cache_mapping: memcache.delete(cache_mapping[module_id]) return module_config_db
def contact_list(): contact_dbs, contact_cursor = model.Contact.get_dbs( user_key=auth.current_user_key(), ) return flask.render_template( 'contact_list.html', html_class='contact-list', title='Contact List', contact_dbs=contact_dbs, next_url=util.generate_next_url(contact_cursor), )
def transaction_list(): transaction_dbs, transaction_cursor = model.Transaction.get_dbs( user_key=auth.current_user_key()) return flask.render_template( 'transaction/transaction_list.html', html_class='transaction-list', title='Transaction List', transaction_dbs=transaction_dbs, next_url=util.generate_next_url(transaction_cursor), api_url=flask.url_for('api.transaction.list'), )
def tournament_update(tournament_id=0): if tournament_id == 0: tournament_db = model.Tournament(user_key=auth.current_user_key(), name='') else: tournament_db = model.Tournament.get_by_id(tournament_id) if not tournament_db or tournament_db.user_key != auth.current_user_key(): flask.abort(404) form = TournamentUpdateForm(obj=tournament_db) if form.validate_on_submit(): form.populate_obj(tournament_db) tournament_db.put() return flask.redirect(flask.url_for('my_tournament_list')) return flask.render_template( 'tournament/tournament_update.html', html_class='tournament-update', title='%s' % ('Create Tournament' if tournament_id == 0 else tournament_db.name), form=form, tournament_db=tournament_db, )
def post_view(post_id): post_db = model.Post.get_by_id(post_id) if not post_db or post_db.user_key != auth.current_user_key(): flask.abort(404) return flask.render_template( 'post_view.html', html_class='post-view', title=post_db.title, post_db=post_db, url_list=[get_img_url(id) for id in post_db.img_ids] )
def delete(self, post_key): post_db = model.Post.get_by_id(post_key) user_db = auth.current_user_key().get() stars = model.Star.query(model.Star.post_key == post_db.key, model.Star.user_key == user_db.key).fetch() for star in stars: star.key.delete() return str(stars)
def contact_update(contact_id): contact_db = model.Contact.get_by_id(contact_id) if not contact_db or contact_db.user_key != auth.current_user_key(): flask.abort(404) form = ContactUpdateForm(obj=contact_db) if form.validate_on_submit(): form.populate_obj(contact_db) contact_db.put() return flask.redirect(flask.url_for("contact_list", order="-modified")) return flask.render_template( "contact_update.html", html_class="contact-update", title=contact_db.name, form=form, contact_db=contact_db )
def contact_view(contact_id): contact_db = model.Contact.get_by_id(contact_id, parent=ROOT.key) if not contact_db or contact_db.user_key != auth.current_user_key(): flask.abort(404) return flask.render_template( 'contact_view.html', html_class='contact-view', title=contact_db.name, contact_db=contact_db, )
def get(self,collection,category,name): """Updates user's properties""" if auth.is_admin() or model.Collection.has_permission(collection,auth.current_user_key().urlsafe(),'read',urlsafe=True): adr = BUCKET + '/' + collection + '/' + category + '/' + name blob_key = blobstore.create_gs_key('/gs' + adr) img_url = images.get_serving_url(blob_key=blob_key) return img_url return "No permission" properties = model.Collection.get_private_properties() properties = model.Collection.get_public_properties() return g.model_db.to_dict(include=properties+['permission','permissionNr'])
def post(self, vote_key): """Update a specific vote""" vote_db = ndb.Key(urlsafe=vote_key).get() vote = 0 if util.param('data', str) == 'upvote': vote = ct.UP_VOTE elif util.param('data', str) == 'downvote': vote = ct.DOWN_VOTE else: flask.abort(505) vote_db.vote(auth.current_user_key().urlsafe(), vote) return "Success"