我是python和html的新手,我一直在尝试使用python(使用cgi)运行simplehttpserver。从这个服务器,我可以运行一个显示用户地理位置的location.py文件。我想把这个位置写在我的电脑上的文本文件中,但我不知道该怎么做。目前我的location.py实际上是一个由python加载的html5页面,但我不知道如何从我的页面中提取所需的信息。
P.S。这个的灵感是让我的iPhone和我的笔记本电脑共享相同的wifi网络(adhoc便携式热点),然后我的笔记本电脑使用我的iPhone在谷歌地球更准确的GPS。我最终想要写入一个kml文件,该文件不断更新我当前的lat和long。可能有更简单的方法来做到这一点,但我认为学习一点python会是一个好主意。
我的location.py文件
#!/python
print( "Content-type: text/html\n\n")
print( """\
<html>
<head>
<p id="demo">Test:</p>
<script>
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
window.onload = getLocation;
</script>
</head>
<body>
</body>
</html>""")
我的服务器文件(webserver.py)
import http.server
def main():
server_address = ("", 8000)
handler = http.server.CGIHTTPRequestHandler
handler.cgi_directories = ['/python']
server = http.server.HTTPServer(server_address, handler)
try:
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()
if __name__ == '__main__':
main()
答案 0 :(得分:1)
您需要使用该位置向服务器发送请求,然后在脚本上使用cgi.FielStorage
来获取数据。要发送请求,您必须稍微修改一下javascipt代码。
我向您展示了一个返回静态数据的示例(因为我的Pc:P上没有地理定位),您需要更改它以发送正确的 lat,lon 数据(可能在函数内部) showPosition
?)
接下来,更改你的python脚本(请检查javascript上还有chnages!):
#!/usr/bin/env python
import cgi
form = cgi.FieldStorage()
lat = form.getvalue('lat')
lon = form.getvalue('lon')
with open('location.txt','wt') as f:
if lat:
f.write(lat)
f.write("\n")
if lon:
f.write(lon)
f.close()
print( "Content-type: text/html\n\n")
print( """\
<html>
<head>
<p id="demo">Test:</p>
<script>
var x=document.getElementById("demo");
function getLocation()
{
//this is to send the location back to your python script
var req = new XMLHttpRequest();
req.open('GET', 'location.py?lat=1&lon=2', false);
req.send(null);
//----------------------------------------------
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
window.onload = getLocation;
</script>
</head>
<body>
</body>
</html>""")
如果您运行代码,您会在 location.txt 文件中看到您有代码。
当然,您可以在两个脚本上拆分流程(几乎可以肯定正确的方法!)并将请求发送到您的第二个脚本( save_location.py ?)。