Code introduction
Generates a random string, converts it to JSON format, calculates HMAC SHA256, encodes it in Base64, performs URL encoding, sends a GET request, writes the response to a file, outputs information, gets the current time, pauses execution, creates a thread, uses a queue, waits for queue items, gets the smallest elements, inserts elements, creates a counter.
Technology Stack : random, string, json, hmac, base64, urllib.parse, http.client, os, sys, datetime, time, threading, queue, select, heapq, bisect, collections
Code Type : Code function
Code Difficulty : Intermediate
import random
import string
import json
import os
import sys
import datetime
import time
import threading
import queue
import hashlib
import hmac
import base64
import urllib.parse
import http.client
import urllib.request
import ssl
import socket
import select
import itertools
import re
import io
import heapq
import bisect
import collections
def generate_random_string(length, charset=string.ascii_letters + string.digits):
return ''.join(random.choice(charset) for _ in range(length))
def xxx(arg1, arg2):
# 生成指定长度的随机字符串
random_string = generate_random_string(arg1, arg2)
# 将字符串转换为JSON格式
json_data = json.dumps({"random_string": random_string})
# 计算HMAC SHA256
secret_key = b'my_secret_key'
message = json_data.encode()
hmac_hash = hmac.new(secret_key, message, hashlib.sha256).digest()
# 将HMAC和JSON数据编码为Base64
base64_hmac = base64.b64encode(hmac_hash).decode()
base64_json = base64.b64encode(message).decode()
# 使用urllib.parse进行URL编码
url_encoded_data = urllib.parse.quote_plus(base64_json + '|' + base64_hmac)
# 使用http.client发送GET请求
connection = http.client.HTTPSConnection("httpbin.org")
connection.request("GET", "/get?" + url_encoded_data)
response = connection.getresponse()
data = response.read().decode()
connection.close()
# 使用json.loads解析JSON响应
response_json = json.loads(data)
# 使用os.path.join创建路径
path = os.path.join('data', 'response.json')
# 将响应数据写入文件
with open(path, 'w') as file:
file.write(json.dumps(response_json))
# 使用sys.stdout.write输出信息
sys.stdout.write("Random string generated and stored successfully!\n")
# 使用datetime.datetime获取当前时间
current_time = datetime.datetime.now()
# 使用time.sleep暂停执行
time.sleep(1)
# 创建线程
t = threading.Thread(target=lambda: print("Thread running"))
t.start()
# 使用queue.Queue创建队列
q = queue.Queue()
q.put("Item 1")
q.put("Item 2")
# 使用select.select等待队列中的项目
readable, writable, exceptional = select.select([sys.stdin], [], [], 1)
# 使用heapq.nsmallest获取最小元素
numbers = [10, 4, 5, 2, 3]
smallest_numbers = heapq.nsmallest(3, numbers)
# 使用bisect.insort插入元素
bisect.insort(numbers, 6)
# 使用collections.Counter创建计数器
words = "hello world"
word_counts = collections.Counter(words.split())
return random_string, response_json