在def request()中直接返回响应,可以通过以下步骤实现:
以下是一个示例代码:
import requests
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/request', methods=['GET'])
def request():
url = 'https://example.com' # 替换为实际的URL
headers = {'User-Agent': 'Mozilla/5.0'} # 根据需要设置请求头
response = requests.get(url, headers=headers) # 发送GET请求并获取响应
# 对响应进行处理和解析
status_code = response.status_code # 获取响应状态码
content_type = response.headers.get('Content-Type') # 获取响应头中的Content-Type字段
body = response.text # 获取响应体
# 构建响应对象并返回
return jsonify({
'status_code': status_code,
'content_type': content_type,
'body': body
})
if __name__ == '__main__':
app.run()
在上述示例中,我们使用了Flask作为Web框架,并创建了一个路由'/request',当收到GET请求时,会调用request()函数。在request()函数中,我们使用requests库发送了一个GET请求,并将响应保存在response变量中。然后,我们对响应进行了处理和解析,提取了响应状态码、Content-Type字段和响应体。最后,我们使用Flask的jsonify函数构建了一个包含处理后响应信息的JSON响应对象,并将其返回给调用者。
请注意,上述示例仅为演示目的,实际情况中可能需要根据具体需求进行适当的修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云