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程序设计有所帮助。

相关文章

wxPython实现绘图小例子

wxPython实现绘图小例子

本文实例为大家分享了wxPython绘图小例子的具体实现代码,供大家参考,具体内容如下 一个绘图的例子: #!/usr/bin/env python # -*- coding: ut...

Python使用函数默认值实现函数静态变量的方法

本文实例展示了Python使用函数默认值实现函数静态变量的方法,具体方法如下: 一、Python函数默认值 Python函数默认值的使用可以在函数调用时写代码提供方便,很多时候我们只要使...

详解Python基础random模块随机数的生成

随机数参与的应用场景大家一定不会陌生,比如密码加盐时会在原密码上关联一串随机数,蒙特卡洛算法会通过随机数采样等等。Python内置的random模块提供了生成随机数的方法,使用这些方法时...

python多个模块py文件的数据共享实例

模块a.py 想用 b.py中公有数据 cnt b的python文件 #!/usr/bin/env python # coding:utf8 from wx import Cal...

Python获取统计自己的qq群成员信息的方法

Python获取统计自己的qq群成员信息的方法

首先说明一下需要使用的工具以及技术:python3 + selenium selenium安装方法:pip install selenium 前提:获取自己的qq群成员信息,自己必须是群...