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

相关文章

Python中生成一个指定长度的随机字符串实现示例

方法一: 定义一个函数,参数为所要生成随机字符串的长度。通过random.randint(a, b)方法得到随机数字,具体函数如下: def generate_random_str(...

python 列表删除所有指定元素的方法

如下所示: a = [1,1,1,2,3,45,1,2,1] a.remove(1) result: [1,1,2,3,45,1,2,1] while 1 in a: a.rem...

Python中Collections模块的Counter容器类使用教程

Python中Collections模块的Counter容器类使用教程

1.collections模块 collections模块自Python 2.4版本开始被引入,包含了dict、set、list、tuple以外的一些特殊的容器类型,分别是: Order...

Python使用PIL模块生成随机验证码

Python生成随机验证码,需要使用PIL模块,具体内容如下 安装: pip3 install pillow 基本使用 1. 创建图片 from PIL import Ima...

编写同时兼容Python2.x与Python3.x版本的代码的几个示例

编写兼容Python2.x与3.x代码 当我们正处于Python 2.x到Python 3.x的过渡期时,你可能想过是否可以在不修改任何代码的前提下能同时运行在Python 2和3中。这...