如何使用Python构建高级Restful服务接口?

2026-05-24 13:451阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计457个文字,预计阅读时间需要2分钟。

如何使用Python构建高级Restful服务接口?

本章主要介绍使用CGI库进行原生写法,通常情况下不常用。可以使用Flask框架来实现。下面是创建接口服务的示例代码:

pythonimport cgidef not_found_404(environ, start_response): start_response('404 Not Found', [('Content-type', 'text/plain')]) return ['Not Found']

如何使用Python构建高级Restful服务接口?

本章主要使用cgi库,原生写法一般时候不常用。可以用Flask框架来实现。

创建接口服务

import cgi

def not_found_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), not_found_404)
return handler(environ, start_response)

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

创建接口处理类

import time

_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')

_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 local_time(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__':
from rest_exp import PathDispatcher
from wsgiref.simple_server import make_server

# Create the dispatcher and register functions
dispatcher = PathDispatcher()
dispatcher.register('GET', '/hello', hello_world)
dispatcher.register('GET', '/localtime', local_time)

# Launch a basic server
localhost:8080/hello?name=world')
print(f'hello text:\n{req.text}')

req = requests.get('localhost:8080/localtime')
print(f'localtime text:\n{req.text}')

本文共计457个文字,预计阅读时间需要2分钟。

如何使用Python构建高级Restful服务接口?

本章主要介绍使用CGI库进行原生写法,通常情况下不常用。可以使用Flask框架来实现。下面是创建接口服务的示例代码:

pythonimport cgidef not_found_404(environ, start_response): start_response('404 Not Found', [('Content-type', 'text/plain')]) return ['Not Found']

如何使用Python构建高级Restful服务接口?

本章主要使用cgi库,原生写法一般时候不常用。可以用Flask框架来实现。

创建接口服务

import cgi

def not_found_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), not_found_404)
return handler(environ, start_response)

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

创建接口处理类

import time

_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')

_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 local_time(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__':
from rest_exp import PathDispatcher
from wsgiref.simple_server import make_server

# Create the dispatcher and register functions
dispatcher = PathDispatcher()
dispatcher.register('GET', '/hello', hello_world)
dispatcher.register('GET', '/localtime', local_time)

# Launch a basic server
localhost:8080/hello?name=world')
print(f'hello text:\n{req.text}')

req = requests.get('localhost:8080/localtime')
print(f'localtime text:\n{req.text}')