Debian Codegraph @

examples/downloader.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 #!/usr/bin/python3
2 """
3 A flask web application that downloads a page in the background.
4 """
5
6 import logging
7 from flask import Flask, session, escape
8 from crochet import setup, run_in_reactor, retrieve_result, TimeoutError
9
10 # Can be called multiple times with no ill-effect:
11 setup()
12
13 app = Flask(__name__)
14
15
16 @run_in_reactor
17 def download_page(url):
18 """
19 Download a page.
20 """
21 from twisted.web.client import getPage
22 return getPage(url)
23
24
25 @app.route('/')
26 def index():
27 if 'download' not in session:
28 # Calling an @run_in_reactor function returns an EventualResult:
29 result = download_page('http://www.google.com')
30 session['download'] = result.stash()
31 return "Starting download, refresh to track progress."
32
33 # Retrieval is a one-time operation, so the uid in the session cannot be
34 # reused:
35 result = retrieve_result(session.pop('download'))
36 try:
37 download = result.wait(timeout=0.1)
38 return "Downloaded: " + escape(download)
39 except TimeoutError:
40 session['download'] = result.stash()
41 return "Download in progress..."
42 except:
43 # The original traceback of the exception:
44 return "Download failed:\n" + result.original_failure().getTraceback()
45
46
47 if __name__ == '__main__':
48 import os, sys
49 logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
50 app.secret_key = os.urandom(24)
51 app.run()