使用 Python Web
框架构建 Web
应用可以使我们专注于应用程序的核心逻辑,而不必处理低级细节(例如,协议、套接字或进程和线程管理等),因此使用 Python
构建 Web
应用比较简单,我们就通过 8
道 Python
编程题来解决 Python Web
应用开发的相关问题吧!
知识点描述:客户端与 Web 服务器进行交互,以获取应用服务。
问题描述:向 Web 服务发送一个带有查询参数的 HTTP GET 请求,请从以下选项中选出你认为正确的选项:
A.
import requests
from urllib import parse
url = "https://www.python.org/search/"
params = {
'q': 'list'}
query = parse.urlencode(params)
response = requests.urlopen(url+'?'+query)
print(response.read())
B.
import requests
from urllib import parse
url = "https://www.python.org/search/"
params = {
'q': 'list'}
query = parse.urlencode(params)
response = requests.get(url+'?'+query)
print(response.text)
C.
import requests
from urllib import parse
url = "https://www.python.org/search/"
params = {
'q': 'list'}
query = parse.urlencode(params)
response = requests.get(url+query)
print(response.text)
D.
from urllib import parse, request
url = "https://www.python.org/search/"
params = {
'q': 'list'}
query = parse.urlencode(params)
response = request.get(url+'?'+query)
print(response.read())
正确答案: B
知识点描述:构建 TCP 服务器,通过 TCP 协议和客户端通信。
问题描述:编写程序创建一个简单 TCP 应答服务器,请从以下选项中选出你认为正确的程序:
A.
from socketserver import BaseRequestHandler, TCPServer
class MessageHandler(BaseRequestHandler):
def handle(self):
print("Get connection from {}".format(self.client_address))
while True:
message = self.request.recv(2048)
if not message:
break
else:
self.request.send("Success")
if __name__ == "__main__":
server = MessageHandler(('', 5000), TCPServer)
server.serve_forever()
B.
from socketserver import BaseRequestHandler, TCPServer
class MessageHandler(BaseRequestHandler):
def handle(self):
print("Get connection from {}".format(self.client_address))
while True:
message = self.request.recv(2048)
if not message:
break
else:
self.request.send("Success")
if __name__ == "__main__":
server = TCPServer(('', 5000), MessageHandler)
C.
from socketserver import BaseRequestHandler, TCPServer
class MessageHandler(BaseRequestHandler):
def handle(self):
print("Get connection from {}".format(self.client_address))
while True:
message = self.request.recv(2048)
if not message:
break
else:
self.request.send("Success")
if __name__ == "__main__":
server = MessageHandler()
server.serve_forever()
D.
from socketserver import BaseRequestHandler, TCPServer
class MessageHandler(BaseRequestHandler):
def handle(self):
print("Get connection from {}".format(self.client_address))
while True:
message = self.request.recv(2048)
if not message:
break
else:
self.request.send("Success")
if __name__ == "__main__":
server = TCPServer(('', 5000), MessageHandler)
server.serve_forever()
正确答案: D
知识点描述:构建 UDP 服务器,通过 UDP 协议和客户端通信。
问题描述:编写程序创建一个简单 UDP 应答服务器,请从以下选项中选出你认为正确的程序:
A.
from socketserver import BaseRequestHandler, UDPServer
from datetime import datetime
class MessageHandler(BaseRequestHandler):
def handle(self):
print("Get connection from {}".format(self.client_address))
while True:
message = self.request.recv(2048)
if not message:
break
else:
response = (str(datetime.today()) + ': SUCCESS!')
self.request.send(response)
if __name__ == "__main__":
server = UDPServer(('', 5000), MessageHandler)
server.serve_forever()
B.
from socketserver import BaseRequestHandler, UDPServer
from datetime import datetime
class MessageHandler(BaseRequestHandler):
def handle(self):
print("Get connection from {}".format(self.client_address))
while True:
message = self.request.recv(2048)
if not message:
break
else:
response = (str(datetime.today()) + ': SUCCESS!')
self.request.sendto(response)
if __name__ == "__main__":
server = UDPServer(('', 5000), MessageHandler)
server.serve_forever()
C.
from socketserver import BaseRequestHandler, UDPServer
from datetime import datetime
class MessageHandler(BaseRequestHandler):
def handle(self):
print("Get connection from {}".format(self.client_address))
message, sock = self.request
response = (str(datetime.today()) + ': SUCCESS!')
sock.sendto(response.encode('ascii'), self.client_address)
if __name__ == "__main__":
server = UDPServer(('', 5000), MessageHandler)
server.serve_forever()
D.
from socketserver import BaseRequestHandler, UDPServer
from datetime import datetime
class MessageHandler(BaseRequestHandler):
def handle(self):
print("Get connection from {}".format(self.client_address))
message, sock = self.request
response = (str(datetime.today()) + ': SUCCESS!')
sock.send(response.encode('ascii'), self.client_address)
if __name__ == "__main__":
server = UDPServer(('', 5000), MessageHandler)
server.serve_forever()
正确答案: C
知识点描述:使用 REST 接口通过网络远程控制或访问 Web 应用程序。
问题描述:构建一个标准的 REST 风格的 Web API,请从以下选项中选出你认为正确的选项:
A.
import cgi
from datetime import datetime
def not_found(environ, start_response):
start_response('404 Not Found', [('Content-Type', 'text/plain')])
return ['Not Found']
class Route:
def __init__(self):
self.route = {
}
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'] = {
k: params.getvalue(k) for k in params}
handler = self.route.get((method, path), not_found)
return handler(environ, start_response)
def register(self, method, path, function):
self.route[method.lower(), path] = function
return function
_hello_user = """
Hello {user}
{con_time}: Hello {user}!
"""
def hello_user(environ, start_response):
start_response('200 OK', [('Content-type', 'text/html')])
params = environ['params']
response = _hello_user.format(user=params.get('user'), con_time=datetime.now())
yield response.encode('utf-8')
if __name__ == '__main__':
from wsgiref.simple_server import make_server
route = Route()
route.register('GET', '/hello', hello_user)
httpd = make_server('', 8080, route)
print('Running on 8080')
httpd.serve_forever()
B.
import cgi
from datetime import datetime
def not_found(environ, start_response):
start_response('404 Not Found', [('Content-Type', 'text/plain')])
return [b'Not Found']
class Route:
def __init__(self):
self.route = {
}
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'] = {
k: params.getvalue(k) for k in params}
handler = self.route.get((method, path), not_found)
return handler(environ, start_response)
def register(self, method, path, function):
self.route[method.lower(), path] = function
return function
_hello_user = """
Hello {user}
{con_time}: Hello {user}!
"""
def hello_user(environ, start_response):
start_response('200 OK', [('Content-type', 'text/html')])
params = environ['params']
response = _hello_user.format(user=params.get('user'), con_time=datetime.now())
yield response.encode('utf-8')
if __name__ == '__main__':
from wsgiref.simple_server import make_server
route = Route()
route.register('/hello', hello_user)
httpd = make_server('', 8080, route)
print('Running on 8080')
httpd.serve_forever()
C.
import cgi
from datetime import datetime
def not_found(environ, start_response):
start_response('404 Not Found', [('Content-Type', 'text/plain')])
return [b'Not Found']
class Route:
def __init__(self):
self.route = {
}
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'] = {
k: params.getvalue(k) for k in params}
handler = self.route.get((method, path), not_found)
return handler(environ, start_response)
def register(self, method, path, function):
function = self.route[method.lower(), path]
return function
_hello_user = """
Hello {user}
{con_time}: Hello {user}!
"""
def hello_user(environ, start_response):
start_response('200 OK', [('Content-type', 'text/html')])
params = environ['params']
response = _hello_user.format(user=params.get('user'), con_time=datetime.now())
yield response.encode('utf-8')
if __name__ == '__main__':
from wsgiref.simple_server import make_server
route = Route()
route.register('GET', '/hello', hello_user)
httpd = make_server('', 8080, route)
print('Running on 8080')
httpd.serve_forever()
D.
import cgi
from datetime import datetime
def not_found(environ, start_response):
start_response('404 Not Found', [('Content-Type', 'text/plain')])
return [b'Not Found']
class Route:
def __init__(self):
self.route = {
}
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'] = {
k: params.getvalue(k) for k in params}
handler = self.route.get((method, path), not_found)
return handler(environ, start_response)
def register(self, method, path, function):
self.route[method.lower(), path] = function
return function
_hello_user = """
Hello {user}
{con_time}: Hello {user}!
"""
def hello_user(environ, start_response):
start_response('200 OK', [('Content-type', 'text/html')])
params = environ['params']
response = _hello_user.format(user=params.get('user'), con_time=datetime.now())
yield response.encode('utf-8')
if __name__ == '__main__':
from wsgiref.simple_server import make_server
route = Route()
route.register('GET', '/hello', hello_user)
httpd = make_server('', 8080, route)
print('Running on 8080')
httpd.serve_forever()
正确答案: D
知识点描述:在服务器中实现客户端连接认证功能。
问题描述:实现一个连接握手,用于进行高效认证,请从以下选项中选出你认为正确的选项:
A.
import hmac
import os
def client_auth(conn, secret_key):
message = conn.recv(64)
hash = hmac.new(secret_key, message)
digest = hash.digest()
conn.send(digest)
def server_auth(conn, secret_key):
message = os.urandom(64)
conn.send(message)
hash = hmac.new(secret_key, message)
digest = hash.digest()
resp = conn.recv(len(digest))
return digest == resp
B.
import hmac
import os
def client_auth(conn, secret_key):
message = conn.recv(64)
hash = hmac.new(secret_key, message)
digest = hash.digest()
conn.send(digest)
def server_auth(conn, secret_key):
message = os.urandom(64)
conn.send(message)
hash = hmac.new(secret_key, message)
digest = hash.digest()
resp = conn.recv(len(digest))
return hmac.compare_digest(digest, resp)
C.
import hmac
import os
def client_auth(conn, secret_key):
message = conn.recv(64)
hash = hmac.new(secret_key, message)
digest = hash.digest()
conn.send(digest)
def server_auth(conn, secret_key):
message = os.urandom(64)
conn.send(message)
hash = hmac.new(secret_key, message)
digest = hash.digest()
resp = conn.recv(digest)
return hmac.compare_digest(digest, resp)
D.
import hmac
import os
def client_auth(conn, secret_key):
message = conn.recv(64)
hash = hmac.new(secret_key, message)
digest = hash.digest()
return digest
def server_auth(conn, secret_key):
message = os.urandom(64)
conn.send(message)
hash = hmac.new(secret_key, message)
digest = hash.digest()
resp = conn.recv(len(digest))
return hmac.compare_digest(digest, resp)
正确答案: B
知识点描述:执行运行在服务器上的 Python 程序中的函数或方法。
问题描述:实现一个远程调用,以在远程服务器上执行简单的加减运算,请从以下选项中选出你认为正确的答案:
A.
from xmlrpc.server import SimpleXMLRPCServer
class AlgFunction:
_rpc_methods = ['add', 'sub', 'show']
def __init__(self, address):
self._result = []
self._server = SimpleXMLRPCServer(address, allow_none=False)
for name in self._rpc_methods:
self._server.register_function(getattr(self, name))
def add(self, num_a, num_b):
self._result.append(num_a + num_b)
return num_a + num_b
def sub(self, num_a, num_b):
self._result.append(num_a - num_b)
return num_a - num_b
def show(self):
return self._result
def serve_forever(self):
self._server.serve_forever()
if __name__ == '__main__':
algServer = AlgFunction(('', 25000))
algServer.serve_forever()
B.
from xmlrpc.server import SimpleXMLRPCServer
class AlgFunction:
_rpc_methods = ['add', 'sub', 'show']
def __init__(self, address):
self._result = []
self._server = SimpleXMLRPCServer(address, allow_none=False)
for name in self._rpc_methods:
self._server.register_function(getattr(self, name))
def add(self, num_a, num_b):
self._result.append(num_a + num_b)
return num_a + num_b
def sub(self, num_a, num_b):
self._result.append(num_a - num_b)
return num_a - num_b
def show(self):
return self._result
if __name__ == '__main__':
algServer = AlgFunction(('', 25000))
algServer.serve_forever()
C.
from xmlrpc.server import SimpleXMLRPCServer
class AlgFunction:
_rpc_methods = ['add', 'sub', 'show']
def __init__(self, address):
self._result = []
self._server = SimpleXMLRPCServer(address, allow_none=False)
for name in self._rpc_methods:
self._server.register_function(getattr(self, name))
def add(self, num_a, num_b):
self._result.append(num_a + num_b)
return num_a + num_b
def sub(self, num_a, num_b):
self._result.append(num_a - num_b)
return num_a - num_b
def show(self):
return self._result
def serve_forever(self):
self._server.serve_forever()
if __name__ == '__main__':
algServer = AlgFunction(('', 25000))
D.
from xmlrpc.server import SimpleXMLRPCServer
class AlgFunction:
_rpc_methods = ['add', 'sub', 'show']
def __init__(self, address):
self._result = []
self._server = SimpleXMLRPCServer(address, allow_none=False)
def add(self, num_a, num_b):
self._result.append(num_a + num_b)
return num_a + num_b
def sub(self, num_a, num_b):
self._result.append(num_a - num_b)
return num_a - num_b
def show(self):
return self._result
def serve_forever(self):
self._server.serve_forever()
if __name__ == '__main__':
algServer = AlgFunction(('', 25000))
algServer.serve_forever()
正确答案: A
知识点描述:客户端和服务器通过 SSL 协议认证并加密传输的数据。
问题描述:实现一个基于 sockets 的网络服务,客户端和服务器通过 SSL 协议认证并加密传输的数据,请从以下选项中选出你认为正确的答案:
A.
import ssl
from socket import socket, AF_INET, SOCK_STREAM
key_file = 'serv_key.pem'
cert_file = 'serv_cert.pem'
def simple_client(s):
while True:
mess = s.recv(2048)
if mess == b'':
break
s.sendto(mess)
print('Connection closed.')
def simple_server(addr):
s = socket(AF_INET, SOCK_STREAM)
s.bind(addr)
s.listen(1)
s_ssl = ssl.wrap_socket(s, keyfile=key_file, certfile=cert_file, server_side=True)
while True:
c, a = s_ssl.accept()
print('Got connection: ', c, a)
simple_client(c)
if __name__ == '__main__':
simple_server(('', 5000))
B.
import ssl
from socket import socket, AF_INET, SOCK_STREAM
key_file = 'serv_key.pem'
cert_file = 'serv_cert.pem'
def simple_client(s):
while True:
mess = s.recv(2048)
if mess == b'':
break
s.sendto(mess)
s.close()
print('Connection closed.')
def simple_server(addr):
s = socket(AF_INET, SOCK_STREAM)
s.bind(addr)
s.listen(1)
s_ssl = ssl.wrap_socket(s, keyfile=key_file, certfile=cert_file, server_side=True)
while True:
c, a = s_ssl.accept()
print('Got connection: ', c, a)
simple_client(c)
if __name__ == '__main__':
simple_server(('', 5000))
C.
import ssl
from socket import socket, AF_INET, SOCK_STREAM
key_file = 'serv_key.pem'
cert_file = 'serv_cert.pem'
def simple_client(s):
while True:
mess = s.recv(2048)
if mess == b'':
break
s.send(mess)
s.close()
print('Connection closed.')
def simple_server(addr):
s = socket(AF_INET, SOCK_STREAM)
s.bind(addr)
s_ssl = ssl.wrap_socket(s, keyfile=key_file, certfile=cert_file, server_side=True)
while True:
c, a = s_ssl.accept()
print('Got connection: ', c, a)
simple_client(c)
if __name__ == '__main__':
simple_server(('', 5000))
D.
import ssl
from socket import socket, AF_INET, SOCK_STREAM
key_file = 'serv_key.pem'
cert_file = 'serv_cert.pem'
def simple_client(s):
while True:
mess = s.recv(2048)
if mess == b'':
break
s.send(mess)
s.close()
print('Connection closed.')
def simple_server(addr):
s = socket(AF_INET, SOCK_STREAM)
s.bind(addr)
s.listen(1)
s_ssl = ssl.wrap_socket(s, keyfile=key_file, certfile=cert_file, server_side=True)
while True:
c, a = s_ssl.accept()
print('Got connection: ', c, a)
simple_client(c)
if __name__ == '__main__':
simple_server(('', 5000))
正确答案:D
知识点描述:通过网络连接发送和接受大型数组。
问题描述:通过网络连接发送和接受大型数组,并使用尽可能少的复制操作,请从以下选项中选出你认为正确的答案:
A.
def send_from(arr, dest):
view = memoryview(arr).cast('A')
while len(view):
nsent = dest.send(view)
view = view[nsent:]
def recv_into(arr, source):
view = memoryview(arr).cast('A')
while len(view):
nrecv = source.recv_into(view)
view = view[nrecv:]
B.
def send_from(arr, dest):
view = memoryview(arr).cast('B')
while len(view):
nsent = dest.send(view)
view = view[nsent:]
def recv_into(arr, source):
view = memoryview(arr).cast('B')
while len(view):
nrecv = source.recv_into(view)
view = view[nrecv:]
C.
def send_from(arr, dest):
view = memoryview(arr).cast('A')
while len(view):
nsent = dest.send(view)
view = view[nsent:]
def recv_into(arr, source):
view = memoryview(arr).cast('A')
while len(view):
nrecv = source.recvfrom(view)
view = view[nrecv:]
D.
def send_from(arr, dest):
view = memoryview(arr).cast('B')
while len(view):
nsent = dest.send(view)
view = view[nsent:]
def recv_into(arr, source):
view = memoryview(arr).cast('B')
while len(view):
nrecv = source.recvfrom(view)
view = view[nrecv:]
正确答案:B
https://codechina.csdn.net/LOVEmy134611/python_problem