Skip to content
조회 수 3433 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

Python으로 XML-RPC 서버 구축

 

한 15년전 즈음되나?

그땐 php에 빠져 허우적댔는데,,,

 

한동안 잊고있다가

 

나이 45에...

느닷없이 python으로 xpressengine 블로그 글쓰기를 해봐야겠다고 생각했다.

그래서 한번 해보니 대충 되긴된다.

 

 

import xmlrpc.client

API_URL = "http://econo.urin79.com/attention/api"

class NaverBlog(object):
    def __init__(self, user_id, api_key):
        self.__server = None
        self.__user_id = user_id
        self.__api_key = api_key
        self.__categories = []

        try:
            self.__set_categories()
        except Exception as e:
            raise e

    def __client(self):
        if self.__server is None:
            self.__server = xmlrpc.client.ServerProxy(API_URL)

        return self.__server

    def __set_categories(self):
        categories = self.__client().metaWeblog.getCategories(self.__user_id,
                                                              self.__user_id,
                                                              self.__api_key)

        for category in categories:
            self.__categories.append(category['title'])

    def post(self, title, description, category, publish=True):
        struct = {}
        struct['title'] = title
        struct['description'] = description
        if category in self.__categories:
            struct['categories'] = [category]

        try:
            return self.__client().metaWeblog.newPost(self.__user_id,
                                                      self.__user_id,
                                                      self.__api_key,
                                                      struct,
                                                      publish)
        except Exception as e:
            raise e


def main():
    naver = NaverBlog('아이디', '비밀번호')
    naver.post('테스트 제목', '<h1>테스트 글쓰기</h1>', '카테고리 한글')


if __name__ == '__main__':
    main()

 

 

 

 

1. XML-RPC란?

XML-RPC는 XML로 인코딩을 하는 RPC(Remote Procedure Call) 프로토콜의 종류 중 하나로, Server와 Client가 통신할때 사용한다. 이때, HTTP 프로토콜로 통신한다.

 

XML-RPC를 사용하면, client에서 server의 프로그램을 마치 로컬에 있는 프로그램을 사용하듯이 원격 실행이 가능하다.

 

이후에는 좀 더 부가기능을 추가하여 SOAP 프로토콜이 개발되었지만, 단순하고 사용하기 쉬운 XML-RPC를 더 많이 사용하고 있다. (비슷한 프로토콜로는 JSON-RPC가 존재)

 

1.1. XML-RPC XML 예시

XML-RPC Call

<?xml version="1.0"?>
<methodCall>
  <methodName>examples.getStateName</methodName>
  <params>
    <param>
        <value><i4>40</i4></value>
    </param>
  </params>
</methodCall>html

 

XML-RPC Response

<?xml version="1.0"?>
<methodResponse>
  <params>
    <param>
        <value><string>South Dakota</string></value>
    </param>
  </params>
</methodResponse>html

 

1.2. REST API vs XML-RPC

하지만, 요즘은 XML-RPC를 사용하지 않고 REST API를 많이 사용한다.

  • REST API가 상대적으로 사용하기 쉬움
  • XML-RPC는 대량의 데이터 전송에 상대적으로 효율적이지 못함

 

2. Python으로 XML-RPC 서버 구축

2.1. Server

from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler


class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ("/RPC2",)


if __name__ == "__main__":
    with SimpleXMLRPCServer(('localhost', 8000), requestHandler=RequestHandler) as server:
        server.register_introspection_functions()

        # 1. pow 함수를 저장하는 경우
        server.register_function(pow)

        # 2. 사용자가 정의한 함수를 저장하는 경우
        def adder_function(x, y):
            return x + y
        server.register_function(adder_function, 'add')

        # 3. 사용자가 정의한 클래스를 인스턴스로 생성하여 저장하는 경우
        class MyFuncs:
            def mul(self, x, y):
                return x + y
        server.register_instance(MyFuncs())

        # 서버 실행
        print("Start server...")
        server.serve_forever()
python

 

2.2. Client

Client쪽에는 pow, add, mul 메소드가 없지만, 실행 할 수 있다.

import xmlrpc.client

if __name__ == "__main__":
    proxy = xmlrpc.client.ServerProxy("http://localhost:8000")

    # 따로 pow, add, mul 함수를 정의한적이 없지만 사용이 가능하다.
    print(proxy.pow(2, 3))
    print(proxy.add(2, 3))
    print(proxy.mul(5, 2))

    # 사용할 수 있는 메소드 확인
    print(proxy.system.listMethods())
python

 

결과

 

 

 



출처: https://memostack.tistory.com/240 [MemoStack]

로그인 후 댓글쓰기가 가능합니다.

?

List of Articles
번호 분류 제목 날짜 조회 수
917 AutoHotKey #ifwinactive & #ifwinexist 윈도우창 마다 핫키의 용도를 다르게 사용하는 방법 2011.02.14 16518
916 Excel 'C:Documents.xlsx' 을(를) 찾을 수 없습니다. 라는 오류 메시지가 나오는 경우 대처방법 2015.01.28 4765
915 WindowsTip (nPDF) 프린터 인쇄 내용을 PDF 파일로 변환하기 2015.01.24 2271
914 컴퓨터잡담 -응답없음- 으로 멈춰버린 프로그램 대기시간 줄이는 방법 2010.10.01 7819
913 컴퓨터잡담 .htaccess와 워터마킹을 이용한 이미지 링크 방지 2009.06.30 34917
912 WindowsTip 100M Full 속도내기(레지스터리) file 2013.01.11 6506
911 컴퓨터잡담 16진수 헥사, 2진수, 10진수, 8진법 변환 계산기; Hex Calc 2012.02.22 7916
910 컴퓨터잡담 2021년 플래시 플레이어 웹사이트 크롬에서 접속하는 방법 2021.07.05 2559
909 컴퓨터잡담 2023-09-23 서버다운 후 복구완료 secret 2023.09.23 35773
908 컴퓨터잡담 50 개 이상의 Ajax 예제들 2 2010.03.29 18950
907 컴퓨터잡담 50 개 이상의 Ajax 예제들 2010.03.29 18178
906 Server 8기가 램에 맞는 Mysql config 셋팅 값 1 2016.02.22 3856
905 컴퓨터잡담 ACTIVE-X 의 무서움 file 2015.12.26 666
904 컴퓨터잡담 AHK & my Address of Pointer and my Offset 2011.10.11 13160
903 컴퓨터잡담 Ahk Standard Library Collection, 2010 Sep (+Gui) ~ Libs: 100 3 2011.10.11 14189
902 AutoHotKey ahk) autohotkey controlgettext 이름을 마우스커서에 졸졸 따라다니게 하기 file 2014.04.01 12153
901 AutoHotKey ahk) autohotkey 글자 자르기 방법 2013.10.30 34636
900 AutoHotKey ahk) autohotkey 엑셀(Excel)에서 행값 증가시키기 2013.10.30 37410
899 AutoHotKey AHK) AUTOKEY 웹페이지 열지않고 소스 가져오기 또는 로그인 하기 14 2012.05.12 52944
898 AutoHotKey Ahk) ip할당 진단프로그램 file 2011.12.26 12118
Board Pagination Prev 1 2 3 4 5 ... 46 Next
/ 46

http://urin79.com

우린친구블로그

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소