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中实现将多个print输出合成一个数组

比如有下面一段代码: for i in range(10): print ("%s" % (f_list[i].name)) 该代码段的执行,会生成如下的10行“name”属性...

Python实现优先级队列结构的方法详解

最简单的实现 一个队列至少满足2个方法,put和get. 借助最小堆来实现. 这里按"值越大优先级越高"的顺序. #coding=utf-8 from heapq import h...

Django + Uwsgi + Nginx 实现生产环境部署的方法

Django + Uwsgi + Nginx 实现生产环境部署的方法

如何在生产上部署Django? Django的部署可以有很多方式,采用nginx+uwsgi的方式是其中比较常见的一种方式。 uwsgi介绍 uWSGI是一个Web服务器,它实现...

Python中使用gzip模块压缩文件的简单教程

压缩数据创建gzip文件 先看一个略麻烦的做法   import StringIO,gzip content = 'Life is short.I use python'...

浅谈python中的面向对象和类的基本语法

浅谈python中的面向对象和类的基本语法

当我发现要写python的面向对象的时候,我是踌躇满面,坐立不安呀。我一直在想:这个坑应该怎么爬?因为python中关于面向对象的内容很多,如果要讲透,最好是用面向对象的思想重新学一遍前...