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中调试或排错的五种方法示例

python中调试或排错的五种方法示例

前言 本文主要给大家介绍了关于python中调试或排错的五种方法,分享出来供大家参考学习,下面话不多说了,来一起看看详细的的介绍吧 python调试或排错的五种方法 1、print,直接...

Python常用内置模块之xml模块(详解)

Python常用内置模块之xml模块(详解)

xml即可扩展标记语言,它可以用来标记数据、定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言。从结构上,很像HTML超文本标记语言。但他们被设计的目的是不同的,超文本标记语言...

python实现猜数字游戏(无重复数字)示例分享

复制代码 代码如下:import time, random class GuessNum:    def __init__(self): &nbs...

Python的多态性实例分析

本文实例讲述了Python的多态性。分享给大家供大家参考。具体如下: #!/usr/bin/env python # polymorphism in python # class b...

Python语言生成水仙花数代码示例

Python语言生成水仙花数代码示例

水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。 本文将通过Python代码实现打印水仙花数,具体如下: #水仙花数 #narcissist...