- 案例问题背景
- python 脚本 输入字符串 输出字符串+当前时间 生成api http请求
- 脚本1
- 这是单线程的
- 单次处理单个http请求
- 同时多个请求
- 按照顺序处理
- 而不是并行处理
- 多请求 != 多线程
- 但是相关
- 使用多线程来并行处理多请求
- 使用flask或django等web服务器框架
- 可以与wsgi服务器配合使用
- 比如gunicoorn
- 或uWSGI
- 附
- 脚本1
- 脚本2
- 脚本3
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlparse
from datetime import datetime
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
query = urlparse(self.path).query
query_components = parse_qs(query)
string = query_components.get("string", [""])[0]
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
response = string + ' ' + current_time
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(bytes(response, "utf8"))
return
def run(server_class=HTTPServer, handler_class=MyHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
print('Starting httpd...')
httpd.serve_forever()
if __name__ == "__main__":
run()
from flask import Flask, request
from datetime import datetime
app = Flask(__name__)
@app.route('/', methods=['GET'])
def home():
string = request.args.get('string', '')
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
response = string + ' ' + current_time
return response
if __name__ == '__main__':
app.run(port=8000)
from django.http import HttpResponse
from datetime import datetime
def home(request):
string = request.GET.get('string', '')
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
response = string + ' ' + current_time
return HttpResponse(response)
标签:__,-%,http,string,python,datetime,字符串,import,response
From: https://blog.51cto.com/u_16055028/9124036