问题描述
我只有几个python api端点,它们在请求正文中获取数据。我想在每次api调用任何想法时将这些数据插入/添加到Azure Datalake吗?
示例api端点
@main.route("/order/add",methods=["POST"])
def post_add_new_order():
data = request.json
for key in data:
if not typesModule.key_type_and_value_type_are_equal(key,data[key]):
return {"err": "One of the value types is incorrect"}
想要将此数据插入到蔚蓝的数据湖
解决方法
如果要通过python包将数据添加到Azure Data Lake Storage Gen1,我们可以使用包azure-datalake-store
来实现它。
例如
- 创建服务主体
az login
az ad sp create-for-rbac -n 'Myapp' --skip-assignment
- 将服务主体分配给Azure Data Lake Storage Gen1帐户文件或文件夹访问控制。
Azure数据湖gen1的ACL具有三个权限。有读取,写入和执行。请根据您的需要进行配置。有关更多详细信息,请参阅here和here
- 代码
import json
import azure.datalake.store.lib as lib
from azure.datalake.store.core import AzureDLFileSystem
RESOURCE = 'https://datalake.azure.net/'
client_id = '42e0d***c4c522d988c4'
client_secret = 'Gbx2eK6****ClJDfQpIjoae:'
tenant = 'e4c9ab4e-bd27-40d5-8459-230ba2a757fb'
@main.route("/order/add",methods=["POST"])
def post_add_new_order():
data = request.get_json()
json_data = json.dumps(data).encode('utf-8')
adlCreds = lib.auth(tenant_id = tenant,client_secret = client_secret,client_id = client_id,resource=RESOURCE)
adlsFileSystemClient = AzureDLFileSystem(adlCreds,store_name='testbowman')
# check if the file exist
if adlsFileSystemClient.access('/test/data.json'):
#append content
with adlsFileSystemClient.open(path='/test/data.json',mode='ab') as f:
f.write(json_data)
f.write(b'\r\n')
else:
#create file and write
with adlsFileSystemClient.open(path='/test/data.json',mode='wb') as f:
f.write(json_data)
f.write(b'\r\n')
return {'you sent' : data}