Encapsulation of Methods | Teach You How to Get Started With Python One Hundred and Sixteen

Encapsulation of methods.This section describes the encapsulation of function methods.

Encapsulation of methods.method encapsulation


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})


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 = 'The page is lost'

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 ( "Serving HTTP on" , on [ 0 ], "port" , on [ 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