[英]Python: CGI program wants to know the IP address of the calling web page
我是 Python 編程的新手。
我堅持應該是一個簡單的程序。 我有一個小而基本的 Python 程序,它被 web 頁面稱為 CGI 程序。
我要做的就是從 HTTP header 字段中提取 IP 地址。 例如,在 PHP 中,這將是$_SERVER['REMOTE_ADDR']
的值。
我通過搜索支付了會費,發現我需要使用 web.ctx.ip,但是當我在代碼中使用該位時,出現了異常。 我可能需要導入一些東西。 我嘗試了以下單獨的導入但沒有成功:
import web
import webapi as web
我很感激一個完整的代碼片段,它演示了我需要導入的內容。 我的 Python CGI 程序正在 Linux 盒子上運行,該盒子安裝了基本的 Python 版本 2.4.3。 我需要安裝其他東西嗎?
從這里:
# When run as a cgi script, this will print the client's IP address.
import html
import os
print("Content-type: text/html")
print("")
print html.escape(os.environ["REMOTE_ADDR"])
搜索“python cgi get ip address”,這是第一個結果。 這個答案適用於通用 Python CGI,如果您使用的是其他接口/庫,那么它可能會有所不同。 然而,正如您所見,它與 PHP 版本完全相同。
上面的例子對我很有用。 我為本地測試添加了一些額外的內容。 找了很久才找到這個例子,所以“謝謝!”
import cgi
import os
def f_get_ipaddress():
try:
ipaddress = cgi.escape(os.environ["REMOTE_ADDR"])
except:
ipaddress = "127.0.0.1"
return ipaddress
print "Content-type: text/html"
print ""
ipaddress = f_get_ipaddress()
print ipaddress
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.