예제 #1
0
    def create(request: HttpRequest, course_id: int) -> HttpResponse:
        """Create a new post."""
        course = Course.objects.get(id=course_id)
        payload = loads(request.body)

        # create post with required fields
        new_post = Post(
            title=payload["title"],
            content=payload["content"],
            author=request.user,
            course=course,
        )
        new_post.save()

        # handle optional fields
        if payload.get("parent", False):
            parent_post = Post.objects.get(id=payload["parent"])
            new_post.parent = parent_post
        if payload.get("tags", False):
            tags = Tag.objects.filter(id__in=payload["tags"])
            new_post.tags.add(*tags)
        if payload.get("type", False):
            new_post.type = payload["type"]
        if payload.get("visibility", False):
            new_post.visibility = payload["visibility"]
        new_post.anonymous = payload.get("anonymous", False)

        # automatically add author as a follower
        new_post.followers.add(request.user)

        new_post.save()
        return HttpResponse(dumps(PostService.post_to_dict(new_post)))
예제 #2
0
파일: tests.py 프로젝트: RodericDay/forum
    def test_post_detail_context_info(self):
        topic = Topic.objects.create()
        Post.objects.bulk_create([Post(text=i, topic_id=1) for i in range(20)])
        Post.objects.bulk_create([Post(text=i, topic_id=2) for i in range(20)])

        with self.assertNumQueries(6):
            response = self.client.get("/api/topics/2/posts/28/")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data["context"]["index"], 7)
        self.assertEqual(response.data["context"]["page"], 2)
예제 #3
0
파일: rss.py 프로젝트: spi4kavg/exante
def rss_parser():
    try:
        content = urllib2.urlopen("https://lenta.ru/rss").read()
    except urllib2.HTTPError:
        return False

    tree = etree.fromstring(content)
    items = tree.xpath("//item")

    for item in items:
        try:
            category = item.xpath('category/text()')[0]
            guid = item.xpath('guid/text()')[0]
            title = item.xpath('title/text()')[0]
            link = item.xpath('link/text()')[0]
            description = item.xpath('description/text()')[0]
            pub_date = parser.parse(item.xpath('pubDate/text()')[0])
        except IndexError:
            continue

        category, created = Category.objects.get_or_create(name=category)

        try:
            post = Post.objects.get(guid=guid)
        except Post.DoesNotExist:
            post = Post(guid=guid)

        post.category = category
        post.title = title
        post.link = link
        post.description = description
        post.pub_date = pub_date
        post.save()
    return True
예제 #4
0
def create_post(id):
    data = request.get_json() or {}
    if 'image' not in data:
        return make_response(400, 'must include image field')
    data['user_id'] = id
    post = Post()
    post.from_dict(data)
    db.session.add(post)
    db.session.commit()
    response = jsonify(post.to_dict())
    response.status_code = 201
    return response
예제 #5
0
def create_post():
    title = request.json.get('title', None)
    text = request.json.get('text', None)
    media = request.json.get('media', None)

    new_post = Post(title=title, text=text, media=media)
    if new_post:
        new_post.create()
        return jsonify(new_post.to_dict()), 201

    else:
        return {'error': 'Something went wrong'}, 409
예제 #6
0
 def post(self):
     data = parser.parse_args()
     current_user = get_jwt_identity()
     new_post = Post(author=str(current_user['user_id']),
                     likes=0,
                     body=data['body'],
                     author_username=current_user['username'],
                     title=data['title'])
     try:
         new_post.save_to_db()
         return {'message': 'Post created'}
     except Exception as e:
         return {'message': 'Something went wrong' + str(e)}, 500
예제 #7
0
파일: rss.py 프로젝트: spi4kavg/exante
def rss_parser():
    try:
        content = urllib2.urlopen("https://lenta.ru/rss").read()
    except urllib2.HTTPError:
        return False

    tree = etree.fromstring(content)
    items = tree.xpath("//item")

    for item in items:
        try:
            category = item.xpath('category/text()')[0]
            guid = item.xpath('guid/text()')[0]
            title = item.xpath('title/text()')[0]
            link = item.xpath('link/text()')[0]
            description = item.xpath('description/text()')[0]
            pub_date = parser.parse(item.xpath('pubDate/text()')[0])
        except IndexError:
            continue

        category, created = Category.objects.get_or_create(name=category)

        try:
            post = Post.objects.get(guid=guid)
        except Post.DoesNotExist:
            post = Post(guid=guid)

        post.category = category
        post.title = title
        post.link = link
        post.description = description
        post.pub_date = pub_date
        post.save()
    return True
예제 #8
0
def write_post_db(data):
    post = Post(source_name=data['source_name'],
                author=data['author'],
                title=data['title'],
                url=data['url'],
                img_url=data['img_url'],
                published_at=data['published_at'],
                description=data['description'])
    # check if we have already this post
    if (not Post.objects.filter(title__icontains=data['title'])) or \
            (not Post.objects.filter(url__icontains=data['url'])):
        post.save()
    else:
        print('It\'s OK! We have already this info!')
예제 #9
0
    def post(self):
        data = parser.parse_args()
        if data['value'] > 1 or data['value'] < -1:
            return {'error': 'value must be in range from 1 to -1'}

        user_id = str(get_jwt_identity()['user_id'])
        LikeToPost.delete_like(user_id=user_id, post_id=data['post_id'])

        new_like = LikeToPost(value=data['value'], user_id=user_id, post_id=data['post_id'])
        try:
            new_like.save_to_db()
            Post.put_like(post_id=data['post_id'], value=data['value'])
            return {'message': 'You liked post with {}'.format(data['post_id'])}
        except Exception as e:
            return {'message': 'Something went wrong' + str(e)}, 500
예제 #10
0
def new_post():
	token = request.json.get('token')
	if not token:
		return jsonify(error="Missing token")

	user = auth_user(token)
	if not user:
		return jsonify(error="Invalid token")

	title = request.json.get('title')
	melody_data = request.json.get('melody_data')
	if title == None or melody_data == None:
		return jsonify(error="Missing title/melody_data")

	post = Post(title=title, melody_data=melody_data, author=user)
	db.session.add(post)
	db.session.commit()

	return jsonify(post={
		"id":post.id,
		"title":post.title,
		"melody_data":post.melody_data,
		"author":post.author.name,
		"date":post.date_posted.strftime('%m-%d-%Y'),
	})
예제 #11
0
파일: tests.py 프로젝트: RodericDay/forum
    def test_no_np1q_on_post_list(self):
        Post.objects.bulk_create(
            [Post(text=str(i), topic_id=1) for i in range(5)])

        with self.assertNumQueries(12):
            response = self.client.get("/api/topics/1/posts/")
        self.assertEqual(response.data["count"], 6)
예제 #12
0
def add_measurement(request):
    temp = request.POST.get('temperature', None)
    hum = request.POST.get('humidity', None)
    mac = request.POST.get('mac', None)
    if mac is None:
        return Response()

    sensors = Sensor.objects.filter(mac_addr=mac)
    if sensors.count() == 0:
        sensor = Sensor(mac_addr=mac, name=mac)
        sensor.save()
    else:
        sensor = sensors[0]
    post = Post(temperature=temp, humidity=hum, sensor=sensor)
    post.save()
    return Response(sensor.interval)
예제 #13
0
    def partial_update(self, request, pk=None):
        try:
            # tokenの確認
            authorization = self.check_authorization()
            if authorization:
                # tokenがなかったり違っていたらJSONレスポンスを返す
                return authorization

            # JSONのデータ読み込み
            data = json.loads(request.body)

            # テキストの代入
            body = data['body']
            # statusの代入
            status = data['status']
            # pkはpostのid
            body_id = pk
        except:
            # JSONの読み込みに失敗 keyエラーで失敗
            return JsonResponse({'message': 'Post data injustice'}, status=400)

        # 文字数が140字以内の判定
        if len(body) > 140:
            return JsonResponse({'message': 'Must be 140 characters or less'},
                                status=403)

        # 投稿の修正(データベースに更新)
        post = Post.update(body, status, body_id)

        # 結果をdictに保存しJSONレスポンスで返す
        result = {'id': post.id, 'body': post.body, 'post': post.status}
        return JsonResponse(result, status=200)
예제 #14
0
    def create(self, request):
        try:
            # tokenの確認
            authorization = self.check_authorization()
            if authorization:
                # tokenがなかったり違っていたらJSONレスポンスを返す
                return authorization

            # JSONのデータの読み込み
            data = json.loads(request.body)

            # テキストの代入
            body = data['body']
            # statusの代入
            status = data['status']
        except:
            # JSONの読み込みに失敗 keyエラーでも失敗
            return JsonResponse({'message': 'Post data injustice'}, status=400)

        # 文字数が140字以内の判定
        if len(body) > 140:
            return JsonResponse({'message': 'Must be 140 characters or less'},
                                status=403)

        # 投稿(データベースに保存)
        post = Post.create(body, status, self.token.user_id)

        # 結果をdictに保存しJSONレスポンスで返す
        result = {
            'id': post.id,
            'body': post.body,
            'status': post.status,
        }
        return JsonResponse(result, status=201)
예제 #15
0
def addNewPost():

    # Obtener el ID del usuario registrado get_jwt_identity
    current_user_id = get_jwt_identity()
    user = User.query.get(current_user_id)

    # Se reporta un error si no esta registrado
    if user is None:
        raise APIException('No se ha iniciado sesión', status_code=400)

    #Obtener el request body
    request_body = request.get_json()
    # Validate the data
    if (request_body["title"] is None or request_body["comment"] is None or request_body["url"] is None or request_body["provincia"] is None \
        or request_body["dificultad"] is None or request_body["duracion"] is None):
        raise APIException('Request Body inválido. Uno o más parámetros están vacíos', status_code=400)

    #Crear Nuevo Post
    createdDate = datetime.datetime.now()
    createdDate = createdDate.strftime("%d/%m/%Y %H:%M:%S")
    updatedDate = datetime.datetime.now()
    updatedDate = updatedDate.strftime("%d/%m/%Y %H:%M:%S")
    total_comment = 35
    total_like = 35
    newPost = Post(created = createdDate, updated = updatedDate, title = request_body["title"], comment = request_body["comment"],\
        url = request_body["url"], provincia = request_body["provincia"], dificultad = request_body["dificultad"], duracion = request_body["duracion"],\
        total_comment = total_comment, total_like = total_like, iduser = user.id)

    db.session.add(newPost)
    db.session.commit()  

    tmpObj = newPost.serialize()

    #Obtener Post Guardado 

    # Guardar puntuacion inicial
    createdDate = datetime.datetime.now()
    createdDate = createdDate.strftime("%d/%m/%Y %H:%M:%S")
    updatedDate = datetime.datetime.now()
    updatedDate = updatedDate.strftime("%d/%m/%Y %H:%M:%S")
    newPostLike = Post_like(created = createdDate, updated = updatedDate, puntuacion = 35, idpost = tmpObj["id"],\
        iduser = user.id)

    db.session.add(newPostLike)
    db.session.commit()   

    return jsonify('Nuevo Post publicado'), 200
예제 #16
0
def get_all_posts():

    posts = Post.get_all()
    print(posts)
    if posts:
        posts_dict = [post.to_dict() for post in posts]
        return jsonify(posts_dict), 200

    return jsonify({'error': "Posts not found"}), 404
예제 #17
0
def addPost():

    content = request.json.get("content")
    user_id = request.json.get("user_id")
    user = User.query.get(user_id)

    if not content:
        return jsonify({"msg": "Content required"}), 400

    post = Post()
    post.content = content
    post.user_id = user_id
    db.session.add(post)
    db.session.commit()

    data = {"user": user.username, "success": "Added", "post_id": post.id}

    return jsonify(data), 200
예제 #18
0
def create_cultivo():
   
    body = request.get_json() # get the request body content

    if body is None:
        return jsonify({'msg':"El body está vacio", 'status':'failed'}), 400
    if 'nombre' not in body:
        return jsonify({'msg':'Necesita especificar un nombre', 'status':'failed'}),400
    if 'epoca_siembra' not in body:
        return jsonify({'msg':'Necesita especificar epoca_siembra ', 'status':'failed'}), 400
    if 'clima' not in body:
        return jsonify({'msg':'Necesita especificar clima', 'status':'failed'}), 400
    if 'cosecha' not in body:
        return jsonify({'msg':'Necesita especificar cosecha', 'status':'failed'}), 400
    if 'tipo_de_suelo' not in body:
        return jsonify({'msg':'Necesita especificar tipo_de_suelo', 'status':'failed'}), 400
    if 'preparacion_del_suelo' not in body:
        return jsonify({'msg':'Necesita especificar preparacion_del_suelo', 'status':'failed'}), 400
    if 'plagas' not in body:
        return jsonify({'msg':'Necesita especificar plagas', 'status':'failed'}), 400
    if 'descripcion' not in body:
        return jsonify({'msg':'Necesita especificar descripción', 'status':'failed'}), 400

    body_nombre = body['nombre']
    cultivo = Post.query.filter_by(name= body_nombre).first()

    if cultivo:
        return jsonify({'msg':'El cultivo ya existe', 'status':'failed'}), 200
        
    post = Post()
    post.nombre = body['nombre']  
    post.epoca_siembra = body['epoca_siembra'] 
    post.cosecha = body['cosecha'] 
    post.clima = body['clima'] 
    post.tipo_de_suelo = body['tipo_de_suelo'] 
    post.preparacion_del_suelo = body['preparacion_del_suelo'] 
    post.plagas = body['plagas']
   
    # agrega user a la base de datos
    db.session.add(post)
    # guarda los cambios
    db.session.commit()

    response_body = {
        "msg": "Cultivo creado",
        "status":"succesful"
    }

    return jsonify(response_body), 200
예제 #19
0
파일: views.py 프로젝트: UmmuRasul/sbvbn
def api_create_post_view(request):
    account = Account.objects.get(pk=1)
    post = Post(author=account)

    if request.method == 'Post':
        serializers = PostSerializer(post, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #20
0
 def getting_all_comments_succeeds(self, client, init_db):
     post_id = Post(**self.post_data).save().id
     comment_data = {'body': 'test_comment', 'post_id': post_id}
     # save three comments
     for i in range(3):
         Comment(**comment_data).save()
     res = client.get('/api/comments')
     assert res.status_code == 200
     payload = json.loads(res.data)
     assert len(payload['data']) == 3
예제 #21
0
    def post(self, request, format=None):
        # Check if user is authed or not
        username_data = get_username_from_jwt(request)
        if username_data['username'] != False:
            # Parse and create post
            data = JSONParser().parse(request)
            data['created_at'] = created_at = timezone.now()
            serializer = PostSerializer(data=data)

            if serializer.is_valid():
                user = User.objects.get(username=username_data['username'])
                post = Post(title=serializer.data['title'],
                            description=serializer.data['description'],
                            user=user,
                            created_at=serializer.data['created_at'])
                post.save()
                return JsonResponse(serializer.data, status=201)
            return JsonResponse(serializer.errors, status=400)
        return JsonResponse({'msg': username_data['error_msg']}, status=400)
예제 #22
0
def publish_service():

    current_user_email = get_jwt_identity()
    user = User.query.filter_by(email=current_user_email).first()

    request_body_data = request.data
    decoded_publication = json.loads(request_body_data)

    print(user.id, decoded_publication)

    return jsonify(Post.newService(decoded_publication, user.id)), 200
예제 #23
0
 def creating_comment_succeeds(self, client, init_db):
     post_id = Post(**self.post_data).save().id
     comment_data = {
         'body': 'this is a test comment',
         'post_id': post_id
     }
     res = client.post('/api/comments', data=json.dumps(comment_data))
     assert res.status_code == 201
     payload = json.loads(res.data)
     assert payload['data']['body'] == comment_data['body']
     assert payload['data']['post']['id'] == post_id
예제 #24
0
def create_post_resolver(obj, info, title, description):
    try:
        today = date.today()
        post = Post(title=title,
                    description=description,
                    created_at=today.strftime("%b-%d-%Y"))
        db.session.add(post)
        db.session.commit()
        payload = {"success": True, "post": post.to_dict()}
    except ValueError:  # date format errors
        payload = {
            "success":
            False,
            "errors": [
                f"Incorrect date format provided. Date should be in "
                f"the format dd-mm-yyyy"
            ]
        }

    return payload
예제 #25
0
def post(request):

    #body_unicode = request.body.decode('utf-8')
    #body = json.loads(body_unicode)
    posted = Post()
    form = PostForm(request.POST, instance=posted)
    #form.user = body["user"]
    #form.content = body["content"]
    #form.title = body["title"]
    if form.is_valid():
        form.save()
        return JsonResponse({"is_succeed": True})
    else:
        return HttpResponse(status=500)
예제 #26
0
def create_post(request):
    form = PostForm({'author': request.user.id})

    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)

        title = request.POST['title']
        details = request.POST['details']
        viewers = request.POST['viewers']

        if form.is_valid():
            post = Post(author=request.user,
                        type='Blog',
                        title=title,
                        details=details,
                        viewers=viewers)

            try:
                post.save()
                ''' upload the files '''
                files = request.FILES.getlist('files')
                if files is not None:
                    for file in files:
                        attachment = Attachment(file=file,
                                                post=post,
                                                content_type=file.content_type)
                        attachment.save()

                return HttpResponseRedirect(reverse('thanks'))
            except ():
                pass

    return render(request, 'posts/create.html',
                  {'model': {
                      'form': form,
                      'action': 'create-post'
                  }})
예제 #27
0
파일: tests.py 프로젝트: RodericDay/forum
    def test_record_cycle(self):
        Post.objects.bulk_create(
            [Post(text=str(i), topic_id=1) for i in range(5)])

        record = Record.objects.create(topic_id=1, user_id=2)
        self.assertEqual(record.count, 0)

        self.client.get("/api/topics/1/posts/?page=1")
        record.refresh_from_db()
        self.assertEqual(record.count, 5)

        self.client.get("/api/topics/1/posts/?page=2")
        record.refresh_from_db()
        self.assertEqual(record.count, 6)

        self.client.get("/api/topics/1/posts/?page=1")
        record.refresh_from_db()
        self.assertEqual(record.count, 6)
예제 #28
0
def create_post(current_user):
    # Get data from request
    data = request.get_json()
    # Check the length if the caption (caption is limited to 100 chars)
    if len(data['caption']) <= 100:
        post_image = save_image(url=data['image_file'])
        # Create post object
        post = Post(caption=data['caption'],
                    image_file=post_image,
                    user_id=current_user.id)
        # Add to database
        db.session.add(post)
        db.session.commit()

        # Return feedbacks
        return jsonify({'message': 'Post created!'})
    else:
        return jsonify({'message': 'Caption is limited to 100 chars'})
예제 #29
0
    def destroy(self, request, pk=None):
        # tokenの確認
        authorization = self.check_authorization()
        if authorization:
            # tokenがなかったり違っていたらJSONレスポンスを返す
            return authorization

        # pk(postのid)を代入
        body_id = pk

        # 投稿の削除(論理削除)
        post = Post.delete(body_id)

        # 結果をdictに保存しJSONレスポンスで返す
        result = {
            'id': post.id,
            'body': post.body,
            'is_deleted': post.is_deleted,
        }
        return JsonResponse(result)
예제 #30
0
    def list(self, request):
        # tokenの確認
        authorization = self.check_authorization()
        if authorization:
            # tokenがなかったり違っていたらJSONレスポンスを返す
            return authorization

        # 投稿のされている情報の取得(自分以外, 時系列順)
        post_lists = Post.list(self.token.user_id)

        # 取得したlistを1件づつ空のresultに保存し配列で返す
        result = []
        for post_list in post_lists:
            params = {
                'id': post_list.id,
                'body': post_list.body,
                'created_at': post_list.created_at
            }
            result.append(params)

        # safeをFalseにすることで配列を返せるようにしている
        return JsonResponse(result, safe=False, status=200)
예제 #31
0
 def filter(self, validated_data):
     com_list = ([x.comments for x in Post.objects(__raw__={'sid': validated_data.get('sid')})])
     return com_list