Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# -*- coding: utf-8 -*-
2"""
3@file
4@brief Helpers for :epkg:`Flask`.
5"""
6import traceback
7import threading
8from flask import Response
11def Text2Response(text):
12 """
13 convert a text into plain text
15 @param text text to convert
16 @return textReponse
17 """
18 return Response(text, mimetype='text/plain')
21def Exception2Response(e):
22 """
23 convert an exception into plain text and display the stack trace
25 @param e Exception
26 @return textReponse
27 """
28 text = traceback.format_exc()
29 return Text2Response("Exception: {0}\nSTACK:\n{1}".format(str(e), text))
32class FlaskInThread(threading.Thread):
34 """
35 Defines a thread for the server.
36 """
38 def __init__(self, app, host="localhost", port=8081):
39 """
40 @param app :epkg:`Flask` application
41 """
42 threading.Thread.__init__(self)
43 self._app = app
44 self._host = host
45 self._port = port
46 self.daemon = True
48 def run(self):
49 """
50 Starts the server.
51 """
52 self._app.run(host=self._host, port=self._port)
54 def shutdown(self):
55 """
56 Shuts down the server, the function could work if:
58 * method run keeps a pointer on a server instance
59 (the one owning method
60 `serve_forever <https://docs.python.org/3/library/socketserver.html#socketserver.BaseServer.serve_forever>`_)
61 * module `werkzeug <http://werkzeug.pocoo.org/>`_
62 returns this instance in function
63 `serving.run_simple <https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/serving.py>`_
64 * module `Flask <http://flask.pocoo.org/>`_
65 returns this instance in method
66 `app.Flask.run <https://github.com/mitsuhiko/flask/blob/master/flask/app.py>`_
67 """
68 raise NotImplementedError()
69 # self.server.shutdown()
70 # self.server.server_close()