コード例 #1
0
def delete(story_id):
    story = Story.get(id=story_id)

    if not story:
        abort(404)

    story.delete()
    db.commit()

    return '', 204
コード例 #2
0
    def parseArticlePage(self, response):
        """
        [5]
        Parse the article page and gather the story data
        Create and populate a Story object
        :param response: html string
        :param scan_record: ScanRecord object - just used to get the source_is into the Story object
        :return: Story object
        """
        story = Story()

        story.source_id = self.scan_record.source_id

        strainer = SoupStrainer(self.scan_record.article_page_container_type,
                                self.buildSoupAttrs('article_page_container'))

        soup = BeautifulSoup(response, 'html.parser', parse_only=strainer)

        self.log('\nParsing Article Page ---------------------------------------------------------------------', 'dev')
        self.log(soup.prettify(), 'debug')
        self.log(self.scan_record.article_page_container_type, 'dev')
        self.log(self.buildSoupAttrs('article_page_container'), 'dev')

        article_elements = [{'prop': 'title', 'container': 'article_title_container', 'tag': 'article_title'},
                            {'prop': 'author', 'container': 'article_author_container', 'tag': 'article_author'},
                            {'prop': 'body', 'container': 'article_body_container', 'tag': 'article_body'}]
        for element in article_elements:
            if getattr(self.scan_record, element['container'] + '_type') is not None:
                tag_container = soup.find(getattr(self.scan_record, element['container'] + '_type'),
                                          self.buildSoupAttrs(element['container']))
            else:
                tag_container = soup

            tag_data = self.getTagData(tag_container, element['tag'])
            setattr(story, element['prop'], tag_data)

        if story.body:
            story.body = story.body[:config.settings['limits']['snippet_char_limit']-3] + '...'

        self.log(story.__dict__, 'dev')
        story.snippet = story.body

        # Set a story to active only if we got good data. The story url is set late in the mediator master class
        if story.title and story.body:
            story.active = True
        else:
            story.active = False
        # Set author as a blank string to avoid db warning
        if story.author is None:
            story.author = ''

        return story
コード例 #3
0
def show(story_id):
    # This will serialize our data
    schema = StorySchema()
    # This gets a bread by ID
    story = Story.get(id=story_id)

    # If we can't find a story, send a 404 response
    if not story:
        abort(404)

    # otherwise, send back the story data as JSON
    return schema.dumps(story)
コード例 #4
0
def update(story_id):
    schema = StorySchema()
    story = Story.get(id=story_id)

    if not story:
        abort(404)

    try:
        data = schema.load(request.get_json())
        story.set(**data)
        db.commit()
    except ValidationError as err:
        return jsonify({
            'message': 'Validation failed',
            'errors': err.messages
        }), 422

    return schema.dumps(story)
コード例 #5
0
def create():
    # This will deserialize the JSON from insomnia
    schema = StorySchema()

    try:
        # attempt to convert the JSON into a dict
        data = schema.load(request.get_json())
        # Use that to create a story object
        data['user'] = g.current_user
        story = Story(**data)
        # store it in the database
        db.commit()
    except ValidationError as err:
        # if the validation fails, send back a 422 response
        return jsonify({
            'message': 'Validation failed',
            'errors': err.messages
        }), 422

    # otherwise, send back the story data as JSON
    return schema.dumps(story), 201
コード例 #6
0
db.drop_all_tables(with_all_data=True)
db.create_tables() # We create tables in our database


with db_session():
    schema = UserSchema()
    alikurtulus = User(
        username='******',
        email='*****@*****.**',
        password_hash=schema.generate_hash('sda')
    )

    Story(
     cityname='Lisbon',
     title='Lisbon was great holiday',
     user=alikurtulus,
     description="Lisbon is, in my opinion, one of the best cities to spend a weekend and a perfect place to experience one of Europe’s smaller capitals – but don’t let the word ‘smaller’ fool you! Lisbon packs a hefty punch with great places to see, eat and places to totally ‘let your hair down’…",
     date='12.08.2018',
     image='https://handluggageonly.co.uk/wp-content/uploads/2015/09/DSC02292.jpg'
    )
    Story(
     cityname='Madrid',
     title='Madrid was dream holiday',
     user=alikurtulus,
     description="Madrid is often overshadowed by its northerly neighbor Barcelona. There seems little reason for this, though—with delicious food, affordable living, and deluxe shopping, the capital of Spain deserves its own spotlight of fame! Discover what many locals already know and love about their city—plentiful rooftop bars, nonstop nightclubs, fantastic museum exhibitions, and luscious green parks. Check out all of my tips in the ultimate ",
     date='22.08.2018',
     image='http://d3ipks40p8ekbx.cloudfront.net/dam/jcr:664bc411-039d-4b90-9269-68deba1c2004/20170127_blog_MCT_Plaza%20Mayor-min.jpg'
    )
    Story(
     cityname='Barcelona',
     title='Barcelona was gaudi`s paradise.',
     user=alikurtulus,
コード例 #7
0
def random():
    schema = StorySchema(many=True)
    stories = schema.dump(
        Story.select())  # turns query object to list of dicts
    return jsonify(sample(stories,
                          3))  # chooses a random sample of those dicts
コード例 #8
0
def citystory():
    schema = StorySchema(many=True)
    cityname = request.args.get('cityname')

    stories = Story.select(lambda l: l.cityname == cityname)
    return schema.dumps(stories)
コード例 #9
0
def index():
    schema = StorySchema(many=True)
    stories = Story.select()
    return schema.dumps(stories)