2016-07-07 76 views
0

我有兩個服務運行在docker-compose,frontendbackend,都使用燒瓶開發。使REST調用燒瓶服務運行在不同的端口

frontend: 
    restart: always 
    build: ./frontend 
    expose: 
    - "8000" 
    command: /usr/local/bin/gunicorn --bind :8000 run:application 

backend: 
    restart: always 
    build: ./backend 
    expose: 
    - "9000" 
    command: /usr/local/bin/gunicorn --bind :9000 run:application 

我託管在後端

@app.route('/api/weather', methods=['GET']) 
def get_weather(): 
    super_cool_function() 
    return jsonify({'temperature': 100}) 

什麼是消耗在前端這個API的最好方法簡單的REST API?我猜下面是一個辦法,但我不知道應該是什麼輸入requests.get()

@app.route('/hello') 
def hello(): 
    r = requests.get() 
    return render_template('hello.html', temperature=r.json()['temperature']) 
+0

您是否考慮過使用url來使用您要使用的端點?這就是網絡上的任何請求的工作原理。 – davidism

+0

@davidism - 你的意思是'r = requests.get('http://example.com/api/weather:9000')'。基本上我在燒瓶中嘗試'url_for'函數並且感到困惑 – kampta

+0

這是標準方法嗎? – kampta

回答

1

,而無需實現你的設置,我一般做REST調用通過實施類似如下的方法使用要求。

def get_weather(data): 
    # Set api endpoint to what's needed 
    endpoint = 'http://example.com/api/weather:9000' 

    # Do any work needed specific to api prior to call 

    # Send request and get response 
    response = requests.get(url=endpoint, data=data) 

    # Process response 
    result = process(response) 
    return result 

您可以創建一個類,使所有api調用到同一個url,並且只需更改端點。

class ApiCaller(): 
    def __init__(self, base_url, port): 
     self.base_url = base_url 
     self.port = port 

    def __get_url(self, endpoint): 
     return '%s%s%s' % (self.base_url, endpoint, self.port) 

    def get_weather(self, data): 
     endpoint = 'weather' 
     return requests.get(url=self.__get_url(endpoint), data=data) 

    def get_hello(self, data) 
     endpoint = 'hello' 
     return requests.get(url=self.__get_url(endpoint), data=data) 
相關問題