def get(self, tag=None):
     if not tag:
         return jsonify(**{"error": "You have to specify tag!"})
     tags_avaiable = Tag.objects().distinct('name')
     if tag not in tags_avaiable:
         abort(404, message=f"Not found posts with {tag} tag")
     tag_obj = Tag.objects(name=tag).get()
     posts = Post.objects(tag=tag_obj)
     return PostSchema().dump(posts, many=True)
 def delete(self, id=None):
     if not id:
         abort(404, message="You have to specify id !")
     else:
         try:
             object = Tag.objects.get(id=id)
             TagSchema().dump(Tag.objects(id=id).delete())
         except:
             abort(404, message="id does not exist !")
         TagSchema().dump(Tag.objects(id=id).delete())
         return '', 204
Beispiel #3
0
    def full_render(self, handler, template_info, more_params):
        """Render a dynamic page from scatch."""
        logging.debug("Doing full render using template_file: %s", template_info['file'])
        url = handler.request.uri
        scheme, netloc, path, query, fragment = urlparse.urlsplit(url)

        global NUM_FULL_RENDERS
        if not path in NUM_FULL_RENDERS:
            NUM_FULL_RENDERS[path] = 0
        NUM_FULL_RENDERS[path] += 1     # This lets us see % of cached views
                                        # in /admin/timings (see timings.py)
        tags = Tag.list()
        years = Year.get_all_years()

        # Define some parameters it'd be nice to have in views by default.
        template_params = {
            "current_url": url,
            "bloog_version": config.BLOG['bloog_version'],
            "user": users.get_current_user(),
            "user_is_admin": users.is_current_user_admin(),
            "login_url": users.create_login_url(handler.request.uri),
            "logout_url": users.create_logout_url(handler.request.uri),
            "blog": config.BLOG,
            "blog_tags": tags,
            "archive_years": years,
        }
        template_params.update(config.PAGE)
        template_params.update(more_params)
        return template.render(template_info['file'], template_params,
                               debug=config.DEBUG, 
                               template_dirs=template_info['dirs'])
Beispiel #4
0
    def full_render(self, handler, template_info, more_params):
        """Render a dynamic page from scatch."""
        logging.debug("Doing full render using template_file: %s",
                      template_info['file'])
        url = handler.request.uri
        scheme, netloc, path, query, fragment = urlparse.urlsplit(url)

        global NUM_FULL_RENDERS
        if not path in NUM_FULL_RENDERS:
            NUM_FULL_RENDERS[path] = 0
        NUM_FULL_RENDERS[path] += 1  # This lets us see % of cached views
        # in /admin/timings (see timings.py)
        tags = Tag.list()

        # Define some parameters it'd be nice to have in views by default.
        template_params = {
            "current_url": url,
            "bloog_version": config.BLOG['bloog_version'],
            "user": users.get_current_user(),
            "user_is_admin": users.is_current_user_admin(),
            "login_url": users.create_login_url(handler.request.uri),
            "logout_url": users.create_logout_url(handler.request.uri),
            "blog": config.BLOG,
            "blog_tags": tags
        }
        template_params.update(config.PAGE)
        template_params.update(more_params)
        return template.render(template_info['file'],
                               template_params,
                               debug=config.DEBUG,
                               template_dirs=template_info['dirs'])
Beispiel #5
0
def get_tags(tags_string):
    logging.debug("get_tags: tag_string = %s", tags_string)
    if tags_string:
        from models.blog import Tag
        tags = Tag.list()
        logging.debug("  tags = %s", tags)
        return [process_tag(s, tags) 
                for s in tags_string.split(",") if s != '']
    return None
Beispiel #6
0
def get_tags(tags_string):
    logging.debug("get_tags: tag_string = %s", tags_string)
    if tags_string:
        from models.blog import Tag
        tags = Tag.list()
        logging.debug("  tags = %s", tags)
        return [
            process_tag(s, tags) for s in tags_string.split(",") if s != ''
        ]
    return None
Beispiel #7
0
 def get(self, category):
     category_cfg = config.PAGE['categories'][category]
     sort_attribute = self.request.get('sort', category_cfg['default_sort'])
     logging.debug("BlogEntriesHandler#get sorted by %s", sort_attribute)
     page = view.ViewPage()
     params = {'sort': sort_attribute,
               'category': category,
               'category_cfg': category_cfg}
     if sort_attribute != 'tag':
         page.render_query(
             self, 'blog_entries',
             db.Query(models.blog.Article). \
             filter('article_type =', 'blog entry'). \
             filter('category =', category). \
             order(sort_attribute), params=params,
             num_limit=150)
     else:
         # Set up to make a page where articles are grouped by tag
         all_blog_entries = db.Query(models.blog.Article). \
                  filter('article_type =', 'blog entry'). \
                  filter('category =', category). \
                  order('title').fetch(1000)
         from models.blog import Tag
         tags = [x['name'] for x in Tag.list()]
         tag_blog_entries = []
         other_blog_entries = [x for x in all_blog_entries if not x.tags]    # Glop all tags that have only one entry into one tag
         for tag in tags:
             blog_entries = [x for x in all_blog_entries if tag in x.tags]
             if len(blog_entries) == 1:
                 other_blog_entries.extend(blog_entries)
             elif len(blog_entries) > 1:
                 tag_blog_entries.append({'tag': tag, 'blog_entries': blog_entries})
         if other_blog_entries:
             # Make a dict based on blog entry key to get just unique entries
             other_blog_entries = dict((x.key(), x) for x in other_blog_entries)
             # Now turn it back into a list sorted by the blog entry title
             other_blog_entries = sorted(other_blog_entries.values(), key=lambda x: x.title)
             tag_blog_entries.append({'tag': 'Other', 'blog_entries': other_blog_entries})
         params.update({'tag_blog_entries': tag_blog_entries})
         page.render(self, params)
Beispiel #8
0
# from my_course_notes.Lesson_10_notes.models.workers import Person, Location
# print(sys.path)
import os, sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from models.blog import Author, Post, Tag

author_obj = Author(first_name="Aleksandr", last_name="Yaremenko").save()
tag_obj = Tag(name="OOP").save()
post_text = """
(ООП) — методология программирования, основанная на представлении
программы в виде совокупности объектов, каждый из которых является экземпляром
определённого класса, а классы образуют иерархию наследования.
"""
post_dict = {
    "title": "Основы ООП",
    "post": post_text,
    "view_count": 0,
    "author": author_obj,
    "tag": tag_obj,
}
Post(**post_dict).save()

post_text = """
Инкапсуляция — ограничение доступа к составляющим объект компонентам (методам и переменным).
Инкапсуляция делает некоторые из компонент доступными только внутри класса.
"""
post_dict = {
    "title": "Инкапсуляция",
    "post": post_text,
    "view_count": 0,
 def post(self):
     validity = TagSchema().validate(request.json)
     if validity:
         return validity
     obj = Tag(**request.json).save()
     return TagSchema().dump(obj)
 def put(self, id):
     obj = Tag.objects(id=id).get()
     obj.update(**request.json)
     return TagSchema().dump(obj.reload())
 def get(self, id=None):
     if not id:
         objects = Tag.objects()
         return TagSchema().dump(objects, many=True)
     obj = Tag.objects(id=id).get()
     return TagSchema().dump(Tag.objects(id=id).get())