视图中的数据输出到控制台而不是网页(flask - python)
我正在尝试从一个GTFS数据源获取一些数据。目前我还没搞明白怎么打开这个数据源并把内容保存到本地。现在我有一个Flask应用,代码如下:
def mta():
data = urllib2.urlopen('http://addresshere.php?key=keyvaluehere')
response = data.read()
print response
@app.route('/')
def index():
test = mta()
return render_template("index.html",
test = test,
title = "Home")
当我启动服务器时,信息显示在控制台上,而不是我的浏览器里,并且在index.html模板中出现了“None”的消息。
我用PHP做了个简单的测试,使用get_file_contents()成功获取了一些信息,虽然看起来对我来说像是乱码。不管怎样,我不明白为什么我的模板中会出现“None”。一启动服务器,终端就显示了以下内容(这和我用PHP时得到的类似):
11!??????"L15S(?>
11!??????"L16S(?>
11!??????"L17S(?>
11!??????"L19S(?>
11!??????"L20S(?>
另外,我是不是应该把mta函数单独设置成一个模块,然后在视图中导入它呢?
2 个回答
0
你的 mta
函数是直接打印结果,而不是把结果返回给调用它的地方,所以 test
得到的就是默认值 None
,也就是没有返回值的意思。
def mta():
data = urllib2.urlopen('http://addresshere.php?key=keyvaluehere')
response = data.read()
print response # should be return response
1
你能试试这个吗?
def mta():
data = urllib2.urlopen('http://addresshere.php?key=keyvaluehere')
response = data.read()
print response
return response