1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Streamlitアプリへのアクセスがモバイル端末からかどうか調べる

Last updated at Posted at 2025-08-30

Streamlitとは

StreamlitはPython向けのWebアプリケーションフレームワークです。

Streamlitを使うとPythonオンリーでWebアプリケーションを作成できるのが特徴です。特にPandasなどと組み合わせたデータアプリケーションを得意としています。また、最近ではLLMアプリケーションのフロントエンドとしても活用されています。

Streamlitアプリはモバイル端末からでも使える

Streamlitで作成したWebアプリケーションは特に工夫することなくモバイル端末から使えます。
とはいえ、モバイル端末からアクセスしたときは表示する内容を少しカスタマイズしてあげたいなーということも稀にあるので、アクセスがモバイル端末からかどうか調べてみましょう!

実装方法

将来的にはUser-Agent Client Hints(CH)がモバイル端末のアクセスを識別する方法として普及しそうですが、残念ながら素のStreamlitだとこれはまだ取得できないようです。
ということで、昔ながらのUser-Agentから判別する方法を試しましょう。
Streamlitではバージョン1.37.0以降であればst.context.headersでUser-Agentを取得することができます。

サンプルコードは以下の通りです。

check_mobile.py
import streamlit as st

# ユーザーエージェントに基づいてモバイル端末かどうかを判定する関数
# 判定に失敗した場合はif_failedの値を返す。デフォルトはFalse
def st_is_mobile(if_failed=False):
    if st.context:
        headers = st.context.headers
        user_agent_string = headers.get("User-Agent", "")
        if not user_agent_string:
            return if_failed
        ua = user_agent_string.lower()
        # 以下、典型的なパターンごとに判定していく
        if 'iphone' in ua:
            return True
        if 'android' in ua and 'mobile' in ua:
            return True
        if 'windows phone' in ua:
            return True
        if 'blackberry' in ua:
            return True
    else:
        return if_failed
    return False

st.set_page_config(page_title="テストアプリ", layout="wide")

is_mobile = st_is_mobile()
if is_mobile:
    st.markdown("## モバイル端末でアクセスしています。")
    st.image("img/vertical_image.jpg")
else:
    st.markdown("## デスクトップ端末でアクセスしています。")
    st.image("img/horizontal_image.jpg")

st.write(st.context.headers)

動作例

デスクトップからアクセスした場合

正常に動作しているようです。

PC

開発者ツールでモバイル端末をシミュレートするとこんな感じに。

PC+Mobile Option

Androidからアクセスした場合

Chromeを使って試してみると、これも正常に動作しているようです。

Android

Chromeのメニューから「PC版サイト」をオンにするとこんな感じに。

Android+PC Option

iPhoneからアクセスした場合

Safariを使って試してみると、これも正常に動作しているようです。

iPhone

ちなみに

st.contextが使えない場合、streamlit-browser-engineという拡張をインストールするとUser-Agentが取得できるようです。
Streamlitの実行環境は今ではほとんどがバージョン1.37.0以上になっているので、今後使うことはあまりないかな?という印象。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?