forked from nikolaik/pyfinn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
58 lines (45 loc) · 1.37 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import json
import os
from flask import request, jsonify, send_from_directory
from .finn import scrape_ad
from .app import app
use_cache = eval(os.getenv("USE_CACHE", "False"))
if use_cache:
import redis
redis_service = redis.from_url(
os.getenv("REDIS_URL", "redis://redis:6379/0")
)
cache_duration = int(
os.getenv("CACHE_DURATION_SECONDS", 23 * 60 * 60)
) # This could maybe be 2 weeks (duration of ads)
@app.route("/", methods=["GET"])
def ad_detail():
finnkode = request.args.get("finnkode")
if not finnkode or not finnkode.isdigit():
return jsonify(
**{
"error": "Missing or invalid param finnkode. Try /?finnkode=KODE"
}
)
ad = False
if use_cache:
cache_key = "finn-ad:{}".format(finnkode)
ad = redis_service.get(cache_key)
if not ad:
app.logger.info("Fetching ad")
ad = scrape_ad(finnkode)
if use_cache:
redis_service.set(cache_key, json.dumps(ad), cache_duration)
else:
app.logger.info("Using Cache")
ad = json.loads(ad)
return jsonify(ad=ad)
@app.route("/favicon.ico")
def favicon():
return send_from_directory(
os.path.join(app.root_path, "static"),
"favicon.ico",
mimetype="image/vnd.microsoft.icon",
)
if __name__ == "__main__":
app.run(debug=True)