2017-03-20 21 views
0

現在、HTMLファイルとPythonファイルがあります。 PythonファイルはYELPのAPIを使用してJSONデータを返します。 HTMLを使ってそのデータをWebページに表示するにはどうすればよいですか? JavaScriptのdocument.getElementById("id").innerHTML = JSONDATAのような機能はありますか?PythonファイルからHTMLにJSONデータを表示

詳細が必要な場合はお知らせください。これは初めての投稿と初めてのAPIの使用/ウェブサイトの作成です。私はJSONデータが見栄えが良くないと理解していますが、辞書に入れて後でソートします。基本的には、PythonファイルからHTMLファイルにデータを表示する方法を知りたいだけです。また、役に立つチュートリアルを自由にリンクすることもできます。

代わりにJavascriptを使用するように提案されている次のNode.jsコードが見つかりました。ここで私はトークン/秘密を入れますか?そして、どうすれば私のHTMLファイルでそれを呼び出すことができますか...ありがとう。

/* require the modules needed */ 
var oauthSignature = require('oauth-signature'); 
var n = require('nonce')(); 
var request = require('request'); 
var qs = require('querystring'); 
var _ = require('lodash'); 

/* Function for yelp call 
* ------------------------ 
* set_parameters: object with params to search 
* callback: callback(error, response, body) 
*/ 
var request_yelp = function(set_parameters, callback) { 

    /* The type of request */ 
var httpMethod = 'GET'; 
/* The url we are using for the request */ 
var url = 'http://api.yelp.com/v2/search'; 

/* We can setup default parameters here */ 
var default_parameters = { 
location: 'San+Francisco', 
sort: '2' 
}; 

/* We set the require parameters here */ 
var required_parameters = { 
oauth_consumer_key : process.env.oauth_consumer_key, 
oauth_token : process.env.oauth_token, 
oauth_nonce : n(), 
oauth_timestamp : n().toString().substr(0,10), 
oauth_signature_method : 'HMAC-SHA1', 
oauth_version : '1.0' 
}; 

/* We combine all the parameters in order of importance */ 
var parameters = _.assign(default_parameters, set_parameters,  required_parameters); 

/* We set our secrets here */ 
var consumerSecret = process.env.consumerSecret; 
var tokenSecret = process.env.tokenSecret; 

/* Then we call Yelp's Oauth 1.0a server, and it returns a signature */ 
/* Note: This signature is only good for 300 seconds after the  oauth_timestamp */ 
var signature = oauthSignature.generate(httpMethod, url, parameters,  consumerSecret, tokenSecret, { encodeSignature: false}); 

/* We add the signature to the list of paramters */ 
parameters.oauth_signature = signature; 

/* Then we turn the paramters object, to a query string */ 
var paramURL = qs.stringify(parameters); 

/* Add the query string to the url */ 
var apiURL = url+'?'+paramURL; 

/* Then we use request to send make the API Request */ 
request(apiURL, function(error, response, body){ 
return callback(error, response, body); 
}); 

}; 
+0

答えは、あなたがしようとしていることや方法に応じて複数の方法があります。 jsonを動的にロードしようとしている場合、jquery jQuery.getJSONをロードすることをお勧めします(明らかに、jqueryをロードしてコード内で使用する必要があります) –

+0

JavaScriptまたはJavaScriptライブラリを使用してアクセスする方が簡単かもしれませんAPI。 – brandaemon

+0

これは私が元にしたかったものですが、YelpはAPIへのJavaScriptコールのサンプルを持っておらず、自分自身でやる方法がわかりませんでした。私が知っていた言語の実例を探していました。 – Sam

答えて

0

あなたのhtmlファイルにJqueryを含め、あなたのAPIを呼び出すためのjQueryのAjaxを使用することができます。

$.ajax({ 
    method: "GET", 
    url: "api_url", 
}).done(function(response) { 
    $('#divId').append(response); 
    }); 
HTMLファイルで

<div id="divId"></div> 

Jquery Ajax Documentation

+0

Pythonに接するJQuery Ajaxを使用するのですか?トークンキー、秘密キー、コンシューマーキー、コンシューマーシークレットを使用してAPIを認証してから署名する方法が必要ですが、私が持っているPythonコードはすべてこれを行いますが、今はHTMLファイル内でそのPythonコードを呼び出して表示したいだけです。 – Sam

0

私は似たような状況がありました。 HTMLページにAWSアカウントのIAMユーザーを表示する必要がありました。 AWS boto3 Pythonクライアントを使用してすべてのIAMユーザーを取得し、JSONファイルを作成しました。その後、HTMLファイルからJSONファイルを読み込み、テーブル内のすべてのユーザーを表示しました。ここで

はPythonコードIAM.PYです:

<!DOCTYPE html> 
<html> 
    <head> 
     <!-- Latest compiled and minified CSS --> 
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 
     <title>IAM User List</title> 
     <style type="text/css"> 
      body{ 
       margin: 20px; 
      } 
     </style> 
    </head> 
    <body> 
     <div class="container"> 
      <table class="table table-responsive table-hover table-bordered"> 
       <thead> 
        <tr> 
         <th>User ID</th> 
         <th>User Name</th> 
         <th>Path</th> 
         <th>Create Date</th> 
         <th>Arn</th>      
        </tr>     
       </thead> 
       <tbody id="iam_tbody"> 

       </tbody> 
      </table> 
     </div> 
     <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> 
     <script type="text/javascript"> 
      $(document).ready(function(){ 
       $.ajax({ 
        method: "GET", 
        url: "http://localhost/iam/iam.json", 
       }).done(function(response){ 
        user_list = response.Users; 
        for(i = 0; i<user_list.length; i++){ 
         tr = "<tr>"; 
         tr += "<td>"; 
         tr += user_list[i]["UserId"]; 
         tr += "</td>"; 
         tr += "<td>"; 
         tr += user_list[i]["UserName"]; 
         tr += "</td>"; 
         tr += "<td>"; 
         tr += user_list[i]["Path"]; 
         tr += "</td>"; 
         tr += "<td>"; 
         tr += user_list[i]["CreateDate"]; 
         tr += "</td>"; 
         tr += "<td>"; 
         tr += user_list[i]["Arn"]; 
         tr += "</td>"; 
         tr += "<tr>"; 
         $("#iam_tbody").append(tr); 
        } 
       }); 
      }); 
     </script> 
    </body> 
</html> 

出力

IAM DEMO OUTPUT:ここ

import boto3 
import os 
import subprocess 
import json 
iam_client = boto3.client('iam') 

def list_user_cli(): 
    list_cmd = "aws iam list-users" 
    output = subprocess.check_output(list_cmd, shell = True) 
    output = str(output.decode('ascii')) 
    return output 

def write_json_file(filename, data): 
    try: 
     with open(filename, "w") as f: 
      f.writelines(data) 
     print(filename + " has been created.") 
    except Exception as e: 
     print(str(e)) 

if __name__ == "__main__": 
    filename = "iam.json" 
    data = list_user_cli() 
    write_json_file(filename, data) 

は、HTMLファイルIAM.HTMLです

関連する問題