Ejemplo n.º 1
0
def snippet_detail(request, id):
	"""
	Retrieve, update or delete a code snippet.
	"""
	try:
		snippet = Snippet.objects.raw_query({'rea' : int(id)})
		
		if not snippet:
			return HttpResponse(status=404)

		all_avisos = snippet.values('rea')[0]
	except Snippet.DoesNotExist:
		return HttpResponse(status=404)

	if request.method == 'GET':
		serializer = SnippetSerializer(all_avisos)
		context = {'duplicateds_avisos': all_avisos['rea']}

		return render(request, 'duplicateds.html', context)

	elif request.method == 'PUT':
		data = JSONParser().parse(request)
		serializer = SnippetSerializer(snippet, data=data)
		if serializer.is_valid():
			serializer.save()
			return JSONResponse(serializer.data)
		return JSONResponse(serializer.errors, status=400)

	elif request.method == 'DELETE':
		snippet.delete()
		return HttpResponse(status=204)
Ejemplo n.º 2
0
def snippet_detail_api(request, id):
	"""
	Retrieve, update or delete a code snippet.
	"""
	try:
		snippet = Snippet.objects.raw_query({'rea' : int(id)})
		# print JSONResponse(snippet.data)
	except Snippet.DoesNotExist:
		return HttpResponse(status=404)

	if request.method == 'GET':

		if snippet:
			all_avisos = snippet.values('rea')[0]
			serializer = SnippetSerializer(all_avisos)
			return JSONResponse(serializer.data)
		else:
			all_avisos = [{"Message":"No duplicated ads found."}]
		
		return JSONResponse(all_avisos)
		

	elif request.method == 'PUT':
		data = JSONParser().parse(request)
		serializer = SnippetSerializer(snippet, data=data)
		if serializer.is_valid():
			serializer.save()
			return JSONResponse(serializer.data)
		return JSONResponse(serializer.errors, status=400)

	elif request.method == 'DELETE':
		snippet.delete()
		return HttpResponse(status=204)
 def post(self, request, format=None):
   serializer = SnippetSerializer(data=request.data)
   if serializer.is_valid():
     # The create() method of our serializer will now be passed an additional 'owner' field, along with the validated data from the request.
     serializer.save(owner=self.request.user)
     return Response(serializer.data, status=status.HTTP_201_CREATED)
   return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
	def post(self, request, format=None):
		data = JSONParser().parse(request)
		serializer = SnippetSerializer(data=data)
		if serializer.is_valid():
			serializer.save()
			return Response(serializer.data, status=status.HTTP_201_CREATED)
		return Response(serializer.data, status = status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 5
0
def snippet_detail(request, pk, format=None):
    """
    Retrieve, update or delete a code snippet.
    """
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)

    elif request.method == 'PUT':
        # data = JSONParser().parse(request)
        # serializer = SnippetSerializer(snippet, data=data)
        serializer = SnippetSerializer(snippet, 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':
        snippet.delete()
        return Response(status=status.HTTP_200_OK)
Ejemplo n.º 6
0
	def post(self, request, format = None):
		serializer = SnippetSerializer(request.data)
		if serializer.is_valid():
			serializer.save()
			return Response(serializer.data, status = status.Http_201_CREATE)
		return Response(serializer.errors, status = status.Http_400_BAD_REQUEST)
		pass
Ejemplo n.º 7
0
def snippet_detail(request, month, year):
    """
    Retrieve, update or delete a code snippet.
    """

    try:
        #snippet = Analysis.objects.filter(created__month=month,created__year=year,created__day=4,created__hour__gte=9)
        snippet = Analysis.objects.filter(user_id__contains = 1030)
    except Analysis.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = SnippetSerializer(snippet, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(snippet, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        snippet.delete()
        return HttpResponse(status=204)
def snippet_detail(request, pk):
    """
    Retrieve, update or delete a snippet instance.
    """
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = SnippetSerializer(snippet, data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Ejemplo n.º 9
0
def snippet_detail(request, pk):
    """
    Retrieve, update, or delete a code snippet.
    :param request:
    :param pk:
    :rtype: JSONResponse
    :return:
    """
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return JSONResponse(serializer.data)
    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(snippet, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=400)
    elif request.method == 'DELETE':
        snippet.delete()
        return HttpResponse(status=204)
Ejemplo n.º 10
0
 def post(self, request, format=None):
     serializer = SnippetSerializer(data=request.data)
     if serializer.is_valid():
         #serializer.save()
         self.perform_create(serializer)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 11
0
def snippet_detail(request, pk, format=None):
    """
    Retrieve, update or delete a code snippet.
    """
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)

    elif request.method == 'PUT':
	#use resquest.data repalce data
        #data = JSONParser().parse(request)
        serializer = SnippetSerializer(snippet, data=resquest.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=400)

    elif request.method == 'DELETE':
        snippet.delete()
        return HttpResponse(status=204)
Ejemplo n.º 12
0
def snippet_detail(request, pk):
    """
    코드 조각 조회, 업데이트, 삭제
    """
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return HttpResponse(status=404)


    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return JSONResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(snippet, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        snippet.delete()
        return HttpResponse(status=204)
Ejemplo n.º 13
0
 def put(self, request, pk, format=None):
     snippet = self.get_object(pk)
     serializer = SnippetSerializer(snippet, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 14
0
def snippet_detail(request, pk):
    """
    Retrieve, update or delete a code snippet.
    """
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return JSONResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(snippet, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        snippet.delete()
        return HttpResponse(status=204)
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                      IsOwnerOrReadOnly,)
Ejemplo n.º 15
0
	def post(self,request):
		data = JSONParser().parse(request)
		serializer = SnippetSerializer(data=data)
		if serializer.is_valid():
			serializer.save()
			return JSONResponse(serializer.data,status=201)
		return JSONResponse(serializer.errors,status=400)
    def test_stream(self):
        content = JSONRenderer().render(self.serializer.data)
        stream = StringIO.StringIO(content)
        data = JSONParser().parse(stream)

        serializer = SnippetSerializer(data=data)
        self.assertTrue(serializer.is_valid())
        for attribute in ("title", "code", "linenos", "language", "style"):
            self.assertEquals(getattr(serializer.object, attribute), getattr(self.snippet, attribute))
Ejemplo n.º 17
0
def snippet_list(request):
	if request.method == 'GET':
		snippets = Snippet.objects.all()
		serializer = SnippetSerializer(snippets,many=True)
		return Response(serializer.data)
	elif request.method == 'POST':
		serializer = SnippetSerializer(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_404_BAD_REQUEST)
Ejemplo n.º 18
0
def snippet_list(request):
    if request.method == "GET":
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response(serializer.data)
    elif request.method == "POSt":
        serializer = SnippetSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_100_CONTINUE)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 19
0
def snippet_list(request):
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return JSONResponse(serializer.data)
    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)
def snippet_list(request, format = None):

	if request.method == 'GET':
		snippets = Snippet.objects.all()
		serializer = SnippetSerializer(snippets, many=True)
		return Response(serializer.data)

	elif request.method == 'POST':
		data = JSONParser().parse(request)
		serializer = SnippetSerializer(data=data)
		if serializer.is_valid():
			serializer.save()
			return Response(serializer.data, status=status.HTTP_201_CREATED)
		return Response(serializer.data, status = status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 21
0
def snippet_list(request, format=None):
  """
  List all snippets, or create a new snippet.
  """
  if request.method == 'GET':
    snippets = Snippet.objects.all()
    serializer = SnippetSerializer(snippets, many=True)
    return Response(serializer.data)
  elif request.method == 'POST':
    serializer = SnippetSerializer(request.data)
    if serializer.is_valid():
      serializer.save()
      return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(status=status.HTTP_400_BAD_REQUEST)
def snippet_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = SnippetSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_499)
Ejemplo n.º 23
0
def snippet_list(request, format=None):
    """
    List all the code snippets, or create a new one.
    """
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = SnippetSerializer(data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)
Ejemplo n.º 24
0
def snippet_list(request):
    """
    List all snippets, or create a new snippet.
    """
    if request.method == 'GET':
        snippets = request.user.snippets.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = SnippetSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(owner=request.user)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 25
0
def snippet_list(request):
	'''
	展示所有存在的snippet, 或者建立新的snippet
	'''
	if request.method == 'GET':  # 获得所有数据
		snippets = Snippet.objects.all()
		serializer = SnippetSerializer(snippets, many=True)
		return JSONResponse(serializer.data)
	elif request.method == 'POST': # 提交数据
		data = JSONParser().parse(request)
		serializer = SnippetSerializer(data=data)
		if serializer.is_valid():  # 如果数据存在就保存并提交,反之报错
			serializer.save()
			return JSONResponse(serializer.data, status=201)
		return JSONResponse(serializer.errors, status=400)
Ejemplo n.º 26
0
def snippet_list(request, format=None):
    """
    Lista todos los snippets o crea un nuevo snippet
    """
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = SnippetSerializer(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)
Ejemplo n.º 27
0
    def snippet_list(request):
        """
    List all code snippets, or create a new snippet.
    """
        if request.method == "GET":
            snippets = Snippet.objects.all()
            serializer = SnippetSerializer(snippets, many=True)
            return JSONResponse(serializer.data)

        elif request.method == "POST":
            data = JSONParser().parse(request)
            serializer = SnippetSerializer(data=data)
            if serializer.is_valid():
                serializer.save()
                return JSONResponse(serializer.data, status=201)
            return JSONResponse(serializer.errors, status=400)
Ejemplo n.º 28
0
def snippet_detail(request, pk):
	"""retrieve or delete code snippet"""
	try:
		snippet = Snippet.objects.get(pk=pk)
	except Snippet.DoesNotExist:
		return HttpResponse(status=404)

	if request.method == 'GET':
		serializer = SnippetSerializer(snippet)
		return JSONResponse(serializer.data)

	elif request.method == 'PUT'
		data = JSONParser().parse(request)
		serializer.is_valid():
			serializer.save()
			return JSONResponse(serializer.data)
		return JSONResponse(serializer.errors, status=400)
Ejemplo n.º 29
0
def snippet_detail(request, pk, format=None):
	try:
		snippet = Snippet.objects.get(pk=pk)
	except Snippet.DoesNotExist:
		return Response(status=status.HTTP_404_NOT_FOUND)

	if request.method == 'GET':
		serializer = SnippetSerializer(snippet)
		return Response(serializer.data)
	elif request.method == 'PUT':
		serializer = SnippetSerializer(snippet, 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':
		snippet.delete()
		return Response(status=status.HTTP_204_NO_CONTENT)
Ejemplo n.º 30
0
def snippet_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)
    def perform_create(self, serializer):
    	serializer.save(owner=self.request.user)
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
Ejemplo n.º 31
0
 def get(self, request, format=None):
     snippets = Snippet.objects.all()
     serializer = SnippetSerializer(snippets,
                                    many=True,
                                    context={'request': request})
     return JsonResponse(serializer.data, safe=False)
Ejemplo n.º 32
0
 def get(self, request, pk, format=None):
     snippet = self.get_object(pk)
     serializer = SnippetSerializer(snippet)
     print(serializer.data)
     content = serializer.data.get('text')
     return Response(data=content, content_type='text/plain; charset=utf-8')
from snippets.serializers import SnippetSerializer
serializer = SnippetSerializer()
print(repr(serializer))
# SnippetSerializer():
#    id = IntegerField(label='ID', read_only=True)
#    title = CharField(allow_blank=True, max_length=100, required=False)
#    code = CharField(style={'base_template': 'textarea.html'})
#    linenos = BooleanField(required=False)
#    language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...
#    style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...
Ejemplo n.º 34
0
 def get(self, request, pk, format=None):
     if request.user.is_authenticated:
         snippet = self.get_object(pk)
         serializer = SnippetSerializer(snippet)
         return Response(serializer.data)
     return Response(status=status.HTTP_401_UNAUTHORIZED)
Ejemplo n.º 35
0
from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

snippet = Snippet(code='foo = "bar"\n')
snippet.save()

snippet = Snippet(code='print "hello, world"\n')
"""
Calling .save() will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class.
"""
snippet.save()
"""
We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.
"""
serializer = SnippetSerializer(snippet)
serializer.data
# {'id': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}
"""
At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into json.
"""

content = JSONRenderer().render(serializer.data)
content
# '{"id": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
"""
Deserialization is similar. First we parse a stream into Python native datatypes...
"""
from django.utils.six import BytesIO

stream = BytesIO(content)
Ejemplo n.º 36
0
 def list(self, request, pk):
     queryset = self.get_queryset()
     serializer = SnippetSerializer(queryset, many=True)
     return Response(serializer.data)
Ejemplo n.º 37
0
 def put(self, request, pk, format=None):
     serializer = SnippetSerializer(self.get_object(pk), data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 38
0
 def get(self, request, format=None):
     snippets = Snippet.objects.all()
     serializer = SnippetSerializer(snippets, many=True)
     return Response(serializer.data)
Ejemplo n.º 39
0
 def perform_create(self, serializer: SnippetSerializer):
     serializer.save(owner=self.request.user)
Ejemplo n.º 40
0
 def get(self, request, pk):
     snippet = self.get_object(pk=pk)
     serializer = SnippetSerializer(snippet)
     return Response(serializer.data)
Ejemplo n.º 41
0
 def get(self, request, format=None):
     queryset = Snippet.objects.all()
     return SnippetSerializer(queryset, read_only=True, many=True)
Ejemplo n.º 42
0
 def get(self, request, format=None):
     goods = Goods.objects.all()[:10]
     serializer = SnippetSerializer(snippets, many=True)
     return Response(serializer.data)
Ejemplo n.º 43
0
 def get_context_data(self, **kwargs):
     context = super(IndexView, self).get_context_data(**kwargs)
     context.update(snippet=SnippetSerializer())
     return context
Ejemplo n.º 44
0
 def post(self, request, format=None):
     serializer = SnippetSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Respons(serializer.data, status=status.HTTP_200_OK)
Ejemplo n.º 45
0
def snippet_detail(request, pk, format=None):
    """
    Retrieve, update or delete a code snippet.
    """
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = SnippetSerializer(snippet, 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':
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


# from django.http import HttpResponse, JsonResponse
# from django.views.decorators.csrf import csrf_exempt
# from rest_framework.renderers import JSONRenderer
# from rest_framework.parsers import JSONParser
# from snippets.models import Snippet
# from snippets.serializers import SnippetSerializer
#
# @csrf_exempt
# def snippet_list(request):
#     """
#     List all code snippets, or create a new snippet.
#     """
#     if request.method == 'GET':
#         snippets = Snippet.objects.all()
#         serializer = SnippetSerializer(snippets, many=True)
#         return JsonResponse(serializer.data, safe=False)
#
#     elif request.method == 'POST':
#         data = JSONParser().parse(request)
#         serializer = SnippetSerializer(data=data)
#         if serializer.is_valid():
#             serializer.save()
#             return JsonResponse(serializer.data, status=201)
#         return JsonResponse(serializer.errors, status=400)
#
# @csrf_exempt
# def snippet_detail(request, pk):
#     """
#     Retrieve, update or delete a code snippet.
#     """
#     try:
#         snippet = Snippet.objects.get(pk=pk)
#     except Snippet.DoesNotExist:
#         return HttpResponse(status=404)
#
#     if request.method == 'GET':
#         serializer = SnippetSerializer(snippet)
#         return JsonResponse(serializer.data)
#
#     elif request.method == 'PUT':
#         data = JSONParser().parse(request)
#         serializer = SnippetSerializer(snippet, data=data)
#         if serializer.is_valid():
#             serializer.save()
#             return JsonResponse(serializer.data)
#         return JsonResponse(serializer.errors, status=400)
#
#     elif request.method == 'DELETE':
#         snippet.delete()
#         return HttpResponse(status=204)
Ejemplo n.º 46
0
 def get(self, request, format=None):
     snippets = Snippet.objects.all()
     serializer = SnippetSerializer(snippets, many=True)
     data={"key":"v"}
     return Response(data,status.HTTP_200_OK)
Ejemplo n.º 47
0
 def get(self, request, pk, format=None):
     snippet = self.get_object(pk)
     serializer = SnippetSerializer(snippet)
     return JsonResponse(serializer.data)
Ejemplo n.º 48
0
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

snippet = Snippet(code='foo = "bar"\n')
snippet.save()

snippet = Snippet(code='print("hello, world")\n')
snippet.save()
serializer = SnippetSerializer(snippet)
print(serializer.data)
content = JSONRenderer().render(serializer.data)
print(content)

import io

stream = io.BytesIO(content)
data = JSONParser().parse(stream)
serializer = SnippetSerializer(data=data)
serializer.is_valid()
# True
serializer.validated_data
# OrderedDict([('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
serializer.save()
Ejemplo n.º 49
0
 def post(self, request, format=None):
     serializer = SnippetSerializer(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)
Ejemplo n.º 50
0
def snippet_detail(request, pk):
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return JsonResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        # Serializer인스턴스 생성에 모델 클래스 인스턴스와 data를 함께 사용
        # (전달받은 데이터로 인스턴스의 내용을 update예정)
        serializer = SnippetSerializer(snippet, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)

    elif request.method == 'PATCH':
        data = JSONParser().parse(request)
        # partial=True
        # Serializer의 required=True필드의 값이 주어지지 않아도 valid하다고 판단
        serializer = SnippetSerializer(snippet, data=data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        snippet.delete()
        return HttpResponse(status=204)
Ejemplo n.º 51
0
 def get(self, request, pk, format=None):
     snippet = get_object_or_404(Snippet, pk=pk)
     serializer = SnippetSerializer(snippet)
     return Response(serializer.data)
Ejemplo n.º 52
0
def snippet_list(request):  #全データ

    if request.method == 'GET':
        #snippets = Snippet.objects.all()
        allnode = list(
            AllNode.objects.values_list('client',
                                        flat='True').distinct())  #allnodeの名前一覧
        data_node = list(
            Snippet.objects.values_list(
                'name', flat='True').distinct())  #data_nodeの名前一覧

        #Queueデータベース参照
        queue = list(
            Client_Queue.objects.values_list(
                'client', flat='True').distinct())  #queueに入っているデータを参照
        get_node = request.GET.get("client")  #アクセスしてきたクライエントの名前
        """
        test = garbage("test",0,0)
        print(test.name)
        obj_list = []
        for i in allnode:
            AllNode.objects.values_list('client',flat='True')
        """
        culc_bit = Culc_bit.objects.get(id=1)
        if ((set(allnode)) == (set(data_node))):  #全clientがデータPOST済みなら
            if get_node in queue:  #既に移動先を送信済みなら
                return JsonResponse({"error": "-1"})  #待機命令
            else:
                if (culc_bit.client == 1):
                    temp = AllNode.objects.get(client=get_node)
                    x = temp.x
                    y = temp.y
                    return JsonResponse({"x": x, "y": y})
                #まだGETをもらっていなかったら送信済みQueuデータベースに追加
                client_queue = Client_Queue.objects.create(client=get_node)
                client_queue.save()
                testlist = []
                #アルゴリズム処理
                #instance生成
                for i in allnode:
                    x = AllNode.objects.filter(client=i).values_list(
                        'x', flat='True')
                    y = AllNode.objects.filter(client=i).values_list(
                        'y', flat='True')
                    weight = Snippet.objects.filter(name=i).values_list(
                        'people', flat='True').latest("created")
                    tmp_obj = garbage(i, x, y)  #名前,x,y
                    tmp_obj.amount = weight
                    testlist.append(tmp_obj)
                calced_pos = calc_position(
                    testlist
                )  #名前,x,y 引数objで未実装calc_position calc_position = [[名前,x,y],[名前,x,y]]二次元リスト
                #AllNodeで位置情報設定
                for i in calced_pos:  #[[名前,x,y],[名前,x,y]]二次元リスト
                    temp = AllNode.objects.get(client=i[0])
                    temp.x = str(i[1])
                    temp.y = str(i[2])
                    temp.save()
                temp = Culc_bit.objects.get(id=1)
                temp.client = 1
            if (set(allnode)) == (set(queue)):
                Client_Queue.objects.all().delete()
                Snippet.objects.all().delete()
                temp1 = Culc_bit.objects.get(id=1)
                temp1.client = 0
                temp1.save()
            temp = AllNode.objects.get(client=get_node)
            x = temp.x
            y = temp.y
            return JsonResponse({"x": x, "y": y})
        #serializer = SnippetSerializer(snippets, many=True)
        #print(serializer.data)
        return JsonResponse(
            {"error":
             "-2"})  #JsonResponse(serializer.data, safe=False)#まだそろってない

    elif request.method == 'POST':
        data = JSONParser().parse(request)  #data変数にデータを入れる
        serializer = SnippetSerializer(data=data)  #データベースに格納するオブジェクトを作成する
        if serializer.is_valid():
            serializer.save()  #データベースセーブ
            """
            #MAPデータに格納
            mapfield = MapField(client= "C1_test",x = 0,y = 0)
            mapfield.save()
            """
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)
Ejemplo n.º 53
0
#from snippets.serializers import SnippetSerializer
#from django.http importHttpResponse
from django.views.decorators.csrf import csrf_sxempt
from rest_framework.renderers import JSONRenderer
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from django.conf.urls import url 
from snippets import views



SnippetSerializer():
	id = IntegerField(label='ID', read_only=True)
	title = CharField(allow_blank=True, max_length=100, required=False)
	code = CharField(style={'base_template': 'textarea.html'})
	linenos = BooleanField(required=False)
	language = ChoiceField(choices=[('python', 'python')])
	style = ChoiceField(choices=[('autumn', 'autumn')])

class JSONResponse(HttpResponse):
	def __init__(self, data, **kwargs):
		content = JSONRenderer().render(data)
		kwargs['content_type'] = 'application/json'
		super(JSONResponse, self).__init__(content, **kwargs)

# @csrf_exempt
# def snippet_list(request):
# 	"""list all code snippets or create a new snippet"""
# 	if request.method == 'GET':
# 		snippets = Snippet.objects.all()
# 		serializers = SnippetSerializer(snippets, many=True)
Ejemplo n.º 54
0
def snippet_list(request):
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return JsonResponse(serializer.data, safe=False)
Ejemplo n.º 55
0
 def get(self, request, pk, format=None):
     snippet = self.get_object(pk)
     serializer = SnippetSerializer(snippet, context={'request': request})
     return Response(serializer.data)
Ejemplo n.º 56
0
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
import io

serializer = SnippetSerializer(Snippet.objects.all(), many=True)
print(serializer.data)

# snippet = Snippet(code='foo = "bar"\n')
# snippet.save()

# snippet = Snippet(code='print("hello, world")\n')
# snippet.save()

# serializer = SnippetSerializer(snippet)
# print(serializer.data)

# content = JSONRenderer().render(serializer.data)
# print(content)

# stream = io.BytesIO(content)
# data = JSONParser().parse(stream)

# serializer = SnippetSerializer(data=data)
# print(serializer.is_valid())
# print(serializer.validated_data)
Ejemplo n.º 57
0
def snippet_detail(request, pk, format=None):
    """
    Retrieve, update or delete a code snippet.
    """
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)
    elif request.method == 'PUT':
        serializer = SnippetSerializer(snippet, 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':
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


# Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as csrf_exempt.
# @csrf_exempt
# def snippet_list(request):
#     """
#     List all code snippets, or create a new snippet.
#     """
#     if request.method == 'GET':
#         snippets = Snippet.objects.all()
#         serializer = SnippetSerializer(snippets, many=True) # We can also serialize querysets instead of model instances. To do so we simply add a many=True flag to the serializer arguments.
#         return JsonResponse(serializer.data, safe=False)
#     elif request.method == 'POST':
#         data = JSONParser().parse(request)
#         serializer = SnippetSerializer(data=data)
#         if serializer.is_valid():
#             serializer.save()
#             return JsonResponse(serializer.data, status=201)
#         return JsonResponse(serializer.errors, status=400)
#
#
# @csrf_exempt
# def snippet_detail(request, pk):
#     """
#     Retrieve, update or delete a code snippet.
#     """
#     try:
#         snippet = Snippet.objects.get(pk=pk)
#     except Snippet.DoesNotExist:
#         return HttpResponse(status=404)
#
#     if request.method == 'GET':
#         serializer = SnippetSerializer(snippet)
#         return JsonResponse(serializer.data)
#     elif request.method == 'PUT':
#         data = JSONParser().parse(request)
#         serializer = SnippetSerializer(snippet, data=data)
#         if serializer.is_valid():
#             serializer.save()
#             return JsonResponse(serializer.data)
#         return JsonResponse(serializer.errors, status=400)
#     elif request.method == 'DELETE':
#         snippet.delete()
#         return HttpResponse(status=204)
Ejemplo n.º 58
0
def snippet_detail(request, pk):
    """
    Retrieve, update or delete a snippet instance.
    """
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = SnippetSerializer(snippet, 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':
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


# from django.http import HttpResponse
# from django.views.decorators.csrf import csrf_exempt
# from rest_framework.renderers import JSONRenderer
# from rest_framework.parsers import JSONParser
# from snippets.models import Snippet
# from snippets.serializers import SnippetSerializer
#
# class JSONResponse(HttpResponse):
#     """
#     An HttpResponse that renders its content into JSON.
#     """
#     def __init__(self, data, **kwargs):
#         content = JSONRenderer().render(data)
#         kwargs['content_type'] = 'application/json'
#         super(JSONResponse, self).__init__(content, **kwargs)
#
#
# @csrf_exempt
# def snippet_list(request):
#     """
#     List all code snippets, or create a new snippet.
#     """
#     if request.method == 'GET':
#         snippets = Snippet.objects.all()
#         serializer = SnippetSerializer(snippets, many=True)
#         return JSONResponse(serializer.data)
#
#     elif request.method == 'POST':
#         data = JSONParser().parse(request)
#         serializer = SnippetSerializer(data=data)
#         if serializer.is_valid():
#             serializer.save()
#             return JSONResponse(serializer.data, status=201)
#         return JSONResponse(serializer.errors, status=400)
#
# @csrf_exempt
# def snippet_detail(request, pk):
#     """
#     Retrieve, update or delete a code snippet.
#     """
#     try:
#         snippet = Snippet.objects.get(pk=pk)
#     except Snippet.DoesNotExist:
#         return HttpResponse(status=404)
#
#     if request.method == 'GET':
#         serializer = SnippetSerializer(snippet)
#         return JSONResponse(serializer.data)
#
#     elif request.method == 'PUT':
#         data = JSONParser().parse(request)
#         serializer = SnippetSerializer(snippet, data=data)
#         if serializer.is_valid():
#             serializer.save()
#             return JSONResponse(serializer.data)
#         return JSONResponse(serializer.errors, status=400)
#
#     elif request.method == 'DELETE':
#         snippet.delete()
#         return HttpResponse(status=204)
Ejemplo n.º 59
0
def ShowSnippets(request):
    snippets = Snippet.objects.all()
    serializer = SnippetSerializer(snippets, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)
Ejemplo n.º 60
0
def snippet_detail(request, pk, format=None):
    """
    Retrieve, update or delete a snippet instance.
    """
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = SnippetSerializer(snippet, 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':
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


# @csrf_exempt
# def snippet_list(request):
#     """
#     List all code snippets, or create a new snippet.
#     """
#     if request.method == 'GET':
#         snippets = Snippet.objects.all()
#         serializer = SnippetSerializer(snippets, many=True)
#         return JSONResponse(serializer.data)

#     elif request.method == 'POST':
#         data = JSONParser().parse(request)
#         serializer = SnippetSerializer(data=data)
#         if serializer.is_valid():
#             serializer.save()
#             return JSONResponse(serializer.data, status=201)
#         return JSONResponse(serializer.errors, status=400)

# @csrf_exempt
# def snippet_detail(request, pk):
#     """
#     Retrieve, update or delete a code snippet.
#     """
#     try:
#         snippet = Snippet.objects.get(pk=pk)
#     except Snippet.DoesNotExist:
#         return HttpResponse(status=404)

#     if request.method == 'GET':
#         serializer = SnippetSerializer(snippet)
#         return JSONResponse(serializer.data)

#     elif request.method == 'PUT':
#         data = JSONParser().parse(request)
#         serializer = SnippetSerializer(snippet, data=data)
#         if serializer.is_valid():
#             serializer.save()
#             return JSONResponse(serializer.data)
#         return JSONResponse(serializer.errors, status=400)

#     elif request.method == 'DELETE':
#         snippet.delete()
#         return HttpResponse(status=204)