我在python中创建了一个端点(使用flask),按照他们的示例here
从Twitter检索推文使用oauth2包,我可以将请求发送到Twitter没问题。但是,我想通过post_body变量发送参数,以便我可以定制检索到的推文。从我读到的有关oauth2的内容来看,这应该是一个字节字符串。设置post_body=b""
有效。但我无法弄清楚如何将params(如count = 3)作为字节串传递。我尝试将参数设置为bytes('count=3','utf-8)
和'count=3'.encode('utf-8')
。我继续从Twitter获得500错误,并从应用中获得ValueError: Expecting value: line 1 column 1 (char 0)
。
对python n00b进行排序,因此可以更好地理解为什么这必须是字节以及如何从字符串转换为字节。
我的代码:
import oauth2
import json
import os
from flask import Flask, render_template, request, jsonify, send_from_directory
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
CONSUMER_KEY = os.environ.get('CONSUMER_KEY')
CONSUMER_SECRET = os.environ.get('CONSUMER_SECRET')
TOKEN_KEY = os.environ.get('TOKEN_KEY')
TOKEN_SECRET = os.environ.get('TOKEN_SECRET')
TWITTER_API = 'https://api.twitter.com/1.1/statuses/user_timeline.json'
def create_app(config=None):
flask_app = Flask(__name__, template_folder='public')
create_routes(flask_app)
return flask_app
def create_routes(app):
@app.errorhandler(404)
def handle_404(e):
return render_template('404.html'), 404
@app.route('/', methods=['GET'])
def no_index():
return send_from_directory('public', 'index.html')
@app.route('/<path:filename>', methods=['GET'])
def serve_static(filename):
if os.path.isdir(os.path.join('public', filename)):
return send_from_directory('public', '{}/index.html'.format(filename))
elif os.path.isfile(os.path.join('public', filename)):
return send_from_directory('public', filename)
return render_template('404.html'), 404
@app.route('/twitter', methods=['GET'])
def twitter():
params = bytes('count=3', 'utf-8')
get_tweets = twitter_oauth_req(TWITTER_API, CONSUMER_KEY, CONSUMER_SECRET, TOKEN_KEY, TOKEN_SECRET, params)
return jsonify(get_tweets), 200
def twitter_oauth_req(url, c_key, c_secret, t_key, t_secret, post_body, http_method="GET", http_headers=None):
consumer = oauth2.Consumer(key=c_key, secret=c_secret)
token = oauth2.Token(key=t_key, secret=t_secret)
client = oauth2.Client(consumer, token)
try:
resp, t_response = client.request( url, method=http_method, body=post_body, headers=http_headers )
return_json = json.loads(t_json)
except Exception as e:
return_json = '[]'
print(e)
return return_json
if __name__ == '__main__':
app = create_app()
app.run(host='0.0.0.0', port=5000, debug=True)