AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 77032964
Accepted
David Frick
David Frick
Asked: 2023-09-03 23:24:00 +0800 CST2023-09-03 23:24:00 +0800 CST 2023-09-03 23:24:00 +0800 CST

在 Pyside6 中单击按钮时协程不会运行

  • 772

我正在尝试运行一个协程,该协程通过单击按钮获取数据。它用于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

python
  • 1 1 个回答
  • 32 Views

1 个回答

  • Voted
  1. Best Answer
    Sepu Ling
    2023-09-04T00:21:28+08:002023-09-04T00:21:28+08:00

    使用 QThread 似乎有助于解决这个问题

    class DataWorker(QThread):
        data_ready = Signal(dict)
    
        def __init__(self, stock_ticker):
            super().__init__()
            self.stock_ticker = stock_ticker
    
        async def get_data(self):
            async with aiohttp.ClientSession() as session:
                # ... Your existing async code to fetch data ...
            self.data_ready.emit(short_interest_data)
    
        def run(self):
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            loop.run_until_complete(self.get_data())
    class MainWindow(QMainWindow):
        # your existing code
        def update_data(self):
            stock_ticker = self.search_bar.text()
            print("Entered tickers: ", stock_ticker)
    
            self.data_worker = DataWorker(stock_ticker)
            self.data_worker.data_ready.connect(self.setup_data)
            self.data_worker.start()
    # other codes
    def main():
        app = QApplication(sys.argv)
        main_window = MainWindow()
        main_window.show()
        sys.exit(app.exec_())
    
    if __name__ == '__main__':
        main()
    

    我无法验证这是否完全正确,因为您的代码看起来不完整,但似乎经过此更正,您可以使用异步函数。

    • 2

相关问题

  • 如何将 for 循环拆分为 3 个单独的数据框?

  • 如何检查 Pandas DataFrame 中的所有浮点列是否近似相等或接近

  • “load_dataset”如何工作,因为它没有检测示例文件?

  • 为什么 pandas.eval() 字符串比较返回 False

  • Python tkinter/ ttkboostrap dateentry 在只读状态下不起作用

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    使用 <font color="#xxx"> 突出显示 html 中的代码

    • 2 个回答
  • Marko Smith

    为什么在传递 {} 时重载解析更喜欢 std::nullptr_t 而不是类?

    • 1 个回答
  • Marko Smith

    您可以使用花括号初始化列表作为(默认)模板参数吗?

    • 2 个回答
  • Marko Smith

    为什么列表推导式在内部创建一个函数?

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 个回答
  • Marko Smith

    为什么 'char -> int' 是提升,而 'char -> Short' 是转换(但不是提升)?

    • 4 个回答
  • Marko Smith

    为什么库中不调用全局变量的构造函数?

    • 1 个回答
  • Marko Smith

    std::common_reference_with 在元组上的行为不一致。哪个是对的?

    • 1 个回答
  • Marko Smith

    C++17 中 std::byte 只能按位运算?

    • 1 个回答
  • Martin Hope
    fbrereto 为什么在传递 {} 时重载解析更喜欢 std::nullptr_t 而不是类? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 您可以使用花括号初始化列表作为(默认)模板参数吗? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi 为什么列表推导式在内部创建一个函数? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A fmt 格式 %H:%M:%S 不带小数 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python C++20 的 std::views::filter 未正确过滤视图 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute 为什么 'char -> int' 是提升,而 'char -> Short' 是转换(但不是提升)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa 为什么库中不调用全局变量的构造函数? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis std::common_reference_with 在元组上的行为不一致。哪个是对的? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev 为什么编译器在这里错过矢量化? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan C++17 中 std::byte 只能按位运算? 2023-08-17 17:13:58 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve