【发布时间】:2015-02-27 04:08:12
【问题描述】:
我尝试为 OpenWeatherMap 进行非阻塞 api 调用,但我的问题是:
当我对文件进行测试并运行它时,global api 生效,但是在导入函数时,global 不再工作,api 没有变化:api = ""?
在声明函数后,我输入了global api,然后当我使用print 'The API link is: ' + api 时,我得到了确切的api,但global dident 生效了!
这里是代码:https://github.com/abdelouahabb/tornadowm/blob/master/tornadowm.py#L62
我做错了什么?
当我导入文件时:
from tornadowm import *
forecast('daily', q='london', lang='fr')
The API link is: http://api.openweathermap.org/data/2.5/forecast/daily?lang=fr&q=london
api
Out[5]: ''
执行文件而不是导入文件时:
runfile('C:/Python27/Lib/site-packages/tornadowm.py', wdir='C:/Python27/Lib/site-packages')
forecast('daily', q='london', lang='fr')
The API link is: http://api.openweathermap.org/data/2.5/forecast/daily?lang=fr&q=london
api
Out[8]: 'http://api.openweathermap.org/data/2.5/forecast/daily?lang=fr&q=london'
编辑:这里是代码,如果 Git 更新了:
from tornado.httpclient import AsyncHTTPClient
import json
import xml.etree.ElementTree as ET
http_client = AsyncHTTPClient()
url = ''
response = ''
args = []
link = 'http://api.openweathermap.org/data/2.5/'
api = ''
result = {}
way = ''
def forecast(way, **kwargs):
global api
if way in ('weather', 'forecast', 'daily', 'find'):
if way == 'daily':
way = 'forecast/daily?'
else:
way += '?'
for i, j in kwargs.iteritems():
args.append('&{0}={1}'.format(i, j))
a = ''.join(set(args))
api = (link + way + a.replace(' ', '+')).replace('?&', '?')
print 'The API link is: ' + api
def handle_request(resp):
global response
if resp.error:
print "Error:", resp.error
else:
response = resp.body
http_client.fetch(api, handle_request)
else:
print "please put a way: 'weather', 'forecast', 'daily', 'find' "
def get_result():
global result
if response.startswith('{'):
print 'the result is JSON, stored in the variable result'
result = json.loads(response)
elif response.startswith('<'):
print 'the result is XML, parse the result variable to work on the nodes,'
print 'or, use response to see the raw result'
result = ET.fromstring(response)
else:
print '''Sorry, no valid response, or you used a parameter that is not compatible with the way!\n please check http://www.openweathermap.com/api for more informations''
【问题讨论】:
-
当你只在一个地方使用这个变量时,为什么要使用全局变量?您是否在代码示例中未显示的地方使用它?
-
另外,您的 args 在技术上没有在您的
def中定义,当导入时应该会引发错误 -
刚刚编辑了问题,现在,如您所见,如果我运行文件,我会更改
global,但是在导入它时,global不会被触及,python 2.7.9 -
@Abdelouahab 为了后代,下次尝试将代码的重要部分直接粘贴到您的问题中,因为您的链接可能会损坏或更改,并且您希望您的问题仍然有意义几年后,来自谷歌或类似网站的用户:)
-
@Jivan 谢谢你,我刚做了,所以万一它丢失了,或者 git 改变了,所以人们总会得到它有用的:)
标签: python function global-variables python-import