我想在python中为将要托管在Web服务器上的应用程序创建一个Twitter访问令牌请求。 我尝试了一些脚本但是虽然它们在裸终端上运行良好,但在部署到Web服务器上后会遇到一些错误。 请在Twitter上注册并获取oauth密钥后指导如何继续。
以下是我尝试在Google App引擎上部署的代码
import sys
import requests,sys
sys.path.insert(0,'requests_oauthlib')
from requests_oauthlib import OAuth1
from urlparse import parse_qs
import webapp2
MAIN_PAGE_HTML = """\
<!doctype html>
<html>
<body>
<h3> Twitter Analysis</h3>
<form action="/parser" method="post">
Enter the words you want to perform analysis on :
<div><input type="text" name="conten" ></input></div>
<div><input type="submit" value="Analyse"></div>
</form>
</body>
</html>
"""
REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token"
AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize?oauth_token="
ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token"
CONSUMER_KEY = "xxxxxxxx"
CONSUMER_SECRET = "xxxxxxxxxxxxx"
OAUTH_TOKEN = ""
OAUTH_TOKEN_SECRET = ""
def setup_oauth():
"""Authorize your app via identifier."""
# Request token
oauth = OAuth1(CONSUMER_KEY, client_secret=CONSUMER_SECRET)
r = requests.post(url=REQUEST_TOKEN_URL, auth=oauth)
print dir(r.content)
credentials = parse_qs(r.content)
print dir(credentials)
resource_owner_key = credentials.get('oauth_token')[0]
resource_owner_secret = credentials.get('oauth_token_secret')[0]
# Authorize
authorize_url = AUTHORIZE_URL + resource_owner_key
print 'Please go here and authorize: ' + authorize_url
verifier = raw_input('Please input the verifier: ')
oauth = OAuth1(CONSUMER_KEY,
client_secret=CONSUMER_SECRET,
resource_owner_key=resource_owner_key,
resource_owner_secret=resource_owner_secret,
verifier=verifier)
# Finally, Obtain the Access Token
r = requests.post(url=ACCESS_TOKEN_URL, auth=oauth)
credentials = parse_qs(r.content)
token = credentials.get('oauth_token')[0]
secret = credentials.get('oauth_token_secret')[0]
return token, secret
def get_oauth():
oauth = OAuth1(CONSUMER_KEY,
client_secret=CONSUMER_SECRET,
resource_owner_key=OAUTH_TOKEN,
resource_owner_secret=OAUTH_TOKEN_SECRET)
return oauth
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.write(MAIN_PAGE_HTML)
class SignIn(webapp2.RequestHandler):
def get(self):
self.response.write("success")
def post(self):
self.response.write("post")
if not OAUTH_TOKEN:
token, secret = setup_oauth()
print "OAUTH_TOKEN: " + token
print "OAUTH_TOKEN_SECRET: " + secret
print
else:
oauth = get_oauth()
r = requests.get(url="https://api.twitter.com/1.1/statuses/mentions_timeline.json", auth=oauth)
print r.json()
application = webapp2.WSGIApplication([
('/', MainPage),
('/parser',SignIn)
], debug=True)