예제 #1
0
파일: scout.py 프로젝트: sharpglasses/scout
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(),
        }
    )
예제 #2
0
파일: app2.py 프로젝트: ack8006/WellWisdom
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)
예제 #3
0
파일: page.py 프로젝트: gkrnours/plume
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}
예제 #4
0
파일: app.py 프로젝트: quarrius/quarry-api
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,
    )
예제 #5
0
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)
예제 #6
0
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()})
예제 #7
0
파일: scout.py 프로젝트: adamchainz/scout
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
예제 #8
0
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
예제 #9
0
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)
예제 #10
0
파일: views.py 프로젝트: keybits/permanote
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)
예제 #11
0
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")
예제 #12
0
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)
예제 #13
0
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)
예제 #14
0
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
예제 #15
0
파일: scout.py 프로젝트: sharpglasses/scout
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)
예제 #16
0
파일: app.py 프로젝트: austin-b/FlaskBlog
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)
예제 #17
0
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)
예제 #18
0
	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/')
예제 #19
0
파일: crud.py 프로젝트: JleMyP/wol
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)
예제 #20
0
 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)
예제 #21
0
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)
예제 #22
0
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
예제 #23
0
 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)
예제 #24
0
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')
예제 #25
0
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)
예제 #26
0
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
예제 #27
0
파일: scout.py 프로젝트: rnewman/scout
    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})
예제 #28
0
파일: app.py 프로젝트: ninabcdefghi/blog
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)
예제 #29
0
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)
예제 #30
0
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
예제 #31
0
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
예제 #32
0
파일: page.py 프로젝트: gkrnours/plume
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}
예제 #33
0
파일: room.py 프로젝트: gfreezy/pushpin
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)
예제 #34
0
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)
예제 #35
0
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)
예제 #36
0
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)
예제 #37
0
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())
예제 #38
0
 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)
예제 #39
0
파일: views.py 프로젝트: hr-system/zhaoping
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)
예제 #40
0
	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
예제 #41
0
파일: scout.py 프로젝트: adamchainz/scout
    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})
예제 #42
0
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)}
예제 #43
0
파일: scout.py 프로젝트: adamchainz/scout
    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)
예제 #44
0
파일: room.py 프로젝트: gfreezy/pushpin
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)
예제 #45
0
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)
예제 #46
0
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)
예제 #47
0
파일: views.py 프로젝트: keybits/permanote
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)
예제 #48
0
파일: collab.py 프로젝트: OSPK/collabdesk
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))
예제 #49
0
파일: collab.py 프로젝트: OSPK/collabdesk
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)
예제 #50
0
파일: blog_app.py 프로젝트: hangjoni/Geek
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')
예제 #51
0
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)
예제 #52
0
파일: collab.py 프로젝트: OSPK/collabdesk
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)
예제 #53
0
파일: collab.py 프로젝트: OSPK/collabdesk
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)
예제 #54
0
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)
예제 #55
0
	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
예제 #56
0
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()})
예제 #57
0
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)
예제 #58
0
파일: collab.py 프로젝트: OSPK/collabdesk
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)
예제 #59
0
파일: scout.py 프로젝트: adamchainz/scout
 def _get_attachment(self, document, pk):
     return get_object_or_404(
         document.attachments,
         Attachment.filename == pk)