Python 117 | Use dictionary to manage request paths

Use a dictionary to manage request paths



Write a function to add a new request path through the url (dictionary), and the callback function implements the result.

url = {
'/': index,
'/test': show_test,
'/demo': show_demo,
'/hello': show_hello,
'/info': show_info,
'/foo': show_foo
}
Example:

import json
from wsgiref.simple_server import make_server


def load_file(file_name, **kwargs):
try:
with open('pages/' + file_name, 'r', encoding='utf8') as file:
content = file.read()
if kwargs: # kwargs = {'username':'zhangsan','age':19,'gender':'male'}
content = content.format(**kwargs)
# {username}, welcome back, you are {age} years old this year, your gender is {gender}.format(**kwargs)
return content
except FileNotFoundError:
print('File not found')


def index():
return 'Welcome to my homepage'


def show_test():
# return json.dumps({'name': 'zhangsan', 'age': 18})
return json.dumps(['zhangsan', 'lisi', 'wangwu', 'jack'])


def show_demo():
return load_file('xxxx.txt')


def show_hello():
return load_file('hello.html')


def show_info():
return load_file('info.html', username='zhangsan', age=19, gender='male')


def show_foo():
return 'I am foo'


url = {
'/': index,
'/test': show_test,
'/demo': show_demo,
'/hello': show_hello,
'/info': show_info,
'/foo': show_foo
}


def demo_app(environ, start_response):
path = environ['PATH_INFO']
status_code = '200 OK'

method = url.get(path)
if method:
response = method()
else:
status_code = '404 Not Found'
response = 'The page is lost'

start_response(status_code, [('Content-Type', 'text/html;charset=utf8')])
return [response.encode('utf8')]


if __name__ == '__main__':
httpd = make_server('', 8090, demo_app)
sa = httpd.socket.getsockname()
print("Serving HTTP on", sa[0], "port", sa[1], "...")
httpd.serve_forever()

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00