2

我正在尝试使用 Tableau 计算字段来使用我的 python 脚本,该脚本获取 JSON 数据。我的最终目标是以表格格式将这些数据放入画面中。

我读过 JSON 更容易进入与数据框对象相反的画面。

我目前在 Spyder 程序中使用它。并执行此操作以获取我的数据。

print (get1D ("2019-02-02", "2019-02-05", "Tableau", "Limits"))

在我的计算字段中,我收到错误:“错误解析数”

.format(status_code))

错误信息:

在此处输入图像描述

将这些数据放入画面中的任何帮助将不胜感激。这是我的完整脚本。

SCRIPT_INT(  

import time  
import requests  
import json  
import pandas as pd  
import re  
import urllib3  
import math  

from io import StringIO  

from datetime import datetime, date,timedelta  
from pandas.tseries.offsets import BDay  
from urllib.parse import urlencode  
from flask import json  


def call_api(url, request_dict, post):     


    if post:  
        header = {'content-type':'application/json'}  

        resp = requests.post(url, data=json.dumps(request_dict), auth=('user', 'pass'), headers = header, verify=False)  
    else:  
        url = url + urlencode(request_dict)  


        resp = requests.get(url, auth=('user', 'pass'), verify=False)  




    status_code = resp.status_code  

    if status_code == 401:  
        raise ValueError("There is an error with the connection.\nLogin failed. \nNot authorized. Please check your credentials and try again.\nStatus code {}".format(status_code))  
    elif status_code == 404:  
        raise ValueError("There is an error with the connection.\nCould not connect to the server.\nStatus code {}".format(status_code))  
    elif status_code == 200:  
        pass  
    else:  
        raise ValueError("There is an error with the connection.\nStatus code {}".format(status_code))  

    return resp  


def getData (startDate, endDate, nodeName, Type, Id):  



    request_dict = [{  
        "hierarchy": "Tableau",  
        "nodeName": nodeName,  
        "FilterId": Type,  
        "Id": Id ,  
    }]  


    url = "https://sampleurl/startDate={0}&endDate={1}"   



    startDate = datetime.strptime(startDate, '%Y-%m-%d')  
    startDate = startDate.strftime ('%Y%m%d')  

    endDate = datetime.strptime(endDate, '%Y-%m-%d')  
    endDate = endDate.strftime ('%Y%m%d')  


    url = url.format(startDate, endDate)  


    resp = call_api(url, request_dict, True)   

    return resp.json ()  

def get1D(startDate, endDate, nodeName, Type):  
    return getData (startDate, endDate, nodeName, Type, 1)  
)  
4

2 回答 2

1

查看 Tableau 的在 Tableau 中创作 Python 计算的指南。

一般来说,格式需要是这样的:

SCRIPT_INT("import xyz foo=_arg1+_arg2 return foo", SUM([A number]), SUM([Another Number])

据我所知,您需要在计算字段中添加引号,将需要传递的任何字段变量替换为 _argX,在计算字段中添加逗号,然后将字段列表作为这些参数传递。

请注意,当您在 Tableau 计算字段窗口中看到错误“计算包含错误”时,表明问题出在 Tableau 计算字段(格式化/编译)中,不一定与基础 Python 相关。(您看到的错误是一条红鲱鱼。Tableau 计算字段解释器将“.”视为小数,并期望在其后面收到一个数字。)在计算字段窗口中,Tableau 将无法检查底层 Python - 它仅将其作为字符串传递给 TabPy。反之亦然 - 在 Tableau 计算字段窗口中看到“此计算有效”并不一定意味着 Python 脚本将正确返回。

希望这可以帮助。

编辑以回应评论:

以下是使用您在问题中提供的代码的示例。

  • 将 Python 脚本中的双引号替换为单引号。这样,Tableau 将能够区分自己的双引号。(Tableau 与 Python 的相同之处在于它对双引号和单引号的处理方式相同。)
  • 将 getData() 的输入参数替换为 _arg1 到 _arg4。
  • 在 Python 脚本作为字符串传递之后,将 [开始日期]、[结束日期]、[节点名称] 和 [类型] 作为 args 传递。(这些作为 _arg1 到 _arg4 被植入到字符串中。(ATTR() 在这里可能不是正确的聚合方法 - 您必须进行试验。)
  • 计算字段现在至少可以编译,但是,我不能保证它会在 Python 端执行,或者它会完成你想要做的事情。
  • 我不确定 get1D() 将如何在这里做出反应。您可能也必须将 _arg1 到 _arg4 作为参数放在那里。有一些工作需要完成 - 甚至可能需要重新格式化代码以接受 Tableau args。

请务必阅读 TabPy 文档,以获得比我在此处提供的更多说明。另外,这是一篇很好的博客文章。如果使用得当,它的功能非常强大。

祝你好运!

SCRIPT_INT(  

"import time  
import requests  
import json  
import pandas as pd  
import re  
import urllib3  
import math  

from io import StringIO  

from datetime import datetime, date,timedelta  
from pandas.tseries.offsets import BDay  
from urllib.parse import urlencode  
from flask import json  


def call_api(url, request_dict, post):     


    if post:  
        header = {'content-type':'application/json'}  

        resp = requests.post(url, data=json.dumps(request_dict), auth=('user', 'pass'), headers = header, verify=False)  
    else:  
        url = url + urlencode(request_dict)  


        resp = requests.get(url, auth=('user', 'pass'), verify=False)  




    status_code = resp.status_code  

    if status_code == 401:  
        raise ValueError('There is an error with the connection.\nLogin 
        failed. \nNot authorized. Please check your credentials and try 
    again.\nStatus code {}'.format(status_code))  
    elif status_code == 404:  
        raise ValueError('There is an error with the connection.\nCould not 
        connect to the server.\nStatus code {}'.format(status_code))  
    elif status_code == 200:  
        pass  
    else:  
        raise ValueError('There is an error with the connection.\nStatus 
    code {}'.format(status_code))  

    return resp  


def getData (startDate, endDate, nodeName, Type, Id):  



    request_dict = [{  
        'hierarchy': 'Tableau',  
        'nodeName': nodeName,  
        'FilterId': Type,  
        'Id': Id ,  
    }]  


    url = 'https://sampleurl/startDate={0}&endDate={1}'  



    startDate = datetime.strptime(startDate, '%Y-%m-%d')  
    startDate = startDate.strftime ('%Y%m%d')  

    endDate = datetime.strptime(endDate, '%Y-%m-%d')  
    endDate = endDate.strftime ('%Y%m%d')  


    url = url.format(startDate, endDate)  


    resp = call_api(url, request_dict, True)   

    return resp.json ()  

def get1D(startDate, endDate, nodeName, Type):  
    return getData (_arg1, _arg2, _arg3, _arg4, 1)"
,
ATTR([Start Date]),ATTR([End Date]),ATTR([Node Name], ATTR([Type]
)  
于 2019-03-07T05:58:42.167 回答
1

为后代添加此答案并简化我以前的答案和结果线程。

问题中提供的 Python 脚本旨在将数据直接加载到 Tableau 中。TabPy 旨在对 Tableau 中已经存在的数据进行操作,而不是作为摄取的来源。

这里有必要将 Python 脚本的输出放置到中间位置,然后 Tableau 可以将其连接到该中间位置。

于 2019-03-08T01:29:25.290 回答