programing

URL에 JSON 콜을 발신하는 방법

minimums 2023. 3. 9. 21:55
반응형

URL에 JSON 콜을 발신하는 방법

다음 API를 보고 있습니다.

http://wiki.github.com/soundcloud/api/oembed-api

그들이 제시한 예는

문의:

http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json

응답:

{
"html":"<object height=\"81\" ... ",
"user":"Forss",
"permalink":"http:\/\/soundcloud.com\/forss\/flickermood",
"title":"Flickermood",
"type":"rich",
"provider_url":"http:\/\/soundcloud.com",
"description":"From the Soulhack album...",
"version":1.0,
"user_permalink_url":"http:\/\/soundcloud.com\/forss",
"height":81,
"provider_name":"Soundcloud",
"width":0
}

URL에서만 이 JSON 개체를 가져오려면 어떻게 해야 합니까?

그들이 제공하는 것 같다.js옵션을 지정하면 JSONP가 반환됩니다.다음과 같이 JSONP를 취득할 수 있습니다.

function getJSONP(url, success) {

    var ud = '_' + +new Date,
        script = document.createElement('script'),
        head = document.getElementsByTagName('head')[0] 
               || document.documentElement;

    window[ud] = function(data) {
        head.removeChild(script);
        success && success(data);
    };

    script.src = url.replace('callback=?', 'callback=' + ud);
    head.appendChild(script);

}

getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){
    console.log(data);
});  

표준 http GET 요구로 실행할 수 있습니다.그런 다음 JSON.parse()를 사용하여 json 객체로 만들 수 있습니다.

function Get(yourUrl){
    var Httpreq = new XMLHttpRequest(); // a new request
    Httpreq.open("GET",yourUrl,false);
    Httpreq.send(null);
    return Httpreq.responseText;          
}

그리고나서

var json_obj = JSON.parse(Get(yourUrl));
console.log("this is the author name: "+json_obj.author_name);

기본적으로는 그렇다

현대의 JS에서는 URL에서 ES6에 전화를 걸어 ES7을 사용하여 JSON 데이터를 얻을 수 있습니다.async/awaitFetch에서 Response 객체를 "패킹 해제"하여 다음과 같이 JSON 데이터를 가져옵니다.

const getJSON = async url => {
  const response = await fetch(url);
  if(!response.ok) // check if response worked (no 404 errors etc...)
    throw new Error(response.statusText);

  const data = response.json(); // get JSON from the response
  return data; // returns a promise, which resolves to this data value
}

console.log("Fetching data...");
getJSON("https://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json").then(data => {
  console.log(data);
}).catch(error => {
  console.error(error);
});

예외/오류 처리를 무시하면 위의 방법을 몇 줄로 줄일 수 있습니다(보통 불필요한 오류가 발생할 수 있으므로 권장하지 않습니다).

const getJSON = async url => {
  const response = await fetch(url);
  return response.json(); // get JSON from the response 
}

console.log("Fetching data...");
getJSON("https://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json")
  .then(data => console.log(data));

URL이 웹사이트와 같은 도메인에 있지 않기 때문에 JSONP를 사용해야 합니다.

예: (jQuery의 경우):

$.getJSON(
    'http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', 
    function(data) { ... }
);

이 조작은, 다음과 같이 행해집니다.<script>다음과 같이 태그 붙입니다.

<script src="http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=someFunction" type="text/javascript"></script>

그 후, 서버는 Javascript를 발신해,someFunction검색해야 할 데이터가 있습니다.
"some Function은 jQuery에 의해 생성된 내부 콜백으로, 콜백을 호출합니다.

DickFeynman의 답변은 JQuery가 적합하지 않거나 필요하지 않은 상황에서 실행 가능한 솔루션입니다.ComFreek에서 알 수 있듯이 서버 측에서 CORS 헤더를 설정해야 합니다.만약 그것이 당신의 서비스이고, 보안에 관한 더 큰 문제를 다룰 수 있다면, 그것은 완전히 실현 가능합니다.

다음은 Flask 서비스 목록, CORS 헤더 설정, 데이터베이스에서 데이터 가져오기, JSON으로 응답 및 클라이언트 측에서 DickFeynman의 접근방식을 만족스럽게 사용할 수 있는 목록입니다.

#!/usr/bin/env python 
from __future__ import unicode_literals
from flask      import Flask, Response, jsonify, redirect, request, url_for
from your_model import *
import os
try:
    import simplejson as json;
except ImportError:
    import json
try:
    from flask.ext.cors import *
except:
    from flask_cors import *

app = Flask(__name__)

@app.before_request
def before_request():
try:
    # Provided by an object in your_model
    app.session = SessionManager.connect()
except:
    print "Database connection failed."

@app.teardown_request
def shutdown_session(exception=None):
    app.session.close()

# A route with a CORS header, to enable your javascript client to access 
# JSON created from a database query.
@app.route('/whatever-data/', methods=['GET', 'OPTIONS'])
@cross_origin(headers=['Content-Type'])
def json_data():
    whatever_list = []
    results_json  = None
    try:
        # Use SQL Alchemy to select all Whatevers, WHERE size > 0.
        whatevers = app.session.query(Whatever).filter(Whatever.size > 0).all()
        if whatevers and len(whatevers) > 0:
            for whatever in whatevers:
                # Each whatever is able to return a serialized version of itself. 
                # Refer to your_model.
                whatever_list.append(whatever.serialize())
             # Convert a list to JSON. 
             results_json = json.dumps(whatever_list)
    except SQLAlchemyError as e:
        print 'Error {0}'.format(e)
        exit(0)

    if len(whatevers) < 1 or not results_json:
        exit(0)
    else:
        # Because we used json.dumps(), rather than jsonify(), 
        # we need to create a Flask Response object, here.
        return Response(response=str(results_json), mimetype='application/json')

if __name__ == '__main__':
    #@NOTE Not suitable for production. As configured, 
    #      your Flask service is in debug mode and publicly accessible.  
    app.run(debug=True, host='0.0.0.0', port=5001) # http://localhost:5001/

your_model에는 임의의 시리얼라이제이션 메서드 및 데이터베이스 접속 매니저(큰 시스템 또는 모델/View/Control 아키텍처에서 데이터베이스 세션 작성을 집중화하기 위해 약간의 리팩터링을 견딜 수 있지만)가 포함되어 있습니다.이것은 postgre를 사용할 때 발생합니다.SQL이지만 서버 측 데이터 스토어를 쉽게 사용할 수 있습니다.

#!/usr/bin/env python 
# Filename: your_model.py
import time
import psycopg2
import psycopg2.pool
import psycopg2.extras
from   psycopg2.extensions        import adapt, register_adapter, AsIs
from   sqlalchemy                 import update
from   sqlalchemy.orm             import *
from   sqlalchemy.exc             import *
from   sqlalchemy.dialects        import postgresql
from   sqlalchemy                 import Table, Column, Integer, ForeignKey
from   sqlalchemy.ext.declarative import declarative_base

class SessionManager(object):
    @staticmethod
    def connect():
        engine = create_engine('postgresql://id:passwd@localhost/mydatabase', 
                                echo = True)
        Session = sessionmaker(bind = engine, 
                               autoflush = True, 
                               expire_on_commit = False, 
                               autocommit = False)
    session = Session()
    return session

  @staticmethod
  def declareBase():
      engine = create_engine('postgresql://id:passwd@localhost/mydatabase', echo=True)
      whatever_metadata = MetaData(engine, schema ='public')
      Base = declarative_base(metadata=whatever_metadata)
      return Base

Base = SessionManager.declareBase()

class Whatever(Base):
    """Create, supply information about, and manage the state of one or more whatever.
    """
    __tablename__         = 'whatever'
    id                    = Column(Integer, primary_key=True)
    whatever_digest       = Column(VARCHAR, unique=True)
    best_name             = Column(VARCHAR, nullable = True)
    whatever_timestamp    = Column(BigInteger, default = time.time())
    whatever_raw          = Column(Numeric(precision = 1000, scale = 0), default = 0.0)
    whatever_label        = Column(postgresql.VARCHAR, nullable = True)
    size                  = Column(BigInteger, default = 0)

    def __init__(self, 
                 whatever_digest = '', 
                 best_name = '', 
                 whatever_timestamp = 0, 
                 whatever_raw = 0, 
                 whatever_label = '', 
                 size = 0):
        self.whatever_digest         = whatever_digest
        self.best_name               = best_name
        self.whatever_timestamp      = whatever_timestamp
        self.whatever_raw            = whatever_raw
        self.whatever_label          = whatever_label

    # Serialize one way or another, just handle appropriately in the client.  
    def serialize(self):
        return {
            'best_name'     :self.best_name,
            'whatever_label':self.whatever_label,
            'size'          :self.size,
        }

돌이켜보면 Python dict가 아닌 목록으로 오브젝트를 시리얼화하여 플라스크 서비스에서의 처리를 심플화했을 가능성이 있습니다.또, 플라스크 실장에서는, (데이터베이스 콜은 루트 핸들러에 짜넣어서는 안 됩니다), 이것을 개선할 수 있습니다.e고객의 개발 환경에서 유효한 솔루션

또한 JQuery를 피하라고 제안하는 것도 아닙니다.하지만 JQuery가 없는 경우에는 이런저런 이유로 이 방법이 합리적인 대안으로 보입니다.

어쨌든 효과가 있다.

클라이언트에 대한 DickFeynman의 접근방식을 다음과 같이 구현합니다.

<script type="text/javascript">
    var addr = "dev.yourserver.yourorg.tld"
    var port = "5001"

    function Get(whateverUrl){
        var Httpreq = new XMLHttpRequest(); // a new request
        Httpreq.open("GET",whateverUrl,false);
        Httpreq.send(null);
        return Httpreq.responseText;          
    }

    var whatever_list_obj = JSON.parse(Get("http://" + addr + ":" + port + "/whatever-data/"));
    whatever_qty = whatever_list_obj.length;
    for (var i = 0; i < whatever_qty; i++) {
        console.log(whatever_list_obj[i].best_name);
    }
</script>

콘솔의 출력은 일람표시하지 않습니다만, 그 외의 출력은 일람표시하고 있습니다.best_name 문자열.

요점 상세:what_list_obj는 javascript 네임스페이스에서 사용할 수 있습니다.무엇을 하고 싶은지 모르겠지만...여기에는 D3.js를 사용한 그래픽 생성, OpenLayer 또는 CesiumJs를 사용한 매핑 또는 DOM에 존재할 필요가 없는 일부 중간값 계산이 포함됩니다.

bog standard HTTP GET Request를 작성합니다.응용프로그램/json 내용 유형과 JSON 문서를 본문으로 하는 BOG 표준 HTTP 응답을 얻을 수 있습니다.그런 다음 이것을 해석합니다.

이 'JavaScript'에 태그를 붙였고('브라우저 내 웹페이지'에서'를 의미한다고 생각되므로 서드파티 서비스일 것으로 생각됩니다).명시적 회피책(JSONP 등)이 마련되지 않으면 JavaScript에서 원격 URI에서 데이터를 가져올 수 없습니다.

링크한 문서를 읽고 있습니다.JSONP는 사용할 수 있지만, 'json'이 아니라 'syson'이라고 말하고 콜백을 지정해야 합니다.format=syslog&callback=foo

다음으로 콜백 함수를 정의할 수 있습니다.

function foo(myData) { 
    // do stuff with myData
}

그런 다음 데이터를 로드합니다.

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = theUrlForTheApi;
document.body.appendChild(script);

언급URL : https://stackoverflow.com/questions/2499567/how-to-make-a-json-call-to-an-url

반응형