【发布时间】:2017-03-18 19:51:30
【问题描述】:
我正在编写一个 RESTful API 作为 django 项目的应用程序。 我的应用程序中有两个端点(将 url 导入到主项目的 urls.py 中),它们的定义如下所示:
testrest/urls.py
>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'prices/(?P<ticker>[X]{1}[A-Z0-9]{3}:[A-Z0-9]{1}[A-Z09.-]{1,4})/?P<resolution>([0-9]{0,3})/$', views.historyPrices, name='prices'),
url(r'chart/?P<name>([a-zA-Z0-9_\.-]{8,12})/$s', views.chart, name='pchart'),
]
testrest/views.py
>from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
# Create your views here.
@api_view(['GET'])
def historyPrices(request, ticker, resolution=1):
if request.method == 'GET':
try:
# do something
return Response({'foo': 'foobar'})
except Exception as e:
print ('Error: {0}'.format(e))
return Response(status = status.HTTP_500_INTERNAL_SERVER_ERROR)
else:
return Response(status = status.HTTP_405_METHOD_NOT_ALLOWED)
@api_view(['GET', 'POST', 'PUT', 'DELETE'])
def chart(request, name=None):
if request.method == 'GET':
if (name is not None):
try:
# do something
except Exception as e:
print('Error:',e)
return Response(status = status.HTTP_404_NOT_FOUND)
return Response({'foo': 'bar')
else:
return Response(status = status.HTTP_400_BAD_REQUEST)
elif request.method == 'POST':
data = request.data
# print(data)
try:
# do something
return Response(status = status.HTTP_201_CREATED)
except Exception as ex:
print('Unhandled exception: {0}'.format(e))
return Response(status = status.HTTP_500_INTERNAL_SERVER_ERROR)
elif request.method == 'PUT':
print('Called with PUT')
return Response(status=status.HTTP_501_NOT_IMPLEMENTED)
elif request.method == 'DELETE':
print('Called with DELETE')
return Response(status=status.HTTP_501_NOT_IMPLEMENTED)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)
我希望能够使用以下 url 进行调用(如下所示,返回 404 not found 错误:
curl http://127.0.0.1:8000/testrest/prices/XNAS:GOOG (404)
curl http://127.0.0.1:8000/testrest/prices/XNAS:GOOG/ (404)
curl http://127.0.0.1:8000/testrest/prices/XNAS:GOOG/3 (404)
curl http://127.0.0.1:8000/testrest/prices/XNAS:GOOG/3/ (404)
curl http://127.0.0.1:8000/testrest/prices?ticker=XNAS:GOOG (404)
curl http://127.0.0.1:8000/testrest/prices/?ticker=XNAS:GOOG&resolution=3 (404)
curl http://127.0.0.1:8000/testrest/prices?ticker=XNAS:GOOG&resolution=3/ (404)
我现在尝试从服务器加载手动创建的图表 (xyz):
curl http://127.0.0.1:8000/testrest/chart/xyz (404)
curl http://127.0.0.1:8000/testrest/chart/xyz/ (404)
curl http://127.0.0.1:8000/testrest/chart?name=xyz (404)
然后我尝试在服务器上发布(创建)一个新图表:
curl -H "Content-Type: application/json" -X POST -d '{/* data */}' http://127.0.0.1:8000/testrest/chart (404)
为什么模式不匹配?
【问题讨论】:
标签: python django rest django-rest-framework