在 Python 中获取标头变量

Posted

技术标签:

【中文标题】在 Python 中获取标头变量【英文标题】:Grab header variable in Python 【发布时间】:2012-11-23 09:37:37 【问题描述】:

我正在尝试在 nginx 上使用 geoip 模块,并且我认为我已经正确设置了所有内容,但我的问题是我正在使用的教程是 php 并且我正在使用 Python Flask。

这是PHP:

<html>
<head>
  <title>What is my IP address - determine or retrieve my IP address</title>
 </head>
<body>
 <?php
     $country_code = getenv(GEOIP_COUNTRY_CODE);
    echo "<br/>Your country : $country_code";
?>
</body>
</html>

特别是这一行:

$country_code = getenv(GEOIP_COUNTRY_CODE);

做同样事情的等效 Python 代码是什么?如果有帮助,这是我正在学习的教程:LINK

【问题讨论】:

在不知道您如何运行 Python 应用程序的情况下无法回答。你在使用框架吗?电脑动画? WSGI?什么? 是的,上面说了,python 烧瓶在 nginx 上运行。我不是说我通过 UWSGI 运行它,但我认为这不相关 【参考方案1】:

等效的 python/flask 代码可以是:

from flask import request
country_code = request.environ.get('GEOIP_COUNTRY_CODE')

【讨论】:

【参考方案2】:

你需要有一个视图,带有一个模板,例如:

request.environ 将从 WSGI 环境中获取值

你的看法:

@app.route('/show-country-code/')
def get_my_ip():
    return render_template('show-country-code.html', country_code=request.environ['the_name_of_the_var'])

你的show-country-code.html

<html>
<head>
  <title>What is my IP address - determine or retrieve my IP address</title>
 </head>
<body>
    <p>Your country code is:  country_code </p>
</body>
</html>

【讨论】:

以上是关于在 Python 中获取标头变量的主要内容,如果未能解决你的问题,请参考以下文章