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常用数据类型之间的转换总结

函数 描述 int(x [,base]) 将x转换为一个...

python下的opencv画矩形和文字注释的实现方法

画矩形 函数调用:cv2.rectangle(img,pt1,pt2,color,thickness,line_type,shift) img: 图像. pt1: 矩形的一个顶点。 pt...

深入理解Python中的内置常量

前言 大家都知道Python内置的常量不多,只有6个,分别是True、False、None、NotImplemented、Ellipsis、__debug__。下面就来看看详细的介绍:...

在Python 不同级目录之间模块的调用方法

Python的模块有自带的也有第三方,还可以自定义然后引用 1、调用自带的模块,例如,sys 调用自带的模块只需要import sys 引入既可以使用 2、第三方的需要先安装模块然后再i...

python字典的遍历3种方法详解

python字典的遍历3种方法详解

遍历字典: keys() 、values() 、items()   1. xxx.keys() : 返回字典的所有的key 返回一个序列,序列中保存有字典的所有的键   效果图:   ...