Python | Encapsulation of methods

# メソッドのカプセル化

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}、お帰りなさい。あなたは {age} 歳で、性別は {gender} です。format(**kwargs)
return content
except FileNotFoundError:
print('ファイルが見つかりません')


def index():
return 'ホームページへようこそ'


def show_test():
return json. dumps({'name': 'zhangsan', 'age': 18})


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 demo_app(environ, start_response):
path = environ['PATH_INFO']

status_code = '200 OK'
if path == '/':
response = index()
elif path == '/test':
response = show_test()
elif path == '/demo':
response = show_demo()
elif path == '/hello':
response = show_hello()
elif path == '/info':
response = show_info()
else:
status_code = '404 Not Found'
response = 'ページが見つかりません'

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


if __name__ == '__main__':
httpd = make_server('', 8080, demo_app)
sa = httpd.socket.getsockname()
print("HTTP を配信中:", sa[0], "ポート", 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

phone お問い合わせ
Hi, I'm Alibaba Cloud AI Assistant!
I can help with questions and solutions.