示例#1
0
文件: views.py 项目: chenjunqian/here
def getCurrentPost(request):
	dict = {}
	resultData = {}
	if request.method == 'GET':
		time = request.GET.get('time')
		index = request.POST.get('index')
		targetTime = int(time) - 60*60*1000
		targetIndex = int(index)


		posts = Post.objects.filter(
			created__gte=targetTime,
		).order_by['-id'][targetIndex-20:targetIndex]

		# 如果最近一小时没有帖子,则选取最近时间的数据
		if  posts:
    		serializer = PostSerializer(posts)
			return Response(serializer.data, status=status.HTTP_200_OK)
		else:
    		posts = Post.objects.all().order_by['-id'][targetIndex-20:targetIndex]
			if posts:
        		serializer = PostSerializer(posts)
				return Response(serializer.data, status=status.HTTP_200_OK)
			else:
        		errors = { 
					'error_code': '8003',
					'error': 'POST_FAILED',
					'message': 'post_not_found',
				}
				return Response(errors,status=status.HTTP_404_NOT_FOUND)
示例#2
0
def get_post(post_id):
    post = Post.query.get(post_id);
    if (post == None):
        abort(404);
    schema = PostSerializer();
    data, errors = schema.dump(post);
    return jsonify({'post':make_public_post(data)});
示例#3
0
文件: views.py 项目: chenjunqian/here
def updateUserPostLocation(request):
    	
	if request.method == 'POST':
    	longitude = request.POST.get('longitude')
    	latitude = request.POST.get('latitude')
    	city = request.POST.get('city')
    	cityCode = request.POST.get('cityCode')
    	address = request.POST.get('address')
    	username = request.POST.get('username')
    	tag = request.POST.get('username')
		try:

			post = Post(
				longitude=longitude,
				latitude=latitude,
				city=city,
				cityCode=cityCode,
				address=address,
				username=username,
				tag=tag,

			)
			post.save()
			serializer = PostSerializer(post)
    		redis = get_redis_connection()
			json_serializer = JSONRenderer().render(serializer.data)
			redis.hmset('Post',post.id, json_serializer)
    		serializer.save()
			return Response(serializer.data, status=status.HTTP_201_CREATED)
示例#4
0
 def put(self, request, pk):
     post = self.get_object(pk)
     serializer = PostSerializer(post, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=201)
     return Response(serializer.errors, status=400)
示例#5
0
文件: views.py 项目: porowns/pBoards
 def put(self, request, pk, format=None):
     post = self.get_object(pk)
     serializer = PostSerializer(post, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例#6
0
 def post(self, request, format=None):
     user = request.user
     serializer = PostSerializer(data=request.data, context={'user': user})
     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)
示例#7
0
def all_posts(request):
    """ Retorna um json com todos os post cadastrados """

    response = {
        "status": "failure",
    }

    if request.method == 'GET':
        posts = Post.objects.all()
        serializer = PostSerializer(posts, many=True)
        response = {
            "status": "success",
            "shows": serializer.data,
        }
        return Response(response)

    elif request.method == 'POST':
        serializer = PostSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            response = {
                "status": "success",
                "shows": serializer.data,
            }
            return Response(response, status=status.HTTP_201_CREATED)
        response = {
            "status": "failure",
            "errors": serializer.errors,
        }
        return Response(response, status=status.HTTP_400_BAD_REQUEST)

    return Response(response)
示例#8
0
 def post(self,request, format=None):
     user=request.user
     serializer = PostSerializer(data=request.data, context={'user':user})
     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)
示例#9
0
def create_post():
    # 400: bad request
    if not request.json or not 'title' in request.json or not 'body' in request.json:
        abort(400);
    post = Post(request.json['title'], request.json['body']);
    db.session.add(post);
    db.session.commit();
    # 查询并返回。
    post = Post.query.get(post.id);
    schema = PostSerializer();
    data, errors = schema.dump(post);
    return jsonify({'post': make_public_post(data)}), 201;
示例#10
0
 def put(self, request, pk, format=None):
     try:
         post = Post.objects.get(pk=pk)
         if post.created_by == request.user:
             post_serializer = PostSerializer(post, data=request.data)
             if post_serializer.is_valid():
                 post_serializer.save()
                 return Response(post_serializer.data)
             else:
                 return Response(status.HTTP_400_BAD_REQUEST)
         else:
             return Response(status.HTTP_405_METHOD_NOT_ALLOWED)
     except Post.DoesNotExist:
         return Response(status.HTTP_404_NOT_FOUND)
示例#11
0
    def post(self, request):
       
        user = request.user
        post_id = request.data["post_id"]
        title = request.data["title"]
        body = request.data["body"]
        category_id = request.data["category_id"]
        link = request.data["link"]

        try:

            category = Category.objects.get(id=int(category_id))
            post = Post.objects.get(id=int(post_id))
            post.category=category
            post.title=title
            post.body=body
            post.link=link
            post.save()
            posts = Post.objects.filter(author=user)
            serializer = PostSerializer(posts,many=True)
            return serializer.data

        except Exception,R:
            log = Logger(log=str(R))
            log.save()
            return {'message':'error  '+str(R)}
示例#12
0
 def post(self, request, pk, format=None):
     serializer = PostSerializer(data=request.data)
     if serializer.is_valid():
         serializer.validated_data['created_by'] = request.user
         serializer.validated_data['category'] = Category.objects.get(pk=pk)
         serializer.validated_data['date_created'] = timezone.now()
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例#13
0
 def post(self):
     form = PostCreateForm()
     if not form.validate_on_submit():
         return form.errors, 422
     post = Post(form.title.data,form.img.data, form.body.data,form.tag.data)
     db.session.add(post)
     db.session.commit()
     return PostSerializer(post).data, 201
示例#14
0
def all_posts(request):
    """ Retorna um json com todos os post cadastrados """

    response = {
        "status": "failure",
    }

    if request.method == 'GET':
        posts = Post.objects.all()
        serializer = PostSerializer(posts, many=True)
        response = {
            "status": "success",
            "shows": serializer.data,
        }
        return Response(response)

    elif request.method == 'POST':
        serializer = PostSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            response = {
                "status": "success",
                "shows": serializer.data,
            }
            return Response(response, status=status.HTTP_201_CREATED)
        response = {
            "status": "failure",
            "errors": serializer.errors,
        }
        return Response(response, status=status.HTTP_400_BAD_REQUEST)

    return Response(response)
示例#15
0
def update_post(post_id):
    post = Post.query.get(post_id);
    if post == None:
        abort(404);
    if not request.json:
        abort(404);
    if 'title' in request.json and type(request.json['title']) != str:
        abort(400);
    if 'body' in request.json and type(request.json['body']) != str:
        abort(400);
    post.title = request.json.get('title');
    post.body = request.json.get('body');
    db.session.commit();

    # 查询并返回。
    post = Post.query.get(post.id);
    schema = PostSerializer();
    data, errors = schema.dump(post);
    return jsonify({'post': make_public_post(data)});
示例#16
0
    def get(self, request):

        user = request.user

        try:

            posts = Post.objects.filter(author=user)
            serializer = PostSerializer(posts,many=True)
            return serializer.data

        except Exception,R:
            return {'message':'error '+str(R)}
示例#17
0
def get_post(request, pk):
    """ Realiza as operações de select, update e delete no post dono da pk """

    try:
        post = Post.objects.get(pk=pk)
    except Post.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = PostSerializer(post)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = PostSerializer(post, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        post.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
示例#18
0
def api_token(request):
    """
    Autentica o usuario via rest framework
    :param request:
    :return: response<json> - Retorna todos os posts
    """
    posts = Post.objects.all()
    serializer = PostSerializer(posts, many=True)
    response = {
        "status": "success",
        "shows": serializer.data,
    }

    return Response(response)
示例#19
0
文件: views.py 项目: chenjunqian/here
def getPostByUsername(request):
	if request.method == 'GET':
		username = request.GET.get('username')
		try:
			posts = Post.objects.filter(username=username)
			serializer = PostSerializer(posts)
			return Response(serializer.data, status=status.HTTP_200_OK)
		except Post.DoesNotExist as e:
			errors = { 
				'error_code': '8003',
				'error': 'POST_FAILED',
				'message': e,
			}
			return Response(errors,status=status.HTTP_404_NOT_FOUND)
示例#20
0
    def get(self, request):
        user = request.user
        post_id = request.params.get("post_id","")

        try:
            post = Post.objects.get(id=int(post_id))
            post.delete()
            posts = Post.objects.filter(author=user)
            serializer = PostSerializer(posts,many=True)
            return serializer.data

        except Exception,R:
            log = Logger(log=str(R))
            log.save()
            return {'message':'error  '+str(R)}
示例#21
0
def load(request):
    count = int(request.GET['count'])
    mode = request.GET['mode']

    if mode == 'created_at':
        posts = Post.objects.order_by('-created_at')[count:LOAD_MORE_COUNT +
                                                     count]
    else:
        posts = Post.objects.order_by('-like')[count:LOAD_MORE_COUNT + count]

    return JsonResponse({
        'code': '100',
        'msg': 'success',
        'posts': PostSerializer(posts, many=True).data
    })
示例#22
0
文件: views.py 项目: chenjunqian/here
def deletePostById(request):
	if request.method == 'DELETE':
		postId = request.DELETE.get('postid')
		username = request.POST.get('username')
		try:
			post = Post.objects.get(id=postId,username=username).delete()
			serializer = PostSerializer(post, status=status.HTTP_200_OK)
			return Response(serializer.data)
		except Post.ProtectedError as e:
			errors = { 
				'error_code': '8003',
				'error': 'DELETE_FAILED',
				'message': e,
			}
			return Response(errors,status=status.HTTP_404_NOT_FOUND)
示例#23
0
	def post(self, request, format=None):
		username = request.COOKIES.get('username')
		user = User.objects.get(username=username)
		serializer = PostSerializer(data=request.data, context={'user':user})
		print(serializer.is_valid())
		if serializer.is_valid():
			serializer.save()
			return Response(serializer.data)
		print(serializer.errors)
		return Response(serializer.errors)
示例#24
0
    def get(self, request):

        user = request.user
        title = request.params.get("title","")
        body = request.params.get("body","")  
        category_id = request.params.get("category_id","")

        try:

            category = Category.objects.get(id=int(category_id))
            post = Post.objects.create(title=title,body=body,
                                       category=category,author=user)
            posts = Post.objects.filter(author=user)
            serializer = PostSerializer(posts,many=True)
            return serializer.data

        except Exception,R:
            return {'message':'error '+str(R)}
示例#25
0
    def get(self, request):

        user = request.user

        try:

            posts = Post.objects.all().order_by('-time_published')
      
            for post in posts:
               comments = Comment.objects.filter(post=post)
               post.total_comments = len(comments)
               post.save()
      
            serializer = PostSerializer(posts,many=True)
            return serializer.data

        except Exception,R:
            return {'message':'error '+str(R)}
示例#26
0
    def get(self, request):
        user = request.user
        post_id = request.params.get("post_id","")

        try:
            post = Post.objects.get(id=int(post_id))
            serializer = PostSerializer(post,many=False)
            return serializer.data

        except Exception,R:
            log = Logger(log=str(R))
            log.save()
            logger.error('Internal Server Error: %s', request.path,
                exc_info=sys.exc_info(),
                extra={
                    'status_code': 500,
                    'request': request
                }
            )

            return {'message':'error  '+str(R)}
示例#27
0
文件: views.py 项目: chenjunqian/here
def getLocationByLocation(request):
	if request.method == 'GET':
		longitude = request.GET.get('longitude')
		latitude = request.GET.get('latitude')
		city = request.GET.get('city')
		index = request.GET.get('index')

		try:
			posts = Post.objects.filter(
				longitude__gte=float(longitude)-0.05, longitude__lte=float(longitude)-0.05,
				latitude__gte=float(longitude)-0.05, latitude__lte=float(longitude)-0.05,
				city=city
			)

			serializer = PostSerializer(posts)
			return Response(serializer.data, status=status.HTTP_200_OK)
		except PostTag.DoesNotExist as e:
			errors = { 
				'error_code': '8003',
				'error': 'POST_FAILED',
				'message': e,
			}
			return Response(errors,status=status.HTTP_404_NOT_FOUND)
示例#28
0
def get_post(request, pk):
    """ Realiza as operações de select, update e delete no post dono da pk """

    try:
        post = Post.objects.get(pk=pk)
    except Post.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = PostSerializer(post)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = PostSerializer(post, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        post.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
示例#29
0
    def get(self, request):

        user = request.user
        post_id = request.params.get("post_id","")
        title = request.params.get("title","")
        body = request.params.get("body","")
        category_id = request.params.get("category_id","")
        link = request.params.get("link","")

        try:

            category = Category.objects.get(id=int(category_id))
            post = Post.objects.get(id=int(post_id))
            post.category=category
            post.title=title
            post.body=body
            post.link=link
            post.save()   
            posts = Post.objects.filter(author=user)
            serializer = PostSerializer(posts,many=True)
            return serializer.data

        except Exception,R:
            return {'message':'error '+str(R)}
示例#30
0
	def get(self, request, format=None):
		post = Post.objects.all().order_by('-date')
		serializer = PostSerializer(post, many=True)
		return Response(serializer.data)
示例#31
0
 def post(self, request):
     serializer = PostSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=201)
     return Response(serializer.errors, status=400)
示例#32
0
 def list(self, request):
     queryset = Post.objects.all()
     serializer = PostSerializer(queryset, many=True)
     return Response(serializer.data)
示例#33
0
 def get(self, id):
     posts = Post.query.filter_by(id=id).first()
     return PostSerializer(posts).data
示例#34
0
 def get(self):
     posts = Post.query.all()
     return PostSerializer(posts, many=True).data
示例#35
0
 def get(self, request, *args, **kwargs):
     post = Post.objects.all()
     serializer = PostSerializer(post, many=True)
     return Response(serializer.data)