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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
#!/usr/bin/env python3
# Startdate: 2022-09-08
# Improve:
# confirm date logic works.
from flask import Flask, Response, request, url_for, render_template
import json, sys, os
# Load coupons from same directory as coupons_web.py
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import coupons
from urllib import parse
app = Flask(__name__)
config = coupons.Config()
# satisfies mod_wsgi:
application = app
@app.route("/")
def root():
set_cache_dir_from_apache_environ(request, config)
return render_template("index.html")
def set_cache_dir_from_apache_environ(_request, _config):
"""
Given the request and config objects, derive the SetEnv XDG_CACHE_HOME for coupons web app.
"""
try:
cache_dir = _request.environ.get("XDG_CACHE_HOME")
if cache_dir is not None and cache_dir != _config.cache_dir:
print(f"DEBUG(web set_cache_dir): setting cache dir to {cache_dir}")
_config.cache_dir = cache_dir
except:
pass
@app.route("/search/", methods=["GET","POST"])
@app.route("/search/<searchstring>", methods=["GET"])
def search(searchstring = ""):
"""
Pass searchstring to fetch_and_search. Returns json unless html is requested.
Accepts parameters nocache=1 and date=YYYY-MM-DD
"""
if request.method in ["POST"]:
searchstring = request.get_data().decode("utf-8")
set_cache_dir_from_apache_environ(request, config)
print(f"DEBUG(web search): {request}")
#print(f"DEBUG(web search): {request.method} searchstring={searchstring}")
force = False
nocache = request.args.get('nocache')
date = request.args.get('date') # in YYYY-MM-DD form
if nocache in ["1",1,"yes","YES","true","TRUE",True,"True","on"]:
print(f"DEBUG(web search): Caching is disabled for this request.")
force = True
results = []
for store in coupons.store_urls:
a = coupons.fetch_and_search(store = store, force = force, searchstring = searchstring, date = date, config = config)
if len(a) > 2: # an empty a is "{}" which is a string?!
results.append({store: json.loads(a)})
accept = []
try:
accept = request.headers.get("Accept")
except:
pass
from_js = True if request.headers.get("From") else False
#print(f"DEBUG(web search): Accept only type {accept}")
#print(f"DEBUG(web search): Results: {results}")
#print(f"DEBUG(web search): From_js is {from_js}")
if accept in ["text/html", "application/html"] or "text/html" in accept:
#print(f"DEBUG(web search): Must convert the json to html...")
savedlink = url_for("search") + searchstring # because url_for handles searchstring= weird
#print(f"DEBUG(web search): Preparing saved search link: {savedlink}")
return render_template("index.html", results = results, from_js = from_js, savedlink = savedlink)
else:
# json is default
return json.dumps(results),200
if __name__ == "__main__":
app.run()
|