我正在尝试运行一个协程,该协程通过单击按钮获取数据。它用于aiohttp
获取数据。该按钮装饰有@asyncSlot()
fromqasync
但是,当我单击该按钮时,没有任何反应,甚至没有打印语句。我认为 asyncio 示例与我的用例不匹配。我尝试在 asyncio 运行时移动,看看是否有帮助。我有点困惑,因为我没有遇到任何错误。为什么我的函数没有运行?
我的代码:
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.container = QWidget() # Controls container widget.
self.controlsLayout = QVBoxLayout()
# -- Search bar and settings button
self.search_layout = QHBoxLayout()
self.search_bar = QLineEdit()
self.search_button = QPushButton("Search")
self.search_button.clicked.connect(self.update_data) # search by entered text
self.search_layout.addWidget(self.search_button)
self.controlsLayout.addLayout(self.search_layout)
# Our tab container with adjustable number of tabs
self.tab_container = TabContainer()
# Add out tabs widget
self.controlsLayout.addWidget(self.tab_container)
self.container.setLayout(self.controlsLayout)
self.setCentralWidget(self.container
@asyncSlot()
async def update_data(self):
stock_tickers = self.search_bar.text()
print("Entered tickers: ", stock_tickers)
short_interest = asyncio.create_task(self.setup_data(stock))
short_interest = await short_interest
print('SHORT INTEREST:', short_interest)
# Make a table in a new tab here
# ..............................
async def setup_data(self, stock):
short_interest = await get_data(stock) # this function is our main coroutine
# process the data here ...... as previous method return json
async def main():
app = QApplication(sys.argv)
loop = qasync.QEventLoop(app)
asyncio.set_event_loop(loop)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec())
if __name__ == '__main__':
asyncio.run(main())
其中 my get_data(stock)
,我们可以将其视为基本的 aiohttp json 调用,定义为
async def get_data(stock_ticker):
async with aiohttp.ClientSession() as session:
async with session.get('https://www.finra.org/finra-data/browse-catalog/equity-short-interest/data') as response:
cfruid = session.cookie_jar.filter_cookies('https://www.finra.org/')["__cfruid"].value
print("CFRUID", cfruid)
five_months_date = date.today() + relativedelta(months=-5)
headers = {
'authority': 'services-dynarep.ddwa.finra.org',
'accept': 'application/json, text/plain, */*',
'accept-language': 'en-US,en;q=0.6',
'content-type': 'application/json',
'cookie': f'XSRF-TOKEN={cfruid};',
'origin': 'https://www.finra.org',
'referer': 'https://www.finra.org/',
'x-xsrf-token': cfruid,
}
json_data = {
'fields': [
'settlementDate',
'issueName',
'symbolCode',
'marketClassCode',
'currentShortPositionQuantity',
'previousShortPositionQuantity',
'changePreviousNumber',
'changePercent',
'averageDailyVolumeQuantity',
'daysToCoverQuantity',
'revisionFlag',
],
'dateRangeFilters': [],
'domainFilters': [],
'compareFilters': [
{
'fieldName': 'symbolCode',
'fieldValue': 'GME',
'compareType': 'EQUAL',
},
{
'fieldName': 'settlementDate',
'fieldValue': str(five_months_date),
'compareType': 'GREATER',
},
],
'multiFieldMatchFilters': [],
'orFilters': [],
'aggregationFilter': None,
'sortFields': [
'-settlementDate',
'+issueName',
],
'limit': 50,
'offset': 0,
'delimiter': None,
'quoteValues': False,
}
async with session.post('https://services-dynarep.ddwa.finra.org/public/reporting/v2/data/group/OTCMarket/name/ConsolidatedShortInterest',
headers=headers, json=json_data) as response2:
short_interest_data = await response2.json()
return short_interest_data
通过创建任务并等待它,我能够让协程工作并在自己的文件中返回数据。我也尝试使用loop
替代。我缺少什么?请注意,其他常规方法在单击按钮时起作用,因此我知道这只是 asyncio 拒绝运行。
编辑:它似乎挂在aiohttp
未运行我的打印语句的部分的开头get_data
使用 QThread 似乎有助于解决这个问题
我无法验证这是否完全正确,因为您的代码看起来不完整,但似乎经过此更正,您可以使用异步函数。