Python restFUL web service - routing to a specific function in a file
<p>I am implementing a simple API in python using werkzeug. I have created a simple application 'localhost'. I want to execute a function after a GET request. I am confused with URL routing. I have gone through <a href="http://werkzeug.pocoo.org/docs/0.11/routing/" rel="nofollow">this</a> tutorial and implemented routing but still can't figure out how to send a request to another file. Here is my code:</p>

<pre><code>url_map = Map([
    Rule('/spell', endpoint='spell_checker.py'),
    Rule('/he', endpoint='hello/test')
])


   @Request.application
    def application(request):
      urls = url_map.bind_to_environ(environ)
      try:
        endpoint, args = urls.match()
        print(endpoint + " " + args)
        #urls.dispatch('test')
      except httplib.HTTPException, e:
        return e(environ, start_response)

       start_response('200 OK', [('Content-Type', 'text/plain')])
       return ['Rul1e points to %r with arguments %r' % (endpoint, args)]

    if __name__ == '__main__':
        from werkzeug.serving import run_simple
        run_simple('127.0.0.1', 4000, application)
</code></pre>

<p>I have another another in a file named hello.py in the same directory</p>

<pre><code>def index():
    print 'This is the test'
</code></pre>

<p>I want to call index function from URL like localhost:4000/hello which will call the index function of the file hello.py
Kindly assist me.</p>

<blockquote>
  <p>The endpoint is typically a string and can be used to uniquely
  identify the URL</p>
</blockquote>

<p>So it doesn't bind a function to a url, you have to do it yourself.
After this line</p>

<pre><code>endpoint, args = urls.match()
</code></pre>

<p>you can put some kind of control statements to run specific functions, in your case:</p>

<pre><code>if endpoint == "hello/test":
    hello.index(request, **args)
</code></pre>

<p>assuming you have imported <code>hello</code> module when you point your browser to <code>\he</code> the program will call <code>hello.index</code> function.</p>

<p><a href="http://werkzeug.pocoo.org/docs/0.11/tutorial/#step-4-the-routing" rel="nofollow">http://werkzeug.pocoo.org/docs/0.11/tutorial/#step-4-the-routing</a></p>

python web-services rest http werkzeug