def search(index_name): """ Search the index for documents matching the given query. """ if not request.args.get("q"): error('Missing required search parameter "q".') search_query = request.args["q"] ranking = request.args.get("ranking", Index.RANK_SIMPLE) if ranking and ranking not in (Index.RANK_SIMPLE, Index.RANK_BM25): error('Unrecognized "ranking" type.') filters = dict((key, request.args.getlist(key)) for key in request.args if key not in _PROTECTED_KEYS) index = get_object_or_404(Index, Index.name == index_name) query = index.search(search_query, ranking, True, **filters) pq = PaginatedQuery( query, paginate_by=app.config["PAGINATE_BY"], page_var=app.config["PAGE_VAR"], check_bounds=False ) return jsonify( { "documents": _serialize_documents(pq.get_object_list(), include_score=ranking is not None), "page": pq.get_page(), "pages": pq.get_page_count(), } )
def detail(slug): if session.get('loged_in'): query = Entry.select() else: query = Entry.public() entry = get_object_or_404(query, Entry.slug == slug) return render_template('detail.html', entry=entry)
def page_delete(pk): page = get_object_or_404(Content.select(), (Content.id == pk)) if request.method == "POST": page.delete_instance() return redirect(url_for("page")) return {"page": page}
def get_archive_upload_credentials(api_key): world = get_object_or_404(World, World.api_key == api_key) user = world.user post_api_key = str(api_key) post_user_guid = str(user.guid) post_world_guid = str(world.guid) size_range = [int(s) for s in CFG.mget([ 'config:quarry-api:ARCHIVE_MIN_SIZE', 'config:quarry-api:ARCHIVE_MAX_SIZE', ])] return s3c.generate_presigned_post( Bucket=UPLOAD_BUCKET, Key='world-archives/{archive_name}.zip'.format(archive_name=post_api_key), Fields={ 'acl': 'private', # 'success_action_status': 200, 'x-amz-meta-quarry-api-key': post_api_key, 'x-amz-meta-quarry-user-id': post_user_guid, 'x-amz-meta-quarry-world-id': post_world_guid, }, Conditions=[ {'acl': 'private'}, ['content-length-range'] + size_range, {'x-amz-meta-quarry-api-key': post_api_key}, {'x-amz-meta-quarry-user-id': post_user_guid}, {'x-amz-meta-quarry-world-id': post_world_guid}, ], ExpiresIn=UPLOAD_KEY_TTL, )
def user_delete_verify(user): u = get_object_or_404(User, User.username == user) if u.id != current_user.id: return render_template('403.html'), 403 return render_template('user_delete_verify.html', user=u)
def search(index_name): """ Search the index for documents matching the given query. """ if not request.args.get('q'): error('Missing required search parameter "q".') search_query = request.args['q'] ranking = request.args.get('ranking', Index.RANK_SIMPLE) if ranking and ranking not in (Index.RANK_SIMPLE, Index.RANK_BM25): error('Unrecognized "ranking" type.') filters = dict( (key, value) for key, value in request.args.items() if key not in ('page', 'q', 'key', 'ranking')) index = get_object_or_404(Index, Index.name == index_name) query = index.search(search_query, ranking, **filters) pq = PaginatedQuery( query, paginate_by=app.config['PAGINATE_BY'], page_var=app.config['PAGE_VAR'], check_bounds=False) return jsonify({ 'documents': _serialize_documents( pq.get_object_list(), include_score=ranking is not None), 'page': pq.get_page(), 'pages': pq.get_page_count()})
def attachment_download(document_id, pk): document = get_object_or_404( Document.all(), Document._meta.primary_key == document_id) attachment = get_object_or_404( document.attachments, Attachment.filename == pk) _close_database(None) response = make_response(attachment.blob.data) response.headers['Content-Type'] = attachment.mimetype response.headers['Content-Length'] = attachment.length response.headers['Content-Disposition'] = 'inline; filename=%s' % ( attachment.filename) return response
def single(slug): if session.get('logged_in'): query = Post.select() else: query = Post.public() post = get_object_or_404(query, Post.slug == slug) return render_template('pc/single.html', post=post,main_title= post.title,site_name=site_name)
def detail(slug): query = Entry.all() entry = get_object_or_404(query, Entry.slug == slug) tags = "" for tag in entry.tags: tags = tags + " " + tag.tag return render_template("detail.html", entry=entry, tags=tags)
def image(site_id=None): if site_id: query = Site.select().where((Site.last_download.is_null(False)) & (Site.id == site_id)) site = get_object_or_404(query) else: class DummySite(object): pass site = DummySite() site.foreground_color = "black" site.background_color = "white" # parameters text = "Stack Exchange\nSimulator" selected_font = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf" font_size = 70 W, H = (600, 600) # # get the size of the text img = Image.new("RGBA", (W, H), (site.background_color if site.background_color else "white")) font = ImageFont.truetype(selected_font, font_size) draw = ImageDraw.Draw(img) w, h = draw.multiline_textsize(text, font) draw.multiline_text(((W - w) / 2, (H - h) / 2), text, font=font, align="center", fill=(site.foreground_color if site.foreground_color else "black")) byte_io = BytesIO() img.save(byte_io, "PNG", optimize=True) byte_io.seek(0) return send_file(byte_io, mimetype="image/png")
def detail(slug): if session.get('logged_in'): query = Entry.select() else: query = Entry.public() entry = get_object_or_404(query, Entry.slug == slug) return render_template('detail.html', entry=entry)
def course_details(course_id): query = (Course .select(Course, Category.name, Provider.name) .join(Category) .join(Provider, on=(Course.provider == Provider.id))) course = get_object_or_404(query, Course.id == course_id) Course.update(read_count=Course.read_count + 1).where(Course.id == course_id).execute() return render_template('course_details.html', course=course, **Course.MAPPINGS)
def user_courses(): user = get_object_or_404(User, (User.username == get_jwt_identity())) courses = UserCourse.select().join(User).where(User.id == user.id).select() courses_schema = UserCourseSchema(many=True) return courses_schema.jsonify(courses), HTTPStatus.OK
def document_detail(document_id): """ Return the details for an individual document. This view can also be used to update the `content`, `index(es)` and, optionally, `metadata`. To remove a document, issue a `DELETE` request to this view. """ document = get_object_or_404(Document.all(), Document._meta.primary_key == document_id) return _document_detail(document)
def detail(slug): if session.get('logged_in'): query = Entry.select() else: query = Entry.public() # fairly self-defining but I'm not sure what the 404 object is (TODO) entry = get_object_or_404(query, Entry.slug == slug) return render_template('detail.html', entry=entry)
def post_revisions(community, slug): query = Proposal.public() community = Community.get_or_none(Community.name == community) entry = get_object_or_404(query, Proposal.slug == slug, Proposal.community == community) return render_template('post_revisions.html', entry=entry, community=community)
def get(self,slug): query = Post.select() post = get_object_or_404(query,Post.slug==slug) for comment in post.comments: comment.delete_instance() PostIndex.delete().where(PostIndex.post_id ==post.id).execute() post.delete_instance() return redirect('/admin/')
def _edit_object_by_id(model, id_: int, **kwargs) -> None: obj = get_object_or_404(model, model.id == id_) edited_fields = [] for field_name, value in kwargs.items(): field = getattr(model, field_name) edited_fields.append(field) setattr(obj, field_name, value) obj.save(only=edited_fields)
def _get_document(self, pk): if isinstance(pk, int) or (pk and pk.isdigit()): query = Document.all().where(Document._meta.primary_key == pk) try: return query.get() except Document.DoesNotExist: pass return get_object_or_404(Document.all(), Document.identifier == pk)
def klasa(klasa_id): klasa_obj = get_object_or_404(Klasa, Klasa.id == klasa_id) uczniowie_obj = Uczen.select().order_by( Uczen.nazwisko, Uczen.imie).where(Uczen.klasa == klasa_id) liczba_uczniow = uczniowie_obj.count() return render_template('klasa.html', klasa=klasa_obj, uczniowie=uczniowie_obj, liczba_uczniow=liczba_uczniow)
def save_code(exerciseId: str): user = get_object_or_404(User, (User.username == get_jwt_identity())) exercise = get_object_or_404( UserCourseExercise, (UserCourseExercise.platform_course_exercise_id == exerciseId), (UserCourseExercise.user == user)) code = request.json.get('code') if code is None: return {}, HTTPStatus.BAD_REQUEST exercise.saved_code = code exercise.save() return UserCourseExerciseSchema().jsonify(exercise), HTTPStatus.OK
def get(self, pk: int) -> dict: user = get_object_or_404(User, (User.id == pk)) page = request.args.get('p', 1, type=int) if page < 1: page = 1 streams = Stream.select().where(Stream.user == user).order_by( Stream.name).paginate(page) return stream_schema.dump(streams, many=True)
def followers(username): user = get_object_or_404(User, User.username == username) return object_list('follows.html', user.followers(), check_bounds=False, context_variable='follows_list', user=user, endpoint='main.followers')
def usun_klase(klasa_id): klasa_obj = get_object_or_404(Klasa, Klasa.id == klasa_id) if request.method == 'POST': message_name = klasa_obj.nazwa klasa_obj.delete_instance() flash("Usunięto klasę: {}".format(message_name), 'alert-success') return redirect(url_for('klasy')) return render_template('usun_klase.html', klasa=klasa_obj)
def orders_status(order_id: UUID) -> Response: input_data = request.get_json() or "" current_app.logger.info(f"afdsfsfs: {input_data}") if input_data: order = get_object_or_404(Order, Order.id == order_id) order.status = getattr(OrderStatus, input_data) order.save() return api_jsonify({}), 204
def delete(self, pk): index = get_object_or_404(Index, Index.name == pk) with database.atomic(): (IndexDocument.delete().where( IndexDocument.index == index).execute()) index.delete_instance() return jsonify({'success': True})
def detail(slug): if session.get("logged_in"): query = Entry.select() else: query = Entry.public() entry = get_object_or_404( query, Entry.slug == slug ) # The get_object_or_404 helper is defined in the playhouse flask_utils module and, if an object matching the query is not found, will return a 404 response. return render_template("detail.html", entry=entry)
def user(username): user_query = User.select() user = futils.get_object_or_404(user_query, (User.username == username)) pagination = Pagination(user.posts.order_by(Post.timestamp.desc()), current_app.config['FLASKR_POSTS_PER_PAGE'], check_bounds=False) posts = pagination.items return render_template('user.html', user=user, posts=posts, pagination=pagination)
def user_course(platformCourseId: int): user = get_object_or_404(User, (User.username == get_jwt_identity())) user_course = UserCourse.get_or_create(user=user, platform_course_id=platformCourseId) return UserCourseSchema().jsonify( user_course[0] ), HTTPStatus.CREATED if user_course[1] else HTTPStatus.OK # NOQA
def set_user_course_position(platformCourseId: int): user = get_object_or_404(User, (User.username == get_jwt_identity())) position_id = request.json.get('platformCourseExerciseId', 0) position = get_object_or_404( UserCourseExercise, (UserCourseExercise.platform_course_exercise_id == position_id), (UserCourseExercise.user == user)) course = UserCourse.select().join(User).where( User.id == user.id, UserCourse.platform_course_id == platformCourseId).get() course.position = position course.save() return UserCourseSchema().jsonify(course), HTTPStatus.OK
def page_edit(pk): page = get_object_or_404(Content.select(), (Content.id == pk)) form = PageForm(request.form, obj=page) if request.method == 'POST': if form.validate(): form.populate_obj(page) page.save() return redirect(url_for("page")) return {"form": form}
def rooms_say(id): room = get_object_or_404(Room, Room.id == id) if not room.is_user_in_room(g.me): abort(401) text = request.form.get('text', '') if not text.strip(): abort(400) message = room.say(text, g.me) return jsonify(message)
def detail(slug): if session.get('logged_in'): query = Entry.select() else: query = Entry.public() if slug == 'README': entry = Entry(title='README', content=APP_README, slug=slug) else: entry = get_object_or_404(query, Entry.slug == slug) return render_template('detail.html', entry=entry, user=USER)
def usun_ucznia(uczen_id): uczen = get_object_or_404(Uczen, Uczen.id == uczen_id) if request.method == 'POST': message = (uczen.imie, uczen.nazwisko) uczen.delete_instance() flash("Usunięto ucznia: {} {}".format( message[0], message[1]), 'alert-success') return redirect(url_for('uczniowie')) return render_template('usun_ucznia.html', uczen=uczen)
def detail(slug): # makes sense to have these two things for public and private viewing # todo: think about whether there would be any use of "private" entries other than for drafts if session.get("logged_in"): query = Entry.select() else: query = Entry.public() # todo: research how this method works entry = get_object_or_404(query, Entry.slug == slug) return render_template("detail.html", entry=entry)
def edit_post(id): post = futils.get_object_or_404(Post.select(), (Post.id == id)) if g.current_user != post.author and \ not g.current_user.can(Permission.ADMINISTER): return forbidden('Insufficient permissions') post.body = request.json.get('body', post.body) post.save() post.update_body_html() post = post.refresh() return jsonify(post.to_json())
def get(self, id): if Staff.select().count() != 0: query = Staff.select() staff = get_object_or_404(query, Staff.id == int(id)) return render_template('staffs/staff.html', staff=staff, title=staff.name) else: content = 'There are current no staff' return render_template('infor.html', content=content)
def edit_user(id): user = get_object_or_404(User, (User.id == id)) form = EditUser() if form.validate_on_submit(): user.username = form.username.data user.nickname = form.nickname.data user.gender = form.gender.data user.save() flash('修改成功') return redirect(url_for('bp_user.profile', id=user.id)) return render_template('user/edit_user.html', form=form, user=user)
def get_context(self, slug): query = Post.select() post = get_object_or_404(query, Post.slug==slug) form = self.form(request.form) context = { 'post': post, 'form': form } return context
def delete(self, pk): index = get_object_or_404(Index, Index.name == pk) with database.atomic(): (IndexDocument .delete() .where(IndexDocument.index == index) .execute()) index.delete_instance() return jsonify({'success': True})
def new_post_comment(id): post = futils.get_object_or_404(Post.select(), (Post.id == id)) comment = Comment.from_json(request.json) comment.author = g.current_user comment.post = post comment.save() comment.update_body_html() comment = comment.refresh() return jsonify(comment.to_json()), 201, \ {'Location': url_for('api.get_comment', id=comment.id, _external=True)}
def update(self, pk): index = get_object_or_404(Index, Index.name == pk) data = self.validator.parse_post(['name']) index.name = data['name'] with database.atomic(): try: index.save() except IntegrityError: error('"%s" is already in use.' % index.name) return self.detail(index.name)
def rooms_messages(id): room = get_object_or_404(Room, Room.id == id) if not room.is_user_in_room(g.me): abort(401) size = request.args.get('size', '50') before = request.args.get('before', 'inf') after = request.args.get('after') if after: messages = room.messages_after(after, int(size)) else: messages = room.messages_before(before, int(size)) return jsonify(messages)
def edit(id): article = get_object_or_404(Article, Article.id == id) categories = Category.select() tags = Tag.select() entry = article tag_arry = [] for tag in article.tags: tag_arry.append(tag.name) entry_tags = ' '.join(tag_arry) return render_template('create.html', categories=categories, tags=tags, entry=entry, entry_tags=entry_tags)
def dump_excel(course_id): """ 输出单个课程记录的excel表格文件 :param course_id:课程id :return: 带有附件的Response对象,附件文件名为'resource_table_' + 当前时间(iso格式) + '.xlsx' """ query = (Course .select(Course, Category.name) .join(Category)) course = get_object_or_404(query, Course.id == course_id) Course.update(download_count=Course.download_count + 1).where(Course.id == course_id).execute() wb = generate_excel_file([course]) return make_response_with_excel(wb)
def edit(slug): entry = get_object_or_404(Entry, Entry.slug == slug) tags = "" for tag in entry.tags: tags = tags + " " + tag.tag if request.method == "POST": if request.form.get("title") and request.form.get("content"): try: entry.title = request.form["title"] entry.content = request.form["content"] entry.archived = request.form.get("archived") or False entry.lastedited = datetime.datetime.now() # convert the string of tags to a list tags = request.form["tags"].split() # present is a check to see if the tag exists present = 0 # add or create tags for tag in tags: for entrytag in entry.tags: if tag == entrytag.tag: present = 1 if present == 0: try: thistag = Tag.get(Tag.tag == tag) entry.tags.add(thistag) except: tag_obj, was_created = Tag.create_or_get(tag=tag) EntryTags.create(tag=tag_obj, entry=entry) present = 0 # remove tags for entrytag in entry.tags: for tag in tags: if entrytag.tag == tag: present = 1 if present == 0: thistag = Tag.get(Tag.tag == entrytag.tag) entry.tags.remove(thistag) present = 0 entry.save() flash("Note updated successfully.", "success") return redirect(url_for("detail", slug=entry.slug)) except: flash("Note title already exists", "danger") return render_template("create.html") else: flash("Title and Content are required.", "danger") return render_template("edit.html", entry=entry, tags=tags)
def graphic_update(id): if session.get('logged_in'): query = Entry.select() else: query = Entry.public() entry = get_object_or_404(query, Entry.id == id) filename = str(entry.id) savefile = 'static/images/' + filename + '.png' imgfile = requests.get(entry.imgurl) with open(savefile, 'wb') as f: f.write(imgfile.content) return redirect(url_for('graphic', id=entry.id))
def update(id): entry = get_object_or_404(Entry, Entry.id == id) if request.method == 'POST': entry.publink = request.form['publink'] entry.published = request.form.get('published') or False entry.save() flash('Entry saved successfully.', 'success') if entry.published: # return redirect(url_for('detail', id=entry.id)) return redirect(url_for('drafts')) else: # return redirect(url_for('edit', id=entry.id)) return redirect(url_for('drafts')) return render_template('edit.html', entry=entry)
def edit(slug): entry = get_object_or_404(Entry, Entry.slug == slug) if request.method == 'POST': if request.form.get('title') and request.form.get('content'): entry.ttile = request.form['title'] entry.content = request.form['content'] entry.published = request.form.get('published') or False entry.save() flash ('Entry saved successfully', 'success') if entry.published: return redirect(url_for('detail', slug=entry.slug)) else: return redirect(url_for('edit', slug=entry.slug)) else: flash('Title and content are required', 'danger') return render_template('edit.html', entry='entry')
def edit(slug): """Edit existing blog Entry""" entry = get_object_or_404(Entry, Entry.slug == slug) if request.method == 'POST': if request.form.get('title'): entry.title = request.form.get('title') if request.form.get('content'): entry.content = request.form.get('content') entry.published = request.form.get('published') or False entry.save() flash('Entry saved successfully!', 'success') if entry.published: return redirect(url_for('detail', slug=entry.slug)) else: return redirect(url_for('edit', slug=entry.slug)) return render_template('edit.html', entry=entry)
def graphic(id): if session.get('logged_in'): query = Entry.select() else: query = Entry.public() entry = get_object_or_404(query, Entry.id == id) bust = random.random() filename = str(entry.id) savefile = 'static/images/' + filename + '.png' if not os.path.isfile(savefile): imgfile = requests.get(entry.imgurl) with open(savefile, 'wb') as f: f.write(imgfile.content) return render_template('graphic.html', entry=entry, bust=bust, savefile=savefile)
def detail(id): if session.get('logged_in'): query = Entry.select() else: query = Entry.public() entry = get_object_or_404(query, Entry.id == id) # fblink = urllib.quote_plus(entry.publink) fburl = ('https://api.facebook.com/method/links.getStats?urls=%s&format=json' % entry.publink) fbresponse = urllib.urlopen(fburl) fbshares = json.load(fbresponse) # Deprecated # twurl = ('http://urls.api.twitter.com/1/urls/count.json?url=%s' % entry.publink) # twresponse = urllib.urlopen(twurl); # twshares = json.load(twresponse) twshares = 0 return render_template('detail.html', entry=entry, fbshares=fbshares, twshares=twshares)
def edit(slug): post = get_object_or_404(Post, Post.slug == slug) if request.method == 'POST': if request.form.get('title') and request.form.get('content'): #post.slug = request.form['post_slug'] post.title = request.form['title'] post.content = request.form['content'] post.published = request.form.get('published') or False post.save() flash('保存成功!', 'warn') if post.published: return redirect(url_for('single', slug=post.slug)) else: return redirect(url_for('edit', slug=post.slug)) else: flash('所有项目均为必填项!', 'error') return render_template('pc/edit.html', post=post,main_title='编辑文章',site_name=site_name)
def get_context(self, slug=None): form_cls = model_form(Post, exclude=('timestamp', 'comments','slug','author')) if slug: query = Post.select() post = get_object_or_404(query, Post.slug ==slug) if request.method == 'POST': form = form_cls(request.form, intial=post.content) else: form = form_cls(obj=post) else: post = Post() form = form_cls(request.form) context = { 'post': post, 'form': form, 'create': slug is None } return context
def index_detail(index_name): """ Detail view for an index. This view returns a JSON object with the index's id, name, and a paginated list of associated documents. Existing indexes can be renamed using this view by `POST`-ing a `name`, or deleted by issuing a `DELETE` request. """ index = get_object_or_404(Index, Index.name == index_name) if request.method == 'POST': data = parse_post(['name']) index.name = data['name'] with database.atomic(): try: index.save() except IntegrityError: error('"%s" is already in use.' % index.name) elif request.method == 'DELETE': with database.atomic(): (IndexDocument .delete() .where(IndexDocument.index == index) .execute()) index.delete_instance() return jsonify({'success': True}) pq = PaginatedQuery( index.documents, paginate_by=app.config['PAGINATE_BY'], page_var=app.config['PAGE_VAR'], check_bounds=False) return jsonify({ 'id': index.id, 'name': index.name, 'documents': _serialize_documents(pq.get_object_list()), 'page': pq.get_page(), 'pages': pq.get_page_count()})
def detail(slug): if current_user.is_authenticated: query = Article.select() else: query = Article.public() article = get_object_or_404(query, Article.slug == slug) comments = article.comments qp = query.where(Article.id > article.id).order_by( Article.id.asc()).limit(1) qn = query.where(Article.id < article.id).order_by( Article.id.desc()).limit(1) try: prev_slug = qp[0].slug except: prev_slug = None try: next_slug = qn[0].slug except: next_slug = None return render_template('detail.html', entry=article, comments=comments, prev_slug=prev_slug, next_slug=next_slug)
def edit(id): entry = get_object_or_404(Entry, Entry.id == id) if request.method == 'POST': if request.form.get('title') and request.form.get('link'): entry.title = request.form['title'] entry.fbtitle = request.form['fbtitle'] entry.link = request.form['link'] entry.imgurl = request.form['imgurl'] entry.publink = request.form['publink'] entry.content = request.form['content'] entry.published = request.form.get('published') or False entry.save() flash('Entry saved successfully.', 'success') if entry.published: return redirect(url_for('detail', id=entry.id)) # return redirect(url_for('drafts')) else: # return redirect(url_for('edit', id=entry.id)) return redirect(url_for('drafts')) else: flash('Title and Link are required.', 'danger') return render_template('edit.html', entry=entry)
def _get_attachment(self, document, pk): return get_object_or_404( document.attachments, Attachment.filename == pk)