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

Tri*_*ton 32 python django mobile user-agent

我有一个用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)
Run Code Online (Sandbox Code Playgroud)

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

有没有人建议更简单的方法?我的检测不需要100%,只需iPhone,iPod,Android和主流设备......

http_user_agent字符串是否有某种我可以检查的移动标记?

Tri*_*ton 19

更新:

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

这似乎完全符合我的要求,我现在要进行测试.随意告诉我,我错了!

  • 该项目是最新的吗?它自2010年12月以来没有发生过变化.我使用的是https://github.com/shelfworthy/minidetector,因为它是积极开发的.不幸的是,作者只是告诉我它不再受支持了,他的意思是删除那个github仓库所以我正在寻找替代品. (2认同)

Tho*_*mas 15

最佳实践:使用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))
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)


小智 7

去寻找django-mobi的minidetecor的分支,它包括如何使用它的文档.

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