python实现wsgi接口提供http服务响应http请求(跨代码语言数据交互)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_29673403/article/details/80421302

上一篇说完Java如何实现restful API提供http服务与php进行数据交互,这篇就要开始说python语言如何提供http服务进行跨语言数据交互的实现了。同样也是基于实际的需求要求,需要根据不同的关键词推荐信息库中的相应匹配信息。(让机器自己进行分析推荐,需要结合深度学习的部分监督算法实现。)很明显算法部分需要用到python去进行,而显示则是通过php生成的页面将数据展示给用户看。这一篇我们说的就是php与python交互的过程实现(深度学习算法部分将在另一篇文章中具体讲述)。
那让我们先来看看python是如何响应用户的http请求的把。因为我们不需要很复杂的功能,所以我就没有找python实现http服务的框架,而是使用python语言自带的wsgi接口去响应http请求。实现接口的代码如下:

import json
import time
from wsgiref.simple_server import make_server
from PathDispatcher import PathDispatcher
from loadData import loadData
from retrieve import retrieve

_hello_resp = '''\
<html>
  <head>
     <title>Hello {name}</title>
   </head>
   <body>
     <h1>Hello {name}!</h1>
   </body>
</html>'''

def hello_world(environ, start_response):
    start_response('200 OK', [('Content-type', 'text/html')])
    params = environ['params']
    resp = _hello_resp.format(name=params.get('name'))
    yield resp.encode('utf-8')

def match_info(environ, start_response):
    start_response('200 OK', [('Content-type', 'text/html')])
    params = environ['params']
    load = loadData()
    content = load.getTaskInfo(params.get('id'))
    deal = retrieve()
    resp = json.dumps(deal.getMatchInfos(content),ensure_ascii=False)
    yield resp.encode('utf-8')

def set_model(environ, start_response):
    start_response('200 OK', [('Content-type', 'text/html')])
    deal = retrieve()
    resp = deal.setModel()
    yield resp.encode('utf-8')

_localtime_resp = '''\
<?xml version="1.0"?>
<time>
  <year>{t.tm_year}</year>
  <month>{t.tm_mon}</month>
  <day>{t.tm_mday}</day>
  <hour>{t.tm_hour}</hour>
  <minute>{t.tm_min}</minute>
  <second>{t.tm_sec}</second>
</time>'''

def localtime(environ, start_response):
    start_response('200 OK', [('Content-type', 'application/xml')])
    resp = _localtime_resp.format(t=time.localtime())
    yield resp.encode('utf-8')

if __name__ == '__main__':

    # Create the dispatcher and register functions
    dispatcher = PathDispatcher()
    dispatcher.register('GET', '/hello', hello_world)
    dispatcher.register('GET', '/getInfo', match_info)
    dispatcher.register('GET', '/setModel', set_model)
    dispatcher.register('GET', '/localtime', localtime)

    # Launch a basic server
    httpd = make_server('', 8080, dispatcher)
    print('Serving on port 8080...')
    httpd.serve_forever()

python用以识别正确url访问路径的适配器代码如下:

import cgi

def notfound_404(environ, start_response):
    start_response('404 Not Found', [ ('Content-type', 'text/plain') ])
    return [b'Not Found']

class PathDispatcher:
    def __init__(self):
        self.pathmap = { }

    def __call__(self, environ, start_response):
        path = environ['PATH_INFO']
        params = cgi.FieldStorage(environ['wsgi.input'],
                                  environ=environ)
        method = environ['REQUEST_METHOD'].lower()
        environ['params'] = { key: params.getvalue(key) for key in params }
        handler = self.pathmap.get((method,path), notfound_404)
        return handler(environ, start_response)

    def register(self, method, path, function):
        self.pathmap[method.lower(), path] = function
        return function

到此就可以实现一个简单的http服务。监听8080端口来的http请求。同样需要将代码放在服务器上运行即可。
同理,我们来看看php端是如何访问这个http服务来获取自己想要的数据的把(其实方法同Java,CurlGet()发送HTTP请求把参数放入url中即可)

$base_url = "http://".SEARCH_SERVER."/searchOp/myresource/getUserList?".urldecode($condition);
        $info = CurlGet($base_url);

不知道CurlGet()函数里面代码的可以去看看我上一篇博客,这里就不再赘述啦。到此数据交互就完成啦。mark一下,与君共勉~

猜你喜欢

转载自blog.csdn.net/sinat_29673403/article/details/80421302