React and Flask to GCP

Create a driven test site using Yelp API that you want to use GCP

I wanted to make an API test server with GCP Language: React, Flask Screen Shot 2020-03-22 at 1.12.36.png

I thought I should draw it with an api from somewhere, but it's dull (** Learn Udon ** links to talk about udon wiki % E3% 81% 86% E3% 81% A9% E3% 82% 93)) image.pngYelp API使ってこんな感じにした

Yelp api I used yelp api because everyone knows Japanese food sites and I think it's a good idea to take a look overseas.

Getting the api key is easy. If you enter yelp developers and register with your google or facebook account, it will be issued immediately.

Flask

Directory structure

app
├── config.py
└── run.py
# run.py

from flask import Flask, request
from flask_cors import CORS
import requests

import config

app = Flask(__name__)
CORS(app)

URL = "https://api.yelp.com/v3/businesses/search"
headers = {'Authorization': f"Bearer {config.API_KEY}"}


@app.route('/')
def ramen_yelp():
    payload = {
        "term": request.args.get("term", "ramen"),
        "location": request.args.get("location", "ny")
    }
    response = requests.request("GET", URL, headers=headers, params=payload)
    return response.json()


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=config.PORT, debug=config.DEBUG_MODE)

In the case of root ('/'), the ramen ranking in New York is set by default.

Flask, gunicorn settings in config Put the important thing in the env variable

# config.py

from os import environ
import multiprocessing

PORT = int(environ.get("PORT", 8080))
DEBUG_MODE = int(environ.get("DEBUG_MODE", 1))
API_KEY = environ.get("API_KEY")

bind = ":" + str(PORT)
workers = multiprocessing.cpu_count() * 2 + 1
threads = multiprocessing.cpu_count() * 2

If you enter ** 0.0.0.0:8080 ** from your browser (firefox or chrome) json_screen_shot.png

I started to spit out the result with json

Registered with GCR (Google Container Registry)

Convert flask to docker and upload to GCR

The Dockerfile looks like this

# pull official base image
FROM python:3.8.1-alpine

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# install dependencies
RUN pip install --upgrade pip
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

# set work directory
WORKDIR /usr/src/app

# copy project
COPY ./app .

ENV PORT 80
ENV API_KEY YOUR_API_KEY

CMD ["gunicorn", "run:app", "--config=config.py"]
# requirements.txt
Flask==1.1.1
gunicorn==20.0.4
requests==2.23.0
Flask-Cors==3.0.8

** For production, use API_KEY dotenv to put it together in config.py *

Next, you can easily register by typing the command as follows

#!/bin/sh
docker build -t flask-test-gcr 
docker tag flask-test-gcr [HOSTNAME]/[PROJECT-ID]/flask-test-gcr
docker push [HOSTNAME]/[PROJECT-ID]/flask-test-gcr
gcloud container images list-tags [HOSTNAME]/[PROJECT-ID]/flask-test-gcr

Like this Screen Shot 2020-03-22 at 14.08.08.png

GCE(Google Compute Engine) Create an instance from the gcp console screen

The machine specs are a test, so let's make it the weakest! image.png

If you want to deploy immediately from a container using docker, don't forget to check and container image below image.png

If you set the external IP of the GCE VM instance screen to * http: [IP] *, you can get the same result! If you don't have an SSL certificate, you have to set the external IP to * http * instead of * https *. image.png

Make a note of this IP address as it will be called from React

Front is React

Easy with a nice boiler plate called create-react-app

# app-name is your favorite name
npx create-react-app app-name

App.js is mostly a template, with the difference between calling images, links, and Yelp.js Components.

// App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';

import Yelp from './Yelp' //← This

function App() {
  return (
    <div className="main">
      <Yelp />
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="Udon logo" />
          <a
            className="App-link"
            href="https://ja.wikipedia.org/wiki/%E3%81%86%E3%81%A9%E3%82%93"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn Udon
        </a>
        </header>
      </div>
    </div>
  );
}

export default App;
// Yelp.js

import React, { useEffect, useState } from 'react'
import './Yelp.css'

const Yelp = () => {
  const [error, setError] = useState(null)
  const [yelpData, setYelpData] = useState({})

  useEffect(() => {
    const API_URL = 'http://The external IP you noted earlier/'
    fetch(API_URL)
      .then(res => res.json())
      .then(
        result => {
          setYelpData(result)
        })
      .catch(e => {
        setError(e)
      })
  }, [])

  if (error) {
    return (
      <div className="Yelp">error</div>
    )
  } else if (yelpData.businesses) {
    const images = yelpData.businesses.map(item => {
      return (
        < a key={item.id} href={item.url} target="_blank" rel="noopener noreferrer" >
          < img
            height="150" width="150" crop="fill" radius="20"
            src={item.image_url} alt="ramen"
          />
        </a >
      )
    })
    return (
      <div className="Yelp">
        {images}
      </div>
    )
  } else {
    return (
      <div className="Yelp"></div>
    )
  }
}

export default Yelp

After that, if you start it locally, a ramen image will come out

#Start-up
yarn start

Click on your favorite image to jump to the Yelp link for more details ラーメン

reference

Run Docker images registered in Container Registry (GCR) on GCE

Recommended Posts

React and Flask to GCP
I want to make a web application using React and Python flask
Install Python and Flask (Windows 10)
Key additions to pandas 1.1.0 and 1.0.0
Connection between flask and sqlite3
Twitter authentication using Flask and React is very forcible using WebSocket
Send and receive Flask images
The road to installing Python and Flask on an offline PC
Python 3.6 on Windows ... and to Xamarin.
[Introduction to Python3 Day 1] Programming and Python
Preparing to run Flask on EC2
Flask reuse How to write html
Scraping, preprocessing and writing to postgreSQL
Basic authentication and Digest authentication with Flask
GCP: Link Functions and Pub / Sub
How to install and configure blackbird
How to use .bash_profile and .bashrc
How to install and use Graphviz
Ssh connect to GCP from Windows
Python logging and dump to json
Selenium and python to open google
Connect to MySQL using Flask SQLAlchemy
The easiest way to make Flask
How to solve slide puzzles and 15 puzzles
Wrap reading and writing of GCP to Secret Manager with google subcommands
Deploy Django + React from scratch to GKE (4) Create cluster and container PUSH