蛇使いな彼女BLOG
【第130回】非同期処理とFletアプリのその後~asyncioタイムアウト成功とWindows11のビルド方法~
2025.06.06

環境システム モトハシです。
あれから数日粘った結果、fletアプリを起動している状態でのみ、asyncioが正常に起動していることが確認できました!!(どうやらイベントループでしかasyncioが使えないという事だったみたいです!)
そしてタイムアウト処理の方法は、
通常の関数に非同期処理によるコントロールを追加したい場合、
def ⇒ async def の書き換えに加え "await asyncio.sleep"の一行を任意の場所に追加するだけでOKでした💡
class data_request(): def __init__(self,list,time_1,time_2): ・・・(省略) async def exe(self,): for i in range(0,self.Days+1): key=self.start_date+dt.timedelta(days=i) url="{}{}&block_no={:04}&year={}&month={}&day={}&view=".format(self.URL,self.prec,self.block,key.year,key.month,key.day) with urllib.request.urlopen(url) as response: r= response.read() # Read HTML soup =bs4.BeautifulSoup(r, 'html.parser') try: context = soup.find("table",{ "class" : "data2_s" }) tab=[] for row in context.find_all('tr'): cells=row.find_all('td') if len(cells) == 0: continue tab.append([cell.get_text() for cell in cells]) ・・・(省略) await asyncio.sleep(0.1) except AttributeError as error: print('loop Index: {}\n{}'.format(key,error)) await asyncio.sleep(0.1) return self.result.values
async def SELECTED_TAB(select): if select == 0: ・・・(省略) # Wait until scraping is finished task = asyncio.wait_for(inst.exe(), timeout=60) # 60秒でタイムアウト try: task_result = await task View.controls[2].content.controls.pop() temporary['result']=task_result temporary['columns']=inst.cols Notification.content.value='The data extraction process is complete.' Notification.bgcolor=ft.Colors.CYAN_300, page.open(Notification) page.update() except asyncio.TimeoutError: print("タスクがタイムアウトしました") View.controls[2].content.controls.pop() temporary['result']=None temporary['columns']=inst.cols Notification.content.value='Timeout expired.\nPlease shorten the date range.' Notification.bgcolor=ft.Colors.PINK_300 page.open(Notification) page.update()
上記に書き換えた状態で実行すると、ケースバイケースでこのような結果が返ってきます。

loop Index: 2025-05-07 00:00:00
'NoneType' object has no attribute 'find_all'
0
タスクがタイムアウトしました
>>>
60秒のタイムアウトはネット環境にも左右されますが、モトハシが試したところ、スクレイピングの有効日付範囲としては大体3か月程度となります。
データ取得10分間隔 ⇒ 90日×24時間×6=12960回/60秒
この場合、1秒あたり216回データを取りに行ってる計算となり、1回のループにかかる時間は約0.0046秒です。
asyncio.sleep(0.1)なので、本来ループ1回あたり0.1秒のスリープとなるはずですが、0.0046秒しか掛かっていないことから非同期状態と同期状態の時間の流れは違う動きをしていることが分かります。
ちなみに、どうしてスリープさせるのか?
この理由について、基本的にasyncio.sleep(またはtime.sleep)はサーバー上の処理の負荷を軽減する意味があるとのことです。
目安としてスリープ時間はだいたい1秒~3秒程度らしいですが、
今回の例では、1秒にしてしまうと一度に取得できるデータ範囲が1か月程度となってしまうため、
利便性の面から0.1秒としました。
実際はもっとスリープ時間を長くしたほうがよさそうです。
このように、開発者としては使う側の快適さと、サーバーや他の利用者の権利の両方考えなくてはいけないという事ですね💦
flet0.27+Windows11+Python3.9.21 conda 環境によるビルド
最後に出来上がったアプリケーションのビルドですが、最新のflet 0.27.6 (-2025.05.07現在)とWindows11およびPython3.9.21と相性が悪い(?)ようで、
ビルドに成功してもOSや依存関係が原因でアプリの実行エラーになってしまいました。
requirements.txtの追加やWindows Defenderの設定を変えても改善しなかったのですが、fletのバージョンを 0.27.5にダウングレードすることで正常にアプリが立ち上がることが分かりました!!
その時の実際のログとpyproject.toml、requirements.txtを記述しておきます。
[project] name = "myapp" version = "0.1.0" description = "" readme = "README.md" requires-python = ">=3.9" authors = [ { name = "Flet developer", email = "you@example.com" } ] dependencies = [ "flet[all]>=0.27.5", "flet_map==0.1.0", "certifi", "pandas", ] [tool.flet] # org name in reverse domain name notation, e.g. "com.mycompany". # Combined with project.name to build bundle ID for iOS and Android apps org = "com.mycompany" # project display name that is used as an app title on Android and iOS home screens, # shown in window titles and about app dialogs on desktop. product = "KOOTA" # company name to display in about app dialogs company = "Flet" # copyright text to display in about app dialogs copyright = "Copyright (c) 2025 hydrolab.com" [tool.flet.app] path = "src" [tool.uv] dev-dependencies = [ "flet[all]>=0.27.5", ] [tool.poetry] package-mode = false [tool.poetry.group.dev.dependencies] flet = {extras = ["all"], version >= "0.27.5"}
flet==0.27.5 flet_map==0.1.0 beautifulsoup4==4.13.4 numpy==2.* pandas== 2.* certifi==2025.1.31
(python39) PS C:\Users\motoh\source\repos\flet\myapp\src> flet build windows -v
[13:41:07] Ensure Flutter has desktop support enabled
Run subprocess: ['C:\\Users\\motoh\\flutter\\3.27.4\\bin\\flutter.bat', 'config', '--no-version-check',
'--suppress-analytics', '--enable-windows-desktop']
Setting "enable-windows-desktop" value to "true".
You may need to restart any open editors for them to read new settings.
Flutter 3.27.4 installed ✅
Flutter executable: C:\Users\motoh\flutter\3.27.4\bin\flutter.bat
Dart executable: C:\Users\motoh\flutter\3.27.4\bin\dart.bat
Run subprocess: ['C:\\Users\\motoh\\flutter\\3.27.4\\bin\\dart.bat', 'run', '--suppress-analytics',
'serious_python:main', 'package', 'C:\\Users\\motoh\\source\\repos\\flet\\myapp\\src', '--platform',
'Windows', '--requirements', '-r,C:\\Users\\motoh\\source\\repos\\flet\\myapp\\src\\requirements.txt',
'--exclude', 'build', '--cleanup-packages', '--skip-site-packages']
Running package command
Extra PyPi indexes: [https://pypi.flet.dev]
Created temp directory: C:\Users\motoh\AppData\Local\Temp\serious_python_temp43c829c0
Copying Python app from C:\Users\motoh\source\repos\flet\myapp\src to a temp directory
Creating app archive at C:\Users\motoh\source\repos\flet\myapp\src\build\flutter\app/app.zip from a temp
directory
Writing app archive hash to C:\Users\motoh\source\repos\flet\myapp\src\build\flutter\app/app.zip.hash
Deleting temp directory
Packaged Python app ✅
Found "icon" image at C:\Users\motoh\source\repos\flet\myapp\src\assets\icon.png
Run subprocess: ['C:\\Users\\motoh\\flutter\\3.27.4\\bin\\flutter.bat', 'build', 'windows',
'--no-version-check', '--suppress-analytics']
[13:41:08]
[13:41:21] Building Windows application... 12.8s
√ Built build\windows\x64\runner\Release\src.exe
Built Windows app ✅
Copying build output from:
C:\Users\motoh\source\repos\flet\myapp\src\build\flutter\build\windows\x64\runner\Release\*
[13:41:45] Copied build to build\windows directory ✅
╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ Successfully built your Windows app! 🥳 Find it in build\windows directory. 📁 │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
(python39) PS C:\Users\motoh\source\repos\flet\myapp\src> flet build windows -v
[13:42:52] Ensure Flutter has desktop support enabled
Run subprocess: ['C:\\Users\\motoh\\flutter\\3.27.4\\bin\\flutter.bat', 'config', '--no-version-check',
'--suppress-analytics', '--enable-windows-desktop']
Setting "enable-windows-desktop" value to "true".
You may need to restart any open editors for them to read new settings.
Flutter 3.27.4 installed ✅
Flutter executable: C:\Users\motoh\flutter\3.27.4\bin\flutter.bat
Dart executable: C:\Users\motoh\flutter\3.27.4\bin\dart.bat
[13:42:58] Created Flutter bootstrap project from gh:flet-dev/flet-build-template with ref "0.27.5" ✅
Run subprocess: ['C:\\Users\\motoh\\flutter\\3.27.4\\bin\\dart.bat', 'run', '--suppress-analytics',
'serious_python:main', 'package', 'C:\\Users\\motoh\\source\\repos\\flet\\myapp\\src', '--platform',
'Windows', '--requirements', '-r,C:\\Users\\motoh\\source\\repos\\flet\\myapp\\src\\requirements.txt',
'--exclude', 'build', '--cleanup-packages']
[13:43:01] Running package command
Extra PyPi indexes: [https://pypi.flet.dev]
Creating asset directory: C:\Users\motoh\source\repos\flet\myapp\src\build\flutter\app
Created temp directory: C:\Users\motoh\AppData\Local\Temp\serious_python_tempce138fa7
Copying Python app from C:\Users\motoh\source\repos\flet\myapp\src to a temp directory
Configured Windows/ platform with sitecustomize.py
Installing [-r, C:\Users\motoh\source\repos\flet\myapp\src\requirements.txt] with pip command to
C:\Users\motoh\source\repos\flet\myapp\src\build\site-packages
Downloading Python distributive from
https://github.com/astral-sh/python-build-standalone/releases/download/20250205/cpython-3.12.9+20250205-x86_6
4-pc-windows-msvc-shared-install_only_stripped.tar.gz to a build directory
[13:43:06] Extracting Python distributive
[13:43:52] Copying Flutter packages to C:\Users\motoh\source\repos\flet\myapp\src\build\flutter-packages-temp
Cleanup installed packages
[13:43:53] Creating app archive at C:\Users\motoh\source\repos\flet\myapp\src\build\flutter\app/app.zip from a temp
directory
Writing app archive hash to C:\Users\motoh\source\repos\flet\myapp\src\build\flutter\app/app.zip.hash
Deleting temp directory
Packaged Python app ✅
Found Flutter extension at C:\Users\motoh\source\repos\flet\myapp\src\build\flutter-packages\flet_map
Registered Flutter user extensions ✅
[13:43:58] Found "icon" image at C:\Users\motoh\source\repos\flet\myapp\src\assets\icon.png
Copying image C:\Users\motoh\source\repos\flet\myapp\src\assets\icon.png to
C:\Users\motoh\source\repos\flet\myapp\src\build\flutter\images
Customized app icons ✅
Run subprocess: ['C:\\Users\\motoh\\flutter\\3.27.4\\bin\\dart.bat', 'run', '--suppress-analytics',
'flutter_launcher_icons']
[13:44:07] ════════════════════════════════════════════
FLUTTER LAUNCHER ICONS (v0.14.3)
════════════════════════════════════════════
• Creating default icons Android
• Overwriting the default Android launcher icon with a new icon
• Creating adaptive icons Android
• No colors.xml file found in your Android project
• Creating colors.xml file and adding it to your Android project
• Creating mipmap xml file Android
• Overwriting default iOS launcher icon with new icon
[13:44:08] Creating Icons for Web...
Creating Icons for Windows...
Creating Icons for MacOS...
[13:44:09]
✓ Successfully generated launcher icons
Generated app icons ✅
Run subprocess: ['C:\\Users\\motoh\\flutter\\3.27.4\\bin\\flutter.bat', 'build', 'windows',
'--no-version-check', '--suppress-analytics']
[13:44:10] Resolving dependencies...
Downloading packages...
archive 3.6.1 (4.0.7 available)
characters 1.3.0 (1.4.0 available)
clock 1.1.1 (1.1.2 available)
collection 1.19.0 (1.19.1 available)
device_info_plus 11.3.0 (11.4.0 available)
ffi 2.1.3 (2.1.4 available)
file_picker 8.3.7 (10.1.2 available)
fl_chart 0.69.2 (0.71.0 available)
! flet 0.27.5 (overridden) (0.27.6 available)
flutter_lints 2.0.3 (5.0.0 available)
flutter_map 7.0.2 (8.1.1 available)
flutter_map_animations 0.8.0 (0.9.0 available)
flutter_map_cancellable_tile_provider 3.0.2 (3.1.0 available)
flutter_native_splash 2.4.4 (2.4.6 available)
image 4.3.0 (4.5.4 available)
intl 0.19.0 (0.20.2 available)
js 0.6.7 (0.7.2 available)
lints 2.1.1 (6.0.0 available)
material_color_utilities 0.11.1 (0.12.0 available)
meta 1.15.0 (1.16.0 available)
path 1.9.0 (1.9.1 available)
petitparser 6.0.2 (6.1.0 available)
sensors_plus 4.0.2 (6.1.1 available)
sensors_plus_platform_interface 1.2.0 (2.0.1 available)
serious_python 0.9.1 (0.9.2 available)
toml 0.15.0 (0.16.0 available)
unicode 0.3.1 (1.1.8 available)
url_strategy 0.2.0 (discontinued)
vector_math 2.1.4 (2.1.5 available)
! wakelock_plus 1.3.2 (overridden)
! web 1.1.1 (overridden)
web_socket_channel 2.4.5 (3.0.3 available)
! webview_flutter_android 4.4.2 (overridden)
win32 5.10.1 (5.12.0 available)
win32_registry 1.1.5 (2.1.0 available)
! window_manager 0.4.3 (overridden)
Got dependencies!
1 package is discontinued.
32 packages have newer versions incompatible with dependency constraints.
Try `flutter pub outdated` for more information.
[13:44:11]
windows/flutter/CMakeLists.txt does not use FLUTTER_TARGET_PLATFORM, updating.
[13:45:26] Building Windows application...
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.43.34808\include\format(42): warning
STL4038: The contents of <format> are available only with C++20 or later.
[C:\Users\motoh\source\repos\flet\myapp\src\build\flutter\build\windows\x64\plugins\serious_python_windows\se
rious_python_windows_plugin.vcxproj]
[13:45:35] Building Windows application... 84.3s
√ Built build\windows\x64\runner\Release\src.exe
Built Windows app ✅
Copying build output from:
C:\Users\motoh\source\repos\flet\myapp\src\build\flutter\build\windows\x64\runner\Release\*
[13:45:57] Copied build to build\windows directory ✅
╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ Successfully built your Windows app! 🥳 Find it in build\windows directory. 📁 │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
以上、参考になれば幸いです!
今回はここまでです♪