仅需8道题轻松掌握Python Web应用开发 | Python技能树征题

Posted 盼小辉丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了仅需8道题轻松掌握Python Web应用开发 | Python技能树征题相关的知识,希望对你有一定的参考价值。

0. 前言

使用 Python Web 框架构建 Web 应用可以使我们专注于应用程序的核心逻辑,而不必处理低级细节(例如,协议、套接字或进程和线程管理等),因此使用 Python 构建 Web 应用比较简单,我们就通过 8Python 编程题来解决 Python Web 应用开发的相关问题吧!

1. 第 1 题:客户端访问 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

2. 第 2 题:构建 TCP 服务器

知识点描述:构建 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

3. 第 3 题:构建 UDP 服务器

知识点描述:构建 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

4. 第 4 题:构建 REST 接口

知识点描述:使用 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 = """
<html>
    <head>
        <title>Hello {user}</title>
    </head>
    <body>
        <h1>{con_time}: Hello {user}!</h1>
    </body>
</html>
"""
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 = """
<html>
    <head>
        <title>Hello {user}</title>
    </head>
    <body>
        <h1>{con_time}: Hello {user}!</h1>
    </body>
</html>
"""
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 = """
<html>
    <head>
        <title>Hello {user}</title>
    </head>
    <body>
        <h1>{con_time}: Hello {user}!</h1>
    </body>
</html>
"""
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 = """
<html>
    <head>
        <title>Hello {user}</title>
    </head>
    <body>
        <h1>{con_time}: Hello {user}!</h1>
    </body>
</html>
"""
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

5. 第 5 题:客户端认证以上是关于仅需8道题轻松掌握Python Web应用开发 | Python技能树征题的主要内容,如果未能解决你的问题,请参考以下文章

仅需10道题轻松掌握Python字符串方法 | Python技能树征题

仅需10道题轻松掌握Matplotlib图形处理 | Python技能树征题

仅需6道题轻松掌握Python异常捕获 | Python技能树征题

仅需6道题轻松掌握Python时间和日期处理 | Python技能树征题

仅需5道题轻松掌握Python命令行相关标准库 | Python技能树征题

仅需6道题轻松掌握SciPy空间计算基础 | Python技能树征题