使用Flask创建一个API来生产流数据
from flask import Flask, jsonify
from faker import Faker
import datetime
app = Flask(__name__)
fake = Faker()
seq_number = 0
@app.route("/", methods=["GET"])
def random_user():
global seq_number
seq_number += 1
current_time = datetime.datetime.now()
user = {
"seq_number": seq_number,
"datetime": current_time,
"timestamp": int(current_time.timestamp()),
"name": fake.name(),
"username": fake.user_name(),
"email": fake.email(),
"address": {
"street": fake.street_address(),
"city": fake.city(),
"state": fake.state(),
"zipcode": fake.zipcode(),
"country": fake.country()
},
"date_of_birth": str(fake.date_of_birth()), # 注意: 此处将日期转为字符串格式
"phone_number": fake.phone_number(),
"website": fake.url(),
"profile_pic": fake.image_url(),
"job_title": fake.job(),
"company": fake.company(),
"ssn": fake.ssn(),
"about": fake.text(),
# 新增的字段
"random_bool": fake.pybool(),
"random_list": fake.pylist(nb_elements=5, variable_nb_elements=True), # 生成包含5个元素的随机列表
"random_string": fake.pystr(),
"random_int": fake.pyint(),
"random_float": fake.pyfloat(left_digits=4, right_digits=2, positive=True) # 例如,生成一个正的浮点数,整数部分有4位,小数部分有2位
}
return jsonify(user)
if __name__ == "__main__":
app.run()
部署
gunicorn app:app -b 0.0.0.0:5000 --worker-tmp-dir . -D
从API拿数据
import requests
# API的URL地址
url = "http://linux.a:5000"
# 使用GET请求从API获取数据
response = requests.get(url)
# 确保请求成功
if response.status_code == 200:
data = response.json() # 假设API返回的是JSON格式的数据
print(data)
else:
print("Error:", response.status_code)