python使用Flask框架获取用户IP地址的方法

yipeiwu_com5年前Python基础

本文实例讲述了python使用Flask框架获取用户IP地址的方法。分享给大家供大家参考。具体如下:

下面的代码包含了html页面和python代码,非常详细,如果你正使用Flask,也可以学习一下最基本的Flask使用方法。

python代码如下:

from flask import Flask, render_template, request
# Initialize the Flask application
app = Flask(__name__)
# Default route, print user's IP
@app.route('/')
def index():
 ip = request.remote_addr
 return render_template('index.html', user_ip=ip)
if __name__ == '__main__':
 app.run(
    host="0.0.0.0",
    port=int("80")
 )

html代码如下:

<!DOCTYPE html>
<html lang="en">
 <head>
  <link href="bootstrap/3.0.0/css/bootstrap.min.css"
     rel="stylesheet">
 </head>
 <body>
  <div class="container">
   <div class="header">
    <h3 class="text-muted">How To Get The IP Address Of The User</h3>
   </div>
   <hr/>
   <div>
    You IP address is: <strong>{{user_ip}}</strong>
  <div class="header">
    <h3 class="text-muted">Code to retrieve the IP</h3>
   </div>
   <hr/>  
<pre>
from flask import Flask, render_template, request
# Initialize the Flask application
app = Flask(__name__)
# Default route, print user's IP
@app.route('/')
def index():
 ip = request.remote_addr
 return render_template('index.html', user_ip=ip)
</pre>
   </div>
  </div>
 </body>
</html>

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Windows下python3.6.4安装教程

Windows下python3.6.4安装教程

Windows下python3.6.4安装教程的详细过程,供大家参考,具体内容如下 步骤: 下包—>安装—->添加环境变量—–>测试 1、下包 Python安装包下载...

python利用elaphe制作二维条形码实现代码

手机上的二维码识别程序已经做的很好了,“我查查”用起来很不错的 我搜集了几个二维条码生成网站: http://www.morovia.com/free-online-barcode-ge...

为Python的Tornado框架配置使用Jinja2模板引擎的方法

tornado 默认有一个模板引擎但是功能简单(其实我能用到的都差不多)使用起来颇为麻烦, 而jinja2语法与django模板相似所以决定使用他. 下载jinja2 还是用pip 下载...

Python IDLE清空窗口的实例

使用Python IDLE时发现并没有清空当前窗口的快捷键,也没有像 clear 这样的命令,使用非常不便。 新建一个 ClearWindow.py脚本,源码如下: """ Cle...

Python基础之高级变量类型实例详解

Python基础之高级变量类型实例详解

本文实例讲述了Python高级变量类型。分享给大家供大家参考,具体如下: 目标 列表 元组 字典 字符串 公共方法 变量高级 知识点回顾 Python 中数据类型...