401(未经授权)使用AutoDesk API时出错

2024-04-26 20:55:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Django应用程序,我正在使用其中的.stl、.stp和.igs文件。我必须在HTML模板中显示这些文件,我正在尝试使用AutoDesk API来实现这一点。我首先创建了一个帐户并进行了身份验证,但在显示图像时遇到了问题

以下是包含身份验证和将图像上载到bucket的视图:

def viewer(request):
    req = { 'client_id' : CLIENT_ID, 'client_secret': CLIENT_SECRET, 'grant_type' : 'client_credentials','scope':'code:all bucket:create bucket:read data:read data:write'}
    resp = requests.post(BASE_URL+'/authentication/v1/authenticate', req)
    if resp.status_code == 200:
        TOKEN = resp.json()['token_type'] + " " + resp.json()['access_token']
    else:
        print('Get Token Failed! status = {0} ; message = {1}'.format(resp.status_code,resp.text))
        TOKEN = ""
    filepath = "C:/Users/imgea/desktop/"
    filename = '55.stl'
    my_file = Path(filepath + filename)
        #check package file (*.zip) exists
    if my_file.is_file():
        filesize = os.path.getsize(filepath + filename)
        # encoding the file name
        if sys.version_info[0] < 3:
            encodedfilename= urllib.pathname2url(filename)
        else:
            encodedfilename= urllib.parse.quote(filename) 
        resp = requests.put(BASE_URL + '/oss/v2/buckets/'+'bucket'+'/objects/'+ encodedfilename, headers={'Authorization': TOKEN,'Content-Type' : 'application/octet-stream','Content-Length' : str(filesize)},data= open(filepath+filename, 'rb'))
        if resp.status_code == 200:
            urn = resp.json()['objectId']
        else:
            print('Upload File to Bucket of Data Management Failed! status ={0} ; message = {1}'.format(resp.status_code,resp.text ))
            urn = "none"
    else:
        print(' ' + filename + ' does not exist')
        urn = "none"
    urn_bytes = urn.encode('ascii')
    base64_bytes = base64.b64encode(urn_bytes)
    base64_urn = base64_bytes.decode('ascii')

    headers = {
    'Authorization': TOKEN,
    'Content-Type': 'application/json',
    }
    data = '{"input": { "urn": "' + base64_urn + '"},"output": {"destination": {"region": "us" }, "formats": [{ "type": "obj" }]}}'
    resp = requests.post(BASE_URL + '/modelderivative/v2/designdata/job', headers=headers, data=data)
    context = {
        'token': "'"+TOKEN+"'",
        'urn': "'"+urn+"'",
    }
    return render(request, 'viewer.html', context)

以下是模板:

<body>
    <!-- The Viewer will be instantiated here -->
    <div id="MyViewerDiv"></div>
    <!-- The Viewer JS -->
    <script src="https://developer.api.autodesk.com/modelderivative/v2/viewers/6.*/viewer3D.min.js"></script>
    <!-- Developer JS -->
    <script>
        var viewer;
        var options = {
            env: 'AutodeskProduction',
            getAccessToken: function(onGetAccessToken) {
                var accessToken = {{token|safe}};
                var expireTimeSeconds = 86400;
                onGetAccessToken(accessToken, expireTimeSeconds);
            },
            api: 'derivativeV2'    // for models uploaded to EMEA change this option to 'derivativeV2_EU'
        };
        var documentId = {{urn|safe}};
        Autodesk.Viewing.Initializer(options, function onInitialized(){
            Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
        });
        function onDocumentLoadSuccess(doc) {
            // A document contains references to 3D and 2D geometries.
            var geometries = doc.getRoot().search({'type':'geometry'});
            if (geometries.length === 0) {
                console.error('Document contains no geometries.');
                return;
            }
            // Choose any of the avialable geometries
            var initGeom = geometries[0];
            // Create Viewer instance
            var viewerDiv = document.getElementById('MyViewerDiv');
            var config = {
                extensions: initGeom.extensions() || []
            };
            viewer = new Autodesk.Viewing.Private.GuiViewer3D(viewerDiv, config);
            // Load the chosen geometry
            var svfUrl = doc.getViewablePath(initGeom);
            var modelOptions = {
                sharedPropertyDbPath: doc.getPropertyDbPath()
            };
            viewer.start(svfUrl, modelOptions, onLoadModelSuccess, onLoadModelError);
        }
        function onDocumentLoadFailure(viewerErrorCode) {
            console.error('onDocumentLoadFailure() - errorCode:' + viewerErrorCode);
        }
        function onLoadModelSuccess(model) {
            console.log('onLoadModelSuccess()!');
            console.log('Validate model loaded: ' + (viewer.model === model));
            console.log(model);
        }
        function onLoadModelError(viewerErrorCode) {
            console.error('onLoadModelError() - errorCode:' + viewerErrorCode);
        }
    </script>
</body>

根据这些代码块,我可以成功地获得访问令牌和图像urn。同时,它们被正确地发送到模板。但我也犯了一个错误 { "developerMessage":"Token is not provided in the request.", "moreInfo": "https://forge.autodesk.com/en/docs/oauth/v2/developers_guide/error_handling/", "errorCode": "AUTH-010"}。如何解决此问题并以HTML显示3D文件


Tags: tokendataifvarstatuscodefunctionfilename
1条回答
网友
1楼 · 发布于 2024-04-26 20:55:32

请注意,在将令牌添加到授权头时,必须在令牌前面加上“Bearer”,因此头应该是"Authorization": "<token>",而不是"Authorization": "Bearer <token>"

相关问题 更多 >