Skip to content

Commit e75e29d

Browse files
committed
Update to Tornado v.6, Python 3 and cleaning up
1 parent 4113fd5 commit e75e29d

28 files changed

+167
-308
lines changed

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,5 @@
1+
bin/
2+
include/
3+
lib/
4+
pyvenv.cfg
15
.DS_Store

README.md

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
# tornado-examples
22

3-
Different simple examples with Tornado V.4.2.
3+
Different examples with Tornado 6.0.1 and Python 3.6.1.
44

55
[Webside](http://www.tornadoweb.org)
66

77
## Getting started
88

9-
Clone the `tornado-examples` repository, install the dependencies and use examples.
9+
Clone the repository, create a virtual environment and install the dependencies.
1010

1111
### Prerequisites
1212

@@ -19,6 +19,11 @@ Clone the `tornado-examples` repository.
1919
$ git clone [email protected]:DBProductions/tornado-examples.git
2020
$ cd tornado-examples
2121

22+
Create a virtual environment and activate it.
23+
24+
$ python3 -m venv .
25+
$ source bin/activate
26+
2227
Install the dependencies.
2328

2429
$ pip install -r requirements.txt

basics/application.py

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,53 @@
1-
#!/usr/bin/env python
2-
""" application class example """
3-
4-
import tornado.ioloop
51
import tornado.web
2+
import tornado.ioloop
3+
from tornado.options import define, options
64

7-
PORT = 8888
5+
define("port", default=8888, help="application port", type=int)
86

97
class MainHandler(tornado.web.RequestHandler):
108
""" main request handler """
119
def get(self):
1210
message = "You requested %s\n" % self.request.uri
11+
self.set_header("Content-Type", "text/plain")
1312
self.write(message)
1413

14+
class JsonHandler(tornado.web.RequestHandler):
15+
def set_default_headers(self):
16+
self.set_header('Content-Type', 'application/json')
17+
18+
def convertReqBody(self, body):
19+
data = {}
20+
try:
21+
data = json.loads(body)
22+
except ValueError:
23+
elements = urllib.unquote_plus(body).split("&")
24+
for i in elements:
25+
couple = i.split("=")
26+
if len(couple) > 1:
27+
data[couple[0]] = couple[1]
28+
return data
29+
30+
def get(self):
31+
self.write({"response": "GET", "uri": self.request.uri})
32+
33+
def post(self):
34+
data = self.convertReqBody(self.request.body)
35+
data['timestamp'] = int(time.time())
36+
self.write({"response": "POST", "uri": self.request.uri, "data": data})
37+
1538
class Application(tornado.web.Application):
1639
"""" application class """
1740
def __init__(self):
18-
handlers = [(r".*", MainHandler)]
19-
settings = {}
41+
handlers = [(r"/json.*", JsonHandler),
42+
(r".*", MainHandler)]
43+
settings = {
44+
"debug": True,
45+
"autoreload": True,
46+
"compress_response": True,
47+
"cookie_secret": "secret123"
48+
}
2049
tornado.web.Application.__init__(self, handlers, **settings)
2150

2251
if __name__ == "__main__":
23-
Application().listen(PORT)
52+
Application().listen(options.port)
2453
tornado.ioloop.IOLoop.instance().start()

basics/asynchttpclient.py

Lines changed: 0 additions & 18 deletions
This file was deleted.

basics/gen.py

Lines changed: 0 additions & 22 deletions
This file was deleted.

basics/httpclient.py

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,30 @@
1-
#!/usr/bin/env python
2-
""" blocking HTTP client example """
3-
41
import tornado.httpclient
52

6-
URL = "http://www.google.com/"
3+
URL = "http://www.dbproductions.de/"
4+
5+
def http_request():
6+
http_client = tornado.httpclient.HTTPClient()
7+
try:
8+
response = http_client.fetch(URL)
9+
except Exception as e:
10+
print("Error: %s" % e)
11+
else:
12+
print("Status Code: {}, Request Time: {}, Body Length: {}".format(response.code,
13+
response.request_time,
14+
len(response.body)))
715

8-
http_client = tornado.httpclient.HTTPClient()
16+
async def async_http_request():
17+
http_client = tornado.httpclient.AsyncHTTPClient()
18+
try:
19+
response = await http_client.fetch(URL)
20+
except Exception as e:
21+
print("Error: %s" % e)
22+
else:
23+
print("Status Code: {}, Request Time: {}, Body Length: {}".format(response.code,
24+
response.request_time,
25+
len(response.body)))
926

10-
try:
11-
response = http_client.fetch(URL)
12-
print response.body
13-
except tornado.httpclient.HTTPError, e:
14-
print "Error:", e
27+
# do a synchronous http request
28+
http_request()
29+
# do a asynchronous http request
30+
tornado.ioloop.IOLoop.current().run_sync(async_http_request)

basics/httpproxy.py

Lines changed: 0 additions & 28 deletions
This file was deleted.

basics/httpserver.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,24 @@
1-
#!/usr/bin/env python
2-
""" non-blocking, single-threaded HTTP server """
3-
4-
import tornado.httpserver
1+
import tornado.web
52
import tornado.ioloop
3+
import tornado.httpserver
64

75
PORT = 8888
86

9-
def handle_request(request):
10-
message = "You requested %s\n" % request.uri
11-
request.write("HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n%s" % (len(message), message))
12-
request.finish()
7+
class MainHandler(tornado.web.RequestHandler):
8+
""" main request handler """
9+
def get(self):
10+
message = "You requested %s\n" % self.request.uri
11+
self.write(message)
12+
13+
class Application(tornado.web.Application):
14+
"""" application class """
15+
def __init__(self):
16+
handlers = [(r".*", MainHandler)]
17+
settings = {}
18+
tornado.web.Application.__init__(self, handlers, **settings)
1319

14-
http_server = tornado.httpserver.HTTPServer(handle_request)
15-
http_server.listen(PORT)
16-
tornado.ioloop.IOLoop.instance().start()
20+
if __name__ == "__main__":
21+
app = Application()
22+
http_server = tornado.httpserver.HTTPServer(app)
23+
http_server.listen(PORT)
24+
tornado.ioloop.IOLoop.instance().start()

basics/json_requesthandler.py

Lines changed: 0 additions & 39 deletions
This file was deleted.

basics/options.py

Lines changed: 0 additions & 22 deletions
This file was deleted.

0 commit comments

Comments
 (0)