Python restFUL web服务路由到fi中的特定函数

2024-05-23 19:41:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用werkzeug在python中实现一个简单的API。我创建了一个简单的应用程序“localhost”。我想在GET请求之后执行一个函数。我对URL路由感到困惑。我已经看过了this教程并实现了路由,但仍然不知道如何将请求发送到另一个文件。这是我的代码:

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)

我在一个叫你好.py在同一目录中

^{pr2}$

我想从URL调用索引函数本地主机:4000/你好它将调用文件的索引函数你好.py 请帮帮我。在


Tags: 文件函数pyurl路由mapapplicationenviron
2条回答

The endpoint is typically a string and can be used to uniquely identify the URL

所以它不会将函数绑定到url,你必须自己去做。 在这条线之后

endpoint, args = urls.match()

您可以使用某种控制语句来运行特定函数,在您的示例中:

^{pr2}$

假设您在浏览器指向\he时导入了hello模块,程序将调用hello.index函数。在

http://werkzeug.pocoo.org/docs/0.11/tutorial/#step-4-the-routing

如果要使用外部库中的函数,首先必须导入外部库

import foo #your library

然后,要调用函数“foo\u function”,必须使用以下方法调用此函数:

^{pr2}$

相关问题 更多 >