Reputation: 13
Here's my tornado script, it's me trying to understand how to grab user input from a browser and pass it back to the Game
class.
import tornado.ioloop
import tornado.web
def applicationInit():
return tornado.web.Application([
(r"/", Game),
])
class Game(tornado.web.RequestHandler):
def get(self):
self.write("You made it!")
self.render("game.html")
def post(self):
if self.get_argument("keyinput") is not None:
k = int(self.get_argument("keyinput"))
print (k)
app = applicationInit()
app.listen(8080)
print ("Starting...")
tornado.ioloop.IOLoop.current().start()
... and here is my game.html
that is referenced by the Game.write()
in the get
method.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Pyablo</title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on("keydown", this, function(e){
var key = e.which;
switch (key)
{
case 87:
$.post("/game", { 'keyinput': '1' }, function(data) {
alert("You pressed UP. "+ data);
});
}
});
});
</script>
</body>
</html>
So, I know much more about Python than I do jQuery/HTML/JavaScript. I am getting this error whenever I go to 127.0.0.1:8080...
WARNING:tornado.access:404 POST /game (127.0.0.1) 1.96ms
What am I missing?
Upvotes: 0
Views: 11209
Reputation: 6773
You need to properly define your handlers.
If you want to maka a POST request to /game
, you need to define that path for your Game
RequestHandler class to handle it.
You can serve your game.html
file with a StaticFileHandler
.
Make a directory files
, rename game.html
to index.html
and put it into files
directory.
Your code should then be:
def applicationInit():
return tornado.web.Application([
(r"/game", Game),
(r"/(.*)", tornado.web.StaticFileHandler, {'path': './files', 'default_filename': 'index.html'}),
])
class Game(tornado.web.RequestHandler):
def post(self):
if self.get_argument("keyinput") is not None:
k = int(self.get_argument("keyinput"))
print (k)
Upvotes: 1
Reputation: 101
For the POST error, you are posting to /game but only registered the / path. You should POST to /.
The error on the GET is strange as you are getting jquery from a cdn and the version in the error doesn't match the one in your code.
Upvotes: 1