app.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import ipdb, ipaddress, requests, json
  2. from flask import Flask, request, render_template, jsonify
  3. from socket import gethostbyname
  4. db = ipdb.BaseStation("qqwry.ipdb")
  5. app = Flask(__name__)
  6. def iplocated(ip):
  7. city = db.find(ip, "CN")
  8. return ip + " @" + city[0] + city[1] + city[2] + city[3] + "\n"
  9. def getcity(ip):
  10. city = db.find(ip, "CN")
  11. return city[2] + '市'
  12. def getip():
  13. ip = request.remote_addr
  14. try:
  15. _ip = request.headers["X-Real-IP"]
  16. if _ip is not None:
  17. ip = _ip
  18. except Exception as e:
  19. print(e)
  20. return ip
  21. def is_Mozilla():
  22. # Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
  23. ua = request.headers["User-Agent"]
  24. if (ua.find("Mozilla") != -1):
  25. return True
  26. else:
  27. return False
  28. def ip2bdgps(ip):
  29. url = 'https://api.map.baidu.com/location/ip?ak=iUGOVyqGFo4QOP6QhTuZPF1P6FV5GB7p&coor=bd09ll&ip=' + ip
  30. r = requests.get(url)
  31. json_str = r.text
  32. data = json.loads(json_str)
  33. if data['status'] != 0 :
  34. return (116.39564504, 39.92998578 , data['status']) # 查不到返回 北京 x,y
  35. else:
  36. x = data['content']['point']['x']
  37. y = data['content']['point']['y']
  38. return (x, y, data['status'], data)
  39. @app.route("/")
  40. def hello():
  41. ip = getip()
  42. if is_Mozilla():
  43. return ip + render_template('hello.html', ip=ip) + "\n\n" + request.headers["User-Agent"]
  44. else:
  45. return ip
  46. @app.route("/ip/maps/")
  47. def maps():
  48. ip = getip()
  49. bdgps = ip2bdgps(ip)
  50. return render_template('maps.html', bdgps=bdgps)
  51. @app.route("/ip/")
  52. @app.route("/ip/<ipaddr>")
  53. def show_ip(ipaddr=None):
  54. # ip 地址为空获得浏览器客户端IP
  55. if ipaddr is None:
  56. ip = getip()
  57. ipaddr = iplocated(ip)
  58. if is_Mozilla():
  59. return render_template('hello.html', ip=ip, ipaddr=ipaddr, city=getcity(ip))
  60. else:
  61. return ip
  62. else:
  63. ip = ipaddr
  64. # ip地址 从纯真IP数据库 搜索城市定位
  65. try:
  66. ipaddress.ip_address(ip).is_global
  67. ipaddr = iplocated(ip)
  68. except:
  69. try:
  70. ip = gethostbyname(ip) # 域名反解析得到的IP
  71. ipaddr = iplocated(ip)
  72. except Exception as e:
  73. print(e)
  74. return ipaddr
  75. if __name__ == '__main__':
  76. app.run(host='0.0.0.0', debug=True)
  77. # export FLASK_ENV=development # 调试模式: 修改代码不用重启服务
  78. # flask run --host=0.0.0.0 # 监听所有公开的 IP