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 过滤错误log并导出的实例

前言: 测试过程中获取App相关log后,如何快速找出crash的部分,并导出到新的文件呢? 感兴趣的话,继续往下看吧~ 思路:遍历多个日志文件,找出含有Error和Crash的日志,并...

Python列表删除的三种方法代码分享

1、使用del语句删除元素 >>> i1 = ["a",'b','c','d'] >>> del i1[0] >>> pri...

python读取图片并修改格式与大小的方法

本文实例为大家分享了python读取图片并修改文件大小的具体代码,供大家参考,具体内容如下 # Author:NDK # -*- coding:utf-8 -*- from PIL...

Python正则表达式教程之三:贪婪/非贪婪特性

之前已经简单介绍了Python正则表达式的基础与捕获,那么在这一篇文章里,我将总结一下正则表达式的贪婪/非贪婪特性。  贪婪 默认情况下,正则表达式将进行贪婪匹配。所谓“贪婪”...

Python 循环终止语句的三种方法小结

在Python循环终止语句有三种: 1、break break用于退出本层循环 示例如下: while True: print "123" break print "45...