GET请求期间在Django中进行身份验证

时间:2018-09-19 00:59:36

标签: android django api get request

我需要通过android应用程序向Django服务器发送GET请求。 问题在于此GET函数是使用Django @@ login_required编写的。

我应该执行哪种请求来登录并执行GET请求?

我的API:

from django.shortcuts import render
from django.http import HttpResponse,HttpResponseServerError, HttpResponseBadRequest
from rest_framework.decorators import api_view
from .models import Order, New
import json
from django.shortcuts import render_to_response
from .forms import NewForm
from django.core.files.storage import FileSystemStorage
from django.contrib.auth.decorators import login_required
from .validation import *
from django.views.decorators.csrf import csrf_exempt
@login_required
@api_view(['GET'])
def get_order(request):

    order_list = Order.objects.values("user_name",
                        "user_surname",
                        "order_date").all()

    return HttpResponse(json.dumps([x for x in order_list])

我的urls.py:

from django.urls import path
from django.conf.urls import url
from . import views

app_name = 'API'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^order', views.order, name='order'),
    url(r'^get_order', views.get_order, name='get_order')]

和:

from django.contrib import admin
from . import settings
from django.views.static import serve
from django.urls import path, include, re_path
from django.conf.urls.static import static
from API.views import index

urlpatterns = [
    path('API/', include('API.urls',namespace="API")),
    path('admin/', admin.site.urls),
    path('', index, name='index'),
    path(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT})
]

在邮递员中,我正在使用基本身份验证执行GET(http://127.0.0.1:8000/API/get_order),并收到302状态代码。

1 个答案:

答案 0 :(得分:0)

我不确定如何在 Android端 中完成此操作,但是基本思路是您应该添加 身份验证凭据 GET请求中的em>

我将通过使用Python's Requests library

向您显示一个示例
from requests.auth import HTTPBasicAuth
import requests

requests.get('http://my/url/end/poin/', auth=HTTPBasicAuth('my_username', 'mypass'))



May be these results will help you to find the answer;)


更新

1.进入授权标签
2.选择基本身份验证类型
3.在相应的文本框中提供您的usernamepassword
4.点击发送按钮

enter image description here

UPDATE-2
如下更改视图

from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response


@permission_classes((IsAuthenticated,))
@api_view(['GET'])
def get_order(request):
    order_list = Order.objects.values("user_name",
                                      "user_surname",
                                      "order_date").all()

    return Response(data=[x for x in order_list])