如何通过Flask AJAX实现Python与JavaScript通信,传递Tweepy获取的推特数据
问题排查与修复方案
一、现有代码核心问题汇总
- 后端Flask路由参数错误:路由装饰器中关键字是
methods而非method,导致POST请求被拦截 - 全局变量风险:推文拉取逻辑写在Flask服务启动前,仅执行一次,且直接在路由中引用全局
tweet变量,无匹配数据时会直接报错 - 接口返回格式错误:
jsonify参数结构不符合预期,前端无法正常解析返回内容 - 前端选择器错误:
$(justTweet)没有加ID选择器标识#,也不存在对应ID的元素,替换操作无效 - 函数未主动触发:
getTweet仅做了定义,页面加载后没有主动调用执行
二、修正后的完整代码
1. 后端 twitter.py
import tweepy from flask import Flask, render_template # 替换为你自己的Twitter API密钥 access_token="你的access_token" access_token_secret="你的access_token_secret" api_key="你的api_key" api_key_secret="你的api_key_secret" auth = tweepy.OAuthHandler(consumer_key=api_key, consumer_secret=api_key_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True) application = Flask(__name__) # 封装拉取推文的逻辑,可灵活指定关键词和数量 def fetch_tweets(hashtag, count=1): tweets = tweepy.Cursor(api.search_tweets, q=hashtag, include_entities=True).items(count) for tweet in tweets: return tweet.text return "未找到对应关键词的推文" # 首页路由 @application.route('/') def homepage(): # 这里可以替换为你想要搜索的关键词 init_text = fetch_tweets("Python", count=1) return render_template('nuevo.html', x=init_text) # 推文接口,methods参数修正为复数 @application.route('/get_tweets', methods=['POST']) def gettweets(): text = fetch_tweets("Python", count=1) # 直接返回渲染好的模板片段 return render_template('justTweet.html', x=text) if __name__ == '__main__': application.run(debug=True)
2. 前端模板 templates/nuevo.html
<div id="tweet"> {{x}} </div> <script> function getTweet(){ // 原生JS实现AJAX,无需引入额外依赖 const xhr = new XMLHttpRequest() xhr.open('POST', '/get_tweets') xhr.onload = function() { if (xhr.status === 200) { document.getElementById('tweet').outerHTML = xhr.responseText } } xhr.send() } // 页面加载完成后自动调用 window.onload = function() { getTweet() } </script>
3. 片段模板 templates/justTweet.html
<div id="tweet"> {{x}} </div>
三、运行验证步骤
- 在twitter.py同级目录新建
templates文件夹,将两个html文件放入该文件夹 - 替换twitter.py中你的Twitter API密钥,修改你想要搜索的关键词
- 安装依赖:
pip install flask tweepy - 运行twitter.py,访问
http://127.0.0.1:5000即可看到推文内容,AJAX会自动请求刷新内容
内容的提问来源于stack exchange,提问作者Ander Canales Medina
相关产品推荐
相关产品推荐

