如何对我的另一个视图进行API调用?

时间:2019-06-05 05:24:15

标签: django django-rest-framework django-views

我正在开发一个简单的投资跟踪器应用程序,该应用程序应该从api获取股票价格并向用户很好地显示它们。我遇到了麻烦,但是无法将必要的数据传递给API调用。

views.py

class PortfolioData(APIView):
   authentication_classes = []
   permission_classes = []

   def get(self, request, tickers ,format=None):
       # how do I pass the tickers?
       stock_data = get_multiple_stock_details(tickers) # returns JSON response

       return Response(stock_data)

@login_required
   def portfolio(request):
     user = request.user
     user_portfolio = Portfolio.objects.filter(user=user).first()

     return render(request, 'app/portfolio.html', {'portfolio':user_portfolio})

urls.py

urlpatterns = [
    path('', views.home, name="homepage"),
    path('api/portfolio/data/', views.PortfolioData.as_view(), 
    name="portfolio-data"),
    path('portfolio/', views.portfolio, name='portfolio'), 
]

在前端,我将对我的PortfolioData视图进行ajax调用,以便能够在前端处理数据。我最大的问题是如何传递所需的参数。 我试图使用jQuery从前端获取股票代码,然后将其传递给端点url,但我不确定这是否是解决此问题的最佳方法。

1 个答案:

答案 0 :(得分:2)

您可以尝试像这样

urls.py

'''
You should bind two different url with same view. One with dynamic variable and another without it.
'''

urlpatterns = [
    path('', views.home, name="homepage"),
    path('api/portfolio/', views.PortfolioData.as_view(), name='api_portfolio'), # use unique name for each URL
    path('api/portfolio/<tickers>/', views.PortfolioData.as_view(), name='api_portfolio_data'), # use unique name for each URL
    path('portfolio/', views.portfolio, name='portfolio'), 
]

views.py

class PortfolioData(APIView):
   authentication_classes = []
   permission_classes = []

   def get(self, request, tickers=None ,format=None):
        if tickers is None:
            # GET /api/portfolio/ 
            print('No tickers parameter in URL')
            # implement your logic when tickers is not passed.
            return Response(JSON_DATA)
        # GET /api/portfolio/tickers1/
        # implement your logic when tickers is passed.
        stock_data = get_multiple_stock_details(tickers) # returns JSON response
        return Response(stock_data)

现在,当发出HTTP GET请求时(无所谓,是AJAX调用)。

  

http://localhost:8000/api/portfolio/

tickers变量将是None

  

http://localhost:8000/api/portfolio/ticker1/

tickers变量将是ticker1 str

希望,对您有帮助。