我在学习Django,并构建了一个包含公司列表的小应用程序,其中包含每个公司的一些常规信息。主页显示所有公司的列表,然后用户可以点击公司名称查看更多信息。我现在试图通过使用Yahoo Finance来获取关于公司的一些股票数据并将其显示在页面上来了解如何在Django中使用API。 (我在Python中多次使用了yahoo-finance软件包,它非常简单,这就是为什么我盯着这个)。我不需要将数据保存到数据库(除非这是唯一的方法),我只是想显示它。如何在Django中使用Yahoo Finance API
我已经安装了pip打包并将其添加到settings.py文件中的APPS。
然后在我的views.py中,我添加了雅虎财务依赖关系,并试图在下面的代码中的API中工作。然后在模板中尝试使用{{mkt_cap}}。这样做,我得到一个YQLResponseMalformedError。我意识到这可能不是正确的方式,但我很难找出答案。
from django.views import generic
from .models import Company, Articles, Transcripts, TranscriptDetails
from yahoo_finance import Share
import json
class CompanyDetails(generic.DetailView):
model = Company
template_name = 'company_details.html'
def get_context_data(self, **kwargs):
pk = self.kwargs.get('pk')
context = super(CompanyDetails, self).get_context_data(**kwargs)
context['articles'] = Articles.objects.filter(company_id=pk).order_by('-date')
context['company'] = Company.objects.get(id=pk)
context['transcripts'] = Transcripts.objects.filter(company_id=pk).order_by('-date')
# Get Yahoo API data
stock_symbol = Company.objects.filter(id=pk).values_list('stock_symbol', flat=True)
data = Share(stock_symbol)
data = json.load(data)
context['mkt_cap'] = data
return context
编辑
这里是万一别人最后的代码也有类似的问题。我已将所有API调用保存在View中,并创建了一个字典以将它们传递给模板。
class CompanyDetails(generic.DetailView):
model = Company
template_name = 'company_details.html'
def get_context_data(self, **kwargs):
pk = self.kwargs.get('pk')
context = super(CompanyDetails, self).get_context_data(**kwargs)
context['articles'] = Articles.objects.filter(company_id=pk).order_by('-date')
context['transcripts'] = Transcripts.objects.filter(company_id=pk).order_by('-date')
# Get Yahoo API data
stock_symbol = self.object.stock_symbol
data = Share(stock_symbol)
stock_open = data.get_open()
year_range = data.get_year_range()
fifty_day_moving_average = data.get_50day_moving_avg()
market_cap = data.get_market_cap()
yahoo_finance = dict()
yahoo_finance['stock_open'] = stock_open
yahoo_finance['year_range'] = year_range
yahoo_finance['fifty_day_moving_average'] = fifty_day_moving_average
yahoo_finance['market_cap'] = market_cap
context['yahoo_finance'] = yahoo_finance
return context
然后在模板中访问这些我类似用途如下:
{{ yahoo_finance.stock_open }}
{{ yahoo_finance.year_range }}
{{ yahoo_finance.fifty_day_moving_average }}
{{ yahoo_finance.market_cap }}
完美,这就是我一直在寻找的。传递数据对象然后调用模板中的API是我不知道我可以做的额外奖励。我更喜欢在View中保留API请求,但是我只是创建了一个字典来添加其他请求。 – pheeper