2016-07-07 60 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) 
相关问题