我正在编写一个RESTful API作为django项目的应用程序。 我的应用程序中有两个端点(将url导入到主项目中的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'),
]
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)
我希望能够使用以下网址进行呼叫(以下所示的所有内容,返回404未找到的错误:
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)
然后我尝试在服务器上POST(创建)一个新图表:
curl -H "Content-Type: application/json" -X POST -d '{/* data */}' http://127.0.0.1:8000/testrest/chart (404)
为什么模式不匹配?
答案 0 :(得分:0)
urls
中存在一些拼写错误。您缺少<resolution>
和<name>
的{{3}}语法合成语。以下内容将匹配以上所有404
失败:
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_\.-]{3,12})?/?$', views.chart, name='pchart')
]
另外,我将<name>
内pchart
网址的长度更改为3到12之间(不知道你想怎么样)。