python实现web请求与回复

一、作为客户端发送请求(使用requests库)
import
 requests

# 发送GET请求
response 
= requests.get("https://api.example.com/data")
print("GET响应状态码:", response.status_code)
print("GET响应内容:", response.text)

# 发送带参数的GET请求
params 
= {"key1": "value1", "key2": "value2"}
response 
= requests.get("https://api.example.com/data", params=params)

# 发送POST请求(表单数据)
data 
= {"username": "admin", "password": "secret"}
response 
= requests.post("https://api.example.com/login", data=data)

# 发送POST请求(JSON数据)
json_data 
= {"name": "Alice", "age": 30}
response 
= requests.post("https://api.example.com/users", json=json_data)

# 处理响应
if response.status_code == 200:
    print("POST响应JSON:", response.json())
else:
    print("请求失败,状态码:", response.status_code)
安装requests库:
pip install requests
二、作为服务端接收请求(使用Flask框架)
from flask import Flask, request,
 jsonify

app 
= Flask(__name__)

# 处理GET请求
@app.route('/')
def home():
    return "Welcome to the Python Web Server!"

# 处理带路径参数的GET请求
@app.route('/user/<username>')
def show_user(username):
    return f"User: {username}"

# 处理POST请求(表单数据)
@app.route('/login', methods=['POST'])
def login():
    username 
= request.form.get('username')
    password 
= request.form.get('password')
    return f"Received: {username}/{password}"

# 处理POST请求(JSON数据)
@app.route('/api', methods=['POST'])
def handle_json():
    data 
= request.
json
    return jsonify({"received_data": data})

if __name__ == '__main__':
    app
.run(host='0.0.0.0', port=5000, debug=True)
安装Flask库:
pip install flask
三、完整示例流程
1. 启动服务端(保存为server.py)
from flask import Flask, request,
 jsonify

app 
= Flask(__name__)

@app.route('/api', methods=['POST'])
def handle_api():
    req_data 
= request.
json
    return jsonify({
        "status": "success",
        "received": req_data,
        "message": "Data processed successfully"
    })

if __name__ == '__main__':
    app
.run(port=5000)
2. 客户端脚本(保存为client.py)
import
 requests
import
 json

response 
= requests.post(
    "http://localhost:5000/api",
    json
={"name": "John", "action": "update"}
)

print("Status Code:", response.status_code)
print("Response Body:", json.dumps(response.json(), indent=2))
3. 运行流程
# 第一个终端窗口
python server.py

# 第二个终端窗口
python client.py

四、关键点说明
1. 客户端常用功能:
• requests.get()/requests.post() 发送请求
• params 参数添加URL参数
• data 发送表单数据
• json 发送JSON数据
• response.text 获取文本响应
• response.json() 解析JSON响应
2. 服务端关键功能:
• @app.route() 定义路由
• request.form 获取表单数据
• request.json 获取JSON数据
• jsonify() 返回JSON响应

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值