Search code examples
python-3.xapitornado

Tornado get input from URL request


My program is to get parameter(URL) from web and in my tornado API, i want to accept them into one bye one. Now my code accepts a single tuple. My api want to fetch the 4 parameters(south-lat,south-long,east-lat,east-long) which comes from the web URL request. And i will implement them into get method of Tornado and find them in my database. I want to know how to accept them in tornado in seperately. This is my current working codes.

import socket
import tornado.web
from datetime import datetime
import pymongo
from pymongo import MongoClient
from pprint import pprint
import tornado.httpserver
import tornado.ioloop
import tornado.options
from tornado.options import define,options

#apicall/v1/geoloc.json?geoquery=True&southwest_lat=''&southwest_lng=''&northeast_lat=''&northeast_lng=''

#tornado port
port = 8088
host = "127.0.0.1"

#make a connection with mongodb
#client=MongoClient()

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("hello APIs")

#what this works is here   
class VisualizationHandler(tornado.web.RequestHandler):
    def get(self,*args):#how to accept the input from map?


        self.open_args=args
        #self.open_kwargs=kwargs

        print(self.open_args)
        print(type(self.open_args))

        #self.write("Data is at the terminal")
        #client = MongoClient("mongodb://localhost:27017")
        #db=client.test
        #docs=db.neighborhoods.findOne()
        #if docs is None:
            #print("Not found")
        #else:
            #print(docs)

            #lat=self.get_argument('lat',True)
            #long=self.get_argument('long',True)
            #self.write(lat)
            #self.write(long)



        #var neighborhood = db.neighborhoods.findOne( { geometry: { $geoIntersects: { $geometry: { type: "Point", coordinates: [ slong, slat] } } } } )

def main():
    application = tornado.web.Application([
        (r"/", MainHandler),
        (r"/geo/(.*)",VisualizationHandler),
    ])

    try:
        sockets = tornado.netutil.bind_sockets(port, address=host)
        print("Socket binding successful to {0}:{1}".format(host, port))
    except socket.error:
        print("Socket binding failed to {0}:{1}".format(host, port))
        return

    try:
        _id = tornado.process.fork_processes(0, max_restarts=3)
        print("Process forked : {}".format(_id))

        server = tornado.httpserver.HTTPServer(application)
        server.add_sockets(sockets)
        tornado.ioloop.IOLoop.current().start()
    except KeyboardInterrupt: # stop with Ctrl+C from shell
        print("Tornado is stopping")

if __name__ == "__main__":
    print("Tornado is starting")

    main()

Solution

  • get() method's args/kwargs are retrieved from the url (url regex's match groups, to be specific). Of course, you can create something like this to pass arguments to your function:

    (r"/geo/(.*)/(.*)", VisualizationHandler)
    

    or

    (r"/geo/(?P<south_lat>.*)/(?P<south_long>.*)", VisualizationHandler)
    

    and args/kwargs south_lat and south_long would be passed to your function from a URL like /geo/123/456, but it's inconvenient. I'd advise you to pass your arguments as URL params /geo?south_lat=123&south_long=456 and read them using get_argument().