import cgi
import json
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’]
method = environ[‘REQUEST_METHOD’].lower()
if method==‘get’:
params = cgi.FieldStorage(environ[‘wsgi.input’], environ=environ)
environ[‘params’] = { key: params.getvalue(key) for key in params }
# else:
# params = environ[“wsgi.input”].read(int(environ.get(“CONTENT_LENGTH”, 0)))
# params = json.loads(params)
# environ[‘params’] = {key: params[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
import time
_hello_resp = ‘’’
Hello {name}!
‘’’
def hello_world(environ, start_response):
start_response(‘200 OK’, [ (‘Content-type’,‘tehelloxt/html’)])
params = environ['params']
resp = _hello_resp.format(name=params.get('name'))
yield resp.encode('utf-8')
def hello_world_json(environ, start_response):
start_response(‘200 OK’, [(‘Content-Type’, ‘application/json’)])
params = environ[‘params’]
dis={‘name’:params.get(‘name’)}
r = bytes(’{}’.format(json.dumps(dis)), ‘utf-8’)
return [r]
_localtime_resp = ‘’’
<?xml version="1.0"?>
‘’’
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’)
def application(environ, start_response):
print(“1111111111111”)
# 定义文件请求的类型和当前请求成功的code
start_response(‘200 OK’, [(‘Content-Type’, ‘application/json’)])
# environ是当前请求的所有数据,包括Header和URL,body
request_body = environ["wsgi.input"].read(int(environ.get("CONTENT_LENGTH", 0)))
request_body = json.loads(request_body)
name = request_body["name"]
no = request_body["no"]
# input your method here
# for instance:
# 增删改查
dic = {"名称": name, "myNoIs": no}
r = bytes('{}'.format(json.dumps(dic)), 'utf-8')
return [r]
if name == ‘main’:
from resty 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’, localtime)
dispatcher.register('GET', '/hello_json', hello_world_json)
dispatcher.register('post', '/new_person', application)
# Launch a basic server
httpd = make_server('', 8080, dispatcher)
print('Serving on port 8080...')
httpd.serve_forever()