示例#1
0
def post_list():
    model = Posts(get_db())
    posts = model.selectall()

    response = jsonify(posts)
    response.status_code = 200
    return response
示例#2
0
 def post(self):
     post_parser.add_argument('lat_lng',
                              location=['form', 'args'],
                              type=locationValidate)
     post_parser.add_argument('imagename', location='form', type=imageName)
     post_parser.add_argument('description',
                              location='form',
                              type=descriptionValidate)
     data = dict()
     args = post_parser.parse_args()
     try:
         device = args['token']['device']  # Object
         location = args['lat_lng']['data']  # Dict
         lat_lng = args['lat_lng']['lat_lng']
         lat = lat_lng.split(',')[0].strip()
         lng = lat_lng.split(',')[1].strip()
         postParams = dict()
         postParams['user_id'] = device.user_id
         postParams['description'] = args['description']
         postParams['image_name'] = args['imagename']
         postParams['lat'] = lat
         postParams['lng'] = lng
         postParams['location_id'] = location['id'] if location else 0
         postModel = PostsModel()
         newPost = postModel.addPost(postParams)
         return marshal(newPost, post_fields), 200
     except Exception, e:
         data['message'] = str(e)
         return data, e.code if hasattr(e, 'code') else 500
示例#3
0
def post_get(id):
    model = Posts(get_db())
    posts = model.selectmessage(id)

    response = jsonify(posts)
    response.status_code = 200
    return response
示例#4
0
def post_create():
    postdata = request.get_json(silent=True)

    model = Posts(get_db())
    newpost = model.insert(user=postdata['user'], message=postdata['message'])

    response = jsonify(newpost)
    response.status_code = 201  #Created!
    return response
示例#5
0
    def new_post(self,
                 post_title,
                 post_content,
                 date=datetime.datetime.utcnow()):
        post = Posts(blog_id=self._id,
                     title=post_title,
                     content=post_content,
                     author=self.author,
                     date=date)

        post.save_to_db()  #saving to the database
示例#6
0
def post_tweet():
    form = Post_form()
    if form.validate_on_submit():
        if request.method == "POST":
            content = form.post_area.data
            # sending info to db
            time_post_var = time_post()
            post = Posts(user_id=current_user.id,
                         post=content,
                         date_posted=time_post_var)
            post.create()
            print("post posted")
            return redirect(url_for('timeline'))
示例#7
0
 def new_post(self):
     title = input("Enter post title: ")
     content = input("Enter new content: ")
     date = input("Enter post date or leave black for today(In format DDMMYYYY):")
     if date == "":
         date = datetime.datetime.utcnow()
     else:
         date=datetime.datetime.strptime(date,'%d%m%y')
     post= Posts(blog_id= self.id,
                 title=title,
                 content=content,
                 date= date,
                 author= self.author
     )
     post.save_to_mongo()
示例#8
0
def get_data(db: Connection, url: str):
    """
    Получение данных из парсинга сайта

    :param
        * *db* (``Connection``) -- соединение к БД
    :param
        * *url* (``str``) -- url сайта для парсинга

    :rtype (``None``)
    :return:
    """
    query = db.session.query(Posts).order_by(Posts.id.desc()).limit(30)
    titles = tuple(x.title for x in query)

    response = requests.get(url, headers={'Connection': 'close'})
    soup = BeautifulSoup(response.text, "html.parser")

    data = soup.find_all('tr', class_='athing')
    for el in data:
        soup_content = el.find('a', class_='storylink')
        if soup_content.text not in titles:
            content = Posts(**{
                'title': soup_content.text,
                'url': soup_content.get('href'),
                'created': datetime.datetime.now().isoformat(),
            })
            to_database(db, content)

    db.session.commit()
示例#9
0
 def delete(self, post_id):
     args = post_parser.parse_args()
     device = args['token']['device']  # Object
     user_id = device.user_id
     try:
         postModel = PostsModel()
         postDeleted = postModel.deletePost(post_id, user_id)
         if postDeleted:
             return {'message': 'Deleted successfully!'}, 200
         else:
             return {
                 'message': 'The post can not be deleted!'
             }, 403  # unauthorized
     except:
         data['message'] = str(e)
         return data, e.code if hasattr(e, 'code') else 500
示例#10
0
def get_all_posts():

    with sqlite3.connect("rare.db") as conn:

        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute("""
        SELECT
            p.id,
            p.user_id,
            p.date,
            p.title,
            p.content,
            p.category_id
        FROM posts p
        ORDER BY date DESC
        """)

        posts = []

        dataset = db_cursor.fetchall()

        for row in dataset:
            post = Posts(row['id'], row['user_id'], row['date'], row['title'],
                         row['content'], row['category_id'])

            posts.append(post.__dict__)

    return json.dumps(posts)
示例#11
0
def get_posts_by_category(category_id):
    with sqlite3.connect("./rare.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute(
            """
        SELECT
            a.id,
            a.user_id,
            a.date,
            a.title,
            a.content,
            a.category_id
        FROM posts a
        WHERE a.category_id = ?
        """, (category_id, ))

        posts = []

        dataset = db_cursor.fetchall()
        for row in dataset:

            post = Posts(row['id'], row['user_id'], row['date'], row['title'],
                         row['content'], row['category_id'])
            posts.append(post.__dict__)

    return json.dumps(posts)
示例#12
0
 def put(self, post_id):
     post_parser.add_argument('description',
                              location='form',
                              type=descriptionValidate)
     args = post_parser.parse_args()
     device = args['token']['device']  # Object
     user_id = device.user_id
     try:
         postModel = PostsModel()
         postUpdated = postModel.updatePost(post_id, user_id, args)
         if postUpdated:
             return {'message': 'Updated successfully!'}, 200
         else:
             return {'message': 'The post can not be updated!'}, 403
     except:
         data['message'] = str(e)
         return data, e.code if hasattr(e, 'code') else 500
示例#13
0
    def get(self):
        post_parser.add_argument('lat_lng',
                                 location=['form', 'args'],
                                 type=locationValidate)
        post_parser.add_argument('not_ids', location='args', default='0')
        post_parser.add_argument('limits', location='args', default='10')
        post_parser.add_argument('timestamp',
                                 location='args',
                                 type=validateTimeStamp)

        # When the value of when is before, it'll show posts happened before the timestamp
        # This is on infinite scroll
        # When the value of when is after, it'll show posts happened after the timestamp. i.e. New posts
        # This is on pull to refresh
        post_parser.add_argument('when',
                                 location='args',
                                 default='before',
                                 type=validateWhen)
        #post_parser.add_argument('feed_type', location='args', default='nearby')

        list_post = dict()
        list_post['posts'] = fields.List(fields.Nested(post_fields))

        args = post_parser.parse_args()
        #try:
        device = args['token']['device']  # Object
        location = args['lat_lng']['data']  # Dict
        lat_lng = args['lat_lng']['lat_lng']
        lat = lat_lng.split(',')[0].strip()
        lng = lat_lng.split(',')[1].strip()
        getParams = dict()
        getParams['lat'] = lat
        getParams['lng'] = lng
        getParams['location_id'] = location['id']
        getParams['user_id'] = device.user_id
        getParams[
            'not_ids'] = '0' if args['not_ids'] == '' else args['not_ids']
        getParams['limits'] = args['limits']
        getParams['timestamp'] = args['timestamp']
        getParams['when'] = args['when']

        postModel = PostsModel()
        posts = postModel.getNearby(getParams)
        return marshal({'posts': posts}, list_post), 200
示例#14
0
def get_single_post(id):
    with sqlite3.connect("./rare.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute(
            """
        SELECT
            a.id,
            a.user_id,
            a.date,
            a.title,
            a.content,
            a.category_id
        FROM posts a
        WHERE a.id = ?
        """, (id, ))

        data = db_cursor.fetchone()
        post = Posts(data['id'], data['user_id'], data['date'], data['title'],
                     data['content'], data['category_id'])

        return json.dumps(post.__dict__)
示例#15
0
########### IMPORTS ########################
from models.posts import Posts
from common.database import Database

############################################

database = Database.initialize()

post2 = Posts(
    "Vaibhav",
    "B02",
    "Vaibhav's Blog Title",
    "Vaibhav's Blog Content",
)

posts = Posts.get_posts_from_blog('B02')

print(posts)

print('success')
示例#16
0
def post_delete(id):
    model = Posts(get_db())
    model.delete(id)
    response = jsonify({"status": "deletado"})
    response.status_code = 204
    return response
示例#17
0
    def process_item(self, item, spider):
        if isinstance(item, PostItem):
            db_item = Posts()
            author = self.AuthorService.get_author_by_name(item['author_id'][0])
            db_item.author_id = author.id
            db_item.category = ''.join(item['category']).strip().replace("Kategoria: ", '')
            db_item.content = ''.join(item['content']).strip().replace('/n', '')
            db_item.date = item['date']
            db_item.link = item['link']
            db_item.title = ''.join(item['title']).strip()
            db_item.comments = self.process_comments(item['comments'])
            db_item.tags = self.process_tags(item['tags'])
            urls = ";".join([url for url in item['urls'] if "salon24.pl" in url]).strip()
            db_item.urls = urls if urls and urls is not "''" else None
        if isinstance(item, AuthorItem):
            db_item = Authors(**item)
            db_item.name = ''.join(db_item.name).strip().replace('"', '').upper()

        try:
            self.session.add(db_item)
            self.session.commit()
        except:
            self.session.rollback()
            raise
        finally:
            self.session.close()

        return item
示例#18
0
 def get_posts(self):
     return Posts.get_posts_from_blog(self._id)
示例#19
0
 def get_post(self):
     return Posts.from_blog(self.id)