我正在编写一个简单的 Python Web 服务来从 Facebook Graph API 中获取内容。现在,在测试时,我将所有内容都写在一个单独的 python 类中,并且运行良好。现在我已经开始模块化一切,这一切都崩溃了。
我正在为我的 RESTful 服务使用 webpy。我的代码看起来有点像这样:
webapp.py
import web
import FBModule
fb = FBModule.FBManager()
urls = (
'/', 'HomeHandler',
'/auth/login', 'LoginHandler',
'/auth/logout', 'LogoutHandler'
)
class BaseHandler():
def current_user(self):
if not hasattr(self, "_current_user"):
self._current_user = dict()
user_id = web.cookies().get('fb_userid')
user_name = web.cookies().get('fb_username')
if user_id and user_name:
self._current_user = {'id': user_id, 'name': user_name}
return self._current_user
class HomeHandler(BaseHandler):
def GET(self):
return render.oauth(current_user=self.current_user())
class LoginHandler:
def GET(self):
fb.login()
return web.seeother('/')
class LogoutHandler():
def GET(self):
fb.logout()
web.seeother('/')
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
FBModule.py
import urllib
import urlparse
import time
import web
FACEBOOK_APP_ID = "<APP ID>"
FACEBOOK_APP_SECRET = "<APP SECRET>"
def path_url():
return "http://localhost:8080" + web.ctx.fullpath
class FBManager:
def login(self):
data = web.input(code=None)
args = dict(client_id=FACEBOOK_APP_ID, redirect_uri=path_url())
if data.code is None:
return web.seeother('http://www.facebook.com/dialog/oauth?' + urllib.urlencode(args) + '&scope=' + urllib.quote('user_likes,friends_likes,user_birthday,friends_birthday'))
args['code'] = data.code
args['client_secret'] = FACEBOOK_APP_SECRET
response = urlparse.parse_qs(urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args)).read())
access_token = response["access_token"][-1]
profile = json.load(urllib.urlopen("https://graph.facebook.com/me?fields=id,name,birthday,location,gender&" + urllib.urlencode(dict(access_token=access_token))))
web.setcookie('fb_userid', str(profile['id']), expires=time.time() + 7 * 86400)
web.setcookie('fb_username', str(profile['name']), expires=time.time() + 7 * 86400)
def logout(self):
web.setcookie('fb_userid', '', expires=time.time() - 86400)
web.setcookie('fb_username', '', expires=time.time() - 86400)
问题是,如果我使用单独的模块从 Facebook 获取访问令牌,我会收到“内容损坏错误”。但是,如果我做一些简单的事情,比如剪切和粘贴从 FBModule 的 login() 函数到 LoginHandler 类的 GET() 函数的所有内容,那么一切都会再次变得笨拙。我束手无策,试图找出我在这里做错了什么。
如果您知道我做错了什么,请告诉我。
Regds,帕里托什