compliment.b303.me.py
· 1.1 KiB · Python
Raw
#!/usr/bin/env python3
import requests
from flask import *
import random
from apscheduler.schedulers.background import BackgroundScheduler
app = Flask(__name__)
scheduler = BackgroundScheduler()
url = "https://reddit.com/r/gonewild/comments.json?limit=200"
comments = []
def request_wants_json():
best = request.accept_mimetypes \
.best_match(['application/json', 'text/html'])
return best == 'application/json' and \
request.accept_mimetypes[best] > \
request.accept_mimetypes['text/html']
def update_comments():
global comments
data = requests.get(url, headers={"User-Agent": "/u/suudo http://compliment.b303.me (comments from gonewild)"}).json()
comments = [a["data"]["body"] for a in data["data"]["children"]]
@app.route("/")
def compliment():
if request_wants_json():
return jsonify({"compliment": random.choice(comments)})
return random.choice(comments)
update_comments()
scheduler.add_job(update_comments, 'interval', minutes=15)
scheduler.start()
if __name__ == "__main__":
try:
app.run(port=56735, debug=True)
finally:
scheduler.shutdown()
| 1 | #!/usr/bin/env python3 |
| 2 | import requests |
| 3 | from flask import * |
| 4 | import random |
| 5 | |
| 6 | from apscheduler.schedulers.background import BackgroundScheduler |
| 7 | |
| 8 | app = Flask(__name__) |
| 9 | scheduler = BackgroundScheduler() |
| 10 | url = "https://reddit.com/r/gonewild/comments.json?limit=200" |
| 11 | comments = [] |
| 12 | |
| 13 | def request_wants_json(): |
| 14 | best = request.accept_mimetypes \ |
| 15 | .best_match(['application/json', 'text/html']) |
| 16 | return best == 'application/json' and \ |
| 17 | request.accept_mimetypes[best] > \ |
| 18 | request.accept_mimetypes['text/html'] |
| 19 | |
| 20 | def update_comments(): |
| 21 | global comments |
| 22 | data = requests.get(url, headers={"User-Agent": "/u/suudo http://compliment.b303.me (comments from gonewild)"}).json() |
| 23 | comments = [a["data"]["body"] for a in data["data"]["children"]] |
| 24 | |
| 25 | @app.route("/") |
| 26 | def compliment(): |
| 27 | if request_wants_json(): |
| 28 | return jsonify({"compliment": random.choice(comments)}) |
| 29 | return random.choice(comments) |
| 30 | |
| 31 | update_comments() |
| 32 | scheduler.add_job(update_comments, 'interval', minutes=15) |
| 33 | scheduler.start() |
| 34 | if __name__ == "__main__": |
| 35 | try: |
| 36 | app.run(port=56735, debug=True) |
| 37 | finally: |
| 38 | scheduler.shutdown() |
| 39 |