简体   繁体   中英

How to serve REST API on Google Cloud?

I have made a REST API for my Ubuntu machine on Google Cloud. How can I connect this API with public IP address?

In the below code I am uploading image file in multipart/form-data format.

from flask import Flask, url_for, send_from_directory, request
import logging, os
# from werkzeug import secure_filename
import werkzeug
app = Flask(__name__)
file_handler = logging.FileHandler('server.log')
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)

PROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER = '{}/uploads/'.format(PROJECT_HOME)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


def create_new_folder(local_dir):
    newpath = local_dir
    if not os.path.exists(newpath):
        os.makedirs(newpath)
    return newpath

@app.route('/Classifier01', methods = ['POST'])
def api_upload():


    app.logger.info(PROJECT_HOME)
    if request.method == 'POST':
      app.logger.info(app.config['UPLOAD_FOLDER'])

      #get image and save in ../uploads
      img = request.files['image']
      img_name = werkzeug.secure_filename(img.filename)
      create_new_folder(app.config['UPLOAD_FOLDER'])
      saved_path = os.path.join(app.config['UPLOAD_FOLDER'], img_name)
      app.logger.info("saving {}".format(saved_path))
      img.save(saved_path)

      #do some processing here

      return "I got your image"
    else:
      return "Where is the image?"

if __name__ == '__main__':
    app.run()

It start on 127.0.0.1:5000 how make it on public IP.

First, start your app to listen on interface of your VM -> run it like this app.run(host='0.0.0.0')

Then, you have 2 solutions

  • Use the public IP of your VM to reach it. Don't forget to open the correct firewall rule for this (source IP range= 0.0.0.0/0, port TCP 5000). But it's not perfect. You can update your app for listening on the port 80 for a more standard API port on internet. You can also plug an nginx on your VM. On it, you can also deploy a SSL certificate and allow to reach your service on the port 443 in HTTPS. pff, lot of work
  • You can use HTTP(s) load balancer for this. SSL in automatically managed. Simply create a backend with your VM (a NEG), your health check and set up your frontend. It's the easiest way!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM