This repository was archived by the owner on Apr 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.py
More file actions
209 lines (178 loc) · 6.78 KB
/
run.py
File metadata and controls
209 lines (178 loc) · 6.78 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env python
import argparse
import atexit
import os
import signal
import sys
import json
import time
from flask import Flask, g, flash, request, redirect, render_template, make_response, url_for
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
links_file = "./links.json"
app = Flask(__name__)
app.debug = True
app.secret_key = "not so secret"
def load_links():
try:
with open(links_file, "r") as f:
links = json.load(f)
return sorted(links, key=lambda link: link['visits'], reverse=True)
except (ValueError, IOError):
return []
def save_links(links):
with open(links_file, "w") as f:
json.dump(links, f)
def find_link(name):
return {l['name']: l for l in g.links}.get(name, None)
@app.before_request
def before_request():
g.links = load_links()
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']
@app.route("/", methods=["GET"])
def index():
if request_wants_json():
response = make_response(json.dumps(g.links))
response.headers["Content-Type"] = "application/json; charset=utf-8"
return response
else:
return render_template('index.html')
@app.route("/", methods=["POST"])
def add_or_update_link():
name = request.form["name"].strip().lower()
url = request.form["url"].strip()
timestamp = time.strftime("%Y-%m-%dT%H:%M:%S%z", time.localtime())
link = find_link(name)
if link is not None:
link['url'] = url
link['date'] = timestamp
link['visits'] = 0
save_links(g.links)
flash(u"Updated link '{name}' to {url}".format(**locals()), "success")
else:
g.links.append({
"name": name,
"url": url,
"date": timestamp,
"visits": 0
})
save_links(g.links)
flash(u"Added link from '{name}' to {url}".format(**locals()), "success")
return redirect(url_for("index"), code=303)
@app.route("/<name>", methods=["GET"])
def goto(name):
link = find_link(name)
if link is not None:
link['visits'] = link['visits'] + 1
save_links(g.links)
return redirect(link['url'], code=303)
else:
flash(u"That link doesn't exist yet. Create it?", "error")
return make_response(render_template('index.html', name=name), 404)
@app.route("/<name>", methods=["DELETE"])
def delete_link(name):
link = find_link(name)
if link is not None:
g.links = [l for l in g.links if l['name'] != name]
save_links(g.links)
flash(u"Deleted link {} to {}".format(link['name'], link['url']), "error")
return make_response(render_template('index.html', name=name), 200)
else:
flash(u"The link {} doesn't even exist, cannot delete it".format(name), "error")
return make_response(render_template('index.html', name=name), 404)
@app.route("/opensearch.xml")
def opensearch():
response = make_response(render_template("opensearch.xml"))
response.headers["Content-Type"] = "application/xml; charset=utf-8"
return response
@app.route("/search/suggest/<prefix>")
def suggest(prefix):
suggestions = [l['name'] for l in g.links if l['name'].lower().startswith(prefix.lower())]
result = [prefix, suggestions]
response = make_response(json.dumps(result))
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "-1"
response.headers["Cache-Control"] = "no-cache, must-revalidate"
response.headers["Content-Type"] = "text/javascript; charset=utf-8"
response.headers["Content-Disposition"] = 'attachment; filename="f.txt"'
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers["X-Frame-Options"] = "SAMEORIGIN"
response.headers["Accept-Ranges"] = "none"
response.headers["Vary"] = "Accept-Encoding"
return response
def log(message):
timestamp = time.strftime("%Y-%m-%dT%H:%M:%S%z", time.localtime())
print "{timestamp} - {message}".format(**locals())
def run_server(opts):
http_server = HTTPServer(WSGIContainer(app))
http_server.listen(opts.port)
app.logger.info("Server listening on http://0.0.0.0:{}/ (pid: {})".format(opts.port, os.getpid()))
if opts.pid_file is not None:
def write_pid_file():
with open(opts.pid_file, "w") as f:
f.write(str(os.getpid()))
def try_to_delete_pid_file():
try:
os.unlink(opts.pid_file)
except OSError as ignore:
pass
write_pid_file()
atexit.register(try_to_delete_pid_file)
IOLoop.current().start()
def main(argv):
def on_exit(sig, func=None):
log("Close application (signal: {})".format(sig))
IOLoop.current().stop()
parser = argparse.ArgumentParser(
prog=os.path.basename(__file__),
description="Simple URL shorterner"
)
parser.add_argument("-d", "--data-dir",
help="store data in given directory (default: current directory)",
default=".")
parser.add_argument("-p", "--port",
help="set listen port (default: 7410)",
type=int, default=7410)
parser.add_argument("-D", "--daemonize",
help="run server in background (default: run in foreground)",
action="store_true")
parser.add_argument("-P", "--pid-file",
help="where to store pid when daemonizing (default: don't store)")
parser.add_argument("-w", "--work-dir",
help="working directory to set when daemonizing (default: current directory)",
default=".")
parser.add_argument("-l", "--log-dir",
help="log directory to set when daemonizing (default: current directory)",
default=".")
parser.add_argument("--development",
help="run app with Flask's werkzeug server in debug mode",
action="store_true")
opts = parser.parse_args()
if opts.data_dir is not None:
global links_file
links_file = "{}/links.json".format(opts.data_dir)
if opts.development:
app.run(debug=True, port=opts.port)
else:
signal.signal(signal.SIGTERM, on_exit) # OS says terminate
signal.signal(signal.SIGINT, on_exit) # ctrl-c
if opts.daemonize:
import daemon
ctx = daemon.DaemonContext(
working_directory=opts.work_dir,
initgroups=False,
stdout=open("{}/stdout.log".format(opts.log_dir), "w"),
stderr=open("{}/stderr.log".format(opts.log_dir), "w"),
)
with ctx:
run_server(opts)
else:
run_server(opts)
if __name__ == "__main__":
main(sys.argv)