在python vi中检测移动浏览器(不仅仅是iPhone)

2024-06-08 13:07:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用Django编写的web应用程序,它有一个特定的页面,我想实现模板的移动版本(和稍微不同的逻辑)。我希望能够实现这个sudo代码:

def(myView)

  do some stuff

  if user-is-on-a-mobile-device:
     do some stuff
     return (my mobile template)

  else:
     do some stuff
     return (my normal template)

我没有太多的时间,而且我很早就开始了我的编码学习曲线:)-我发现了一个看起来非常强大的可插拔应用程序,名为bloom,用于获取移动设备功能-http://code.google.com/p/django-bloom/wiki/BloomDevice 不过,它似乎通过JSON发出了一个请求,以获得许多我不需要的设备规格,这对我来说似乎有点低效。

有人建议用更简单的方法吗?我的检测不需要100%,只需要iPhone、iPod、android和主流设备。。。

http_user_代理字符串是否有某种可供我检查的移动标志?


Tags: django模板web应用程序httpreturnmytemplate
3条回答

更新:

我刚发现:http://code.google.com/p/minidetector/

这似乎正是我想要的,我现在要测试。你可以告诉我我错了!

找一个叫做django mobi的小型侦探分支,它包含了如何使用它的文档。

https://pypi.python.org/pypi/django-mobi

最佳实践:使用minidetector将额外信息添加到请求中,然后使用django的内置请求上下文将其像这样传递给模板。

from django.shortcuts import render_to_response
from django.template import RequestContext

def my_view_on_mobile_and_desktop(request)
    .....
    render_to_response('regular_template.html', 
                       {'my vars to template':vars}, 
                       context_instance=RequestContext(request))

然后在模板中,您可以介绍如下内容:

<html>
  <head>
  {% block head %}
    <title>blah</title>
  {% if request.mobile %}
    <link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-mobile.css">
  {% else %}
    <link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-desktop.css">
  {% endif %}
  </head>
  <body>
    <div id="navigation">
      {% include "_navigation.html" %}
    </div>
    {% if not request.mobile %}
    <div id="sidebar">
      <p> sidebar content not fit for mobile </p>
    </div>
    {% endif %>
    <div id="content">
      <article>
        {% if not request.mobile %}
        <aside>
          <p> aside content </p>
        </aside>
        {% endif %}
        <p> article content </p>
      </aricle>
    </div>
  </body>
</html>

相关问题 更多 >