Before You Begin
Purpose
This tutorial shows you how to create a simple REST service in Python using the Flask framework and Oracle MySQL Cloud Service and how to deploy the application on Oracle Application Container Cloud Service.
Time to Complete
45 minutes
Background
Oracle Application Container Cloud Service lets you deploy Java SE, Node.js, PHP, and Python applications to the Oracle Cloud.
What Do You Need?
- Access to an instance of Oracle Application Container Cloud Service
- A storage replication policy for your service instance
- An SSH key pair. See Creating SSH Keys for Use with Oracle Cloud Services
- Python 3.6+
- The package management system pip
- cURL 7.0+ with SSL support
Creating the REST Service
-
Create the
python-servicedirectory in your local system to store the project files. -
In
python-servicedirectory, create theapp.pyfile and add the following content:#!/usr/bin/env python from __future__ import print_function from flask import Flask, jsonify, abort, request from flask_cors import CORS, cross_origin import logging import pymysql import os app = Flask(__name__) CORS(app) cors = CORS(app, resources={r"/api/*": {"origins": "*","methods":"POST,DELETE,PUT,GET,OPTIONS"}}) def creatConnection(): # Read MySQL Environment Parameters connectString = os.environ.get('MYSQLCS_CONNECT_STRING', 'localhost:3306/myDB') hostname = connectString[:connectString.index(":")] database = connectString[connectString.index("/")+1:] conn = pymysql.connect(host=hostname, port=int(os.environ.get('MYSQLCS_MYSQL_PORT', '3306')), user=os.environ.get('MYSQLCS_USER_NAME', 'root'), passwd=os.environ.get('MYSQLCS_USER_PASSWORD', ''), db=database, cursorclass=pymysql.cursors.DictCursor) return conn; @app.route('/') def index(): return 'The application is running!' @app.route('/employees/setupdb') def setupDB(): conn = creatConnection() cur = conn.cursor() cur.execute('''CREATE TABLE EMPLOYEE ( ID INTEGER NOT NULL AUTO_INCREMENT, FIRSTNAME VARCHAR(255), LASTNAME VARCHAR(255), EMAIL VARCHAR(255), PHONE VARCHAR(255), BIRTHDATE VARCHAR(10), TITLE VARCHAR(255), DEPARTMENT VARCHAR(255), PRIMARY KEY (ID) ); ''') conn.commit() cur.close() conn.close() return 'The EMPLOYEE tables was created succesfully' @app.route('/employees') def employees(): conn = creatConnection() cur = conn.cursor() cur.execute('''SELECT ID, FIRSTNAME, LASTNAME, EMAIL, PHONE, BIRTHDATE, TITLE, DEPARTMENT FROM EMPLOYEE''') results = cur.fetchall() cur.close() conn.close() return jsonify( results) @app.route('/employees/<int:employee_id>', methods=['GET']) def get_employee(employee_id): conn = creatConnection() cur = conn.cursor() cur.execute('''SELECT ID, FIRSTNAME, LASTNAME, EMAIL, PHONE, BIRTHDATE, TITLE, DEPARTMENT FROM EMPLOYEE WHERE ID = %s'''%(employee_id)) rv = cur.fetchone() if rv is None: abort(404) cur.close() conn.close() return jsonify( rv) @app.route('/employees', methods=['POST']) def create_employee(): conn = creatConnection() cur = conn.cursor() try: cur.execute('''INSERT INTO EMPLOYEE (FIRSTNAME, LASTNAME, EMAIL, PHONE, BIRTHDATE, TITLE, DEPARTMENT) VALUES('%s','%s','%s','%s','%s','%s','%s') '''%(request.json['firstName'],request.json['lastName'], request.json['email'],request.json['phone'],request.json['birthDate'],request.json['title'],request.json['dept'])) conn.commit() message = {'status': 'New employee record is created succesfully'} cur.close() except Exception as e: logging.error('DB exception: %s' % e) message = {'status': 'The creation of the new employee failed.'} conn.close() return jsonify(message) @app.route('/employees/<int:employee_id>', methods=['PUT']) def update_employee(employee_id): conn = creatConnection() cur = conn.cursor() try: cur.execute('''UPDATE EMPLOYEE SET FIRSTNAME='%s', LASTNAME='%s', EMAIL='%s', PHONE='%s', BIRTHDATE='%s', TITLE='%s', DEPARTMENT='%s' WHERE ID=%s '''%(request.json['firstName'],request.json['lastName'], request.json['email'],request.json['phone'],request.json['birthDate'],request.json['title'],request.json['dept'],employee_id)) conn.commit() message = {'status': 'The employee record is updated succesfully'} cur.close() except Exception as e: logging.error('DB exception: %s' % e) message = {'status': 'Employee update failed.'} conn.close() return jsonify(message) @app.route('/employees/<int:employee_id>', methods=['DELETE']) def delete_employee(employee_id): conn = creatConnection() cur = conn.cursor() try: cur.execute('''DELETE FROM EMPLOYEE WHERE ID=%s '''%(employee_id)) message = {'status': 'The employee record is deleted succesfully'} conn.commit() cur.close() except Exception as e: logging.error('DB exception: %s' % e) message = {'status': 'Employee delete failed.'} conn.close() return jsonify(message) if __name__ == '__main__': app.run(host='0.0.0.0', port=os.environ.get('PORT', '8080'))
Preparing Your Application for Cloud Deployment
In
python-servicedirectory, create thestart.shfile and add the following content:#!/bin/sh export PYTHONPATH=modules python app.pyCreate the
manifest.jsonfile and add the following content:{ "runtime": { "majorVersion": "3.6.0" }, "command": "sh ./start.sh", "isClustered": true, "release": { "version": "1.0" }, "notes": "Python App using Flask and MySQL" }Create the
requeriments.txtfile and add the dependencies:flask==0.12.1 pymysql==0.7.11Open a command-line window (or terminal in Linux).
Go to the
python-servicedirectory and install the project dependencies:pip install -r requirements.txt -t modulesCreate the
python-service-dist.zipfile with the content of thepython-servicedirectory.zip -r python-service-dist.zip app.py start.sh manifest.json modules requirements.txt
Creating an Oracle MySQL Cloud Service Instance
In this section, you create an Oracle MySQL Cloud Service instance using the user interface. When you create your Oracle MySQL Cloud Service instance, you need to provide a secure shell (SSH) public key to establish secure connections. If you don't have one, see the "What do you need?" section of this tutorial.
You need the public key when creating a service instance, and you need the paired private key when you access it using the ssh utility.
Log in to Oracle Cloud at http://cloud.oracle.com/. Enter the identity domain, user name, and password for your account.
In the Oracle Cloud Services dashboard click
and select Oracle MySQL Cloud Service.To open the Oracle MySQL Cloud Service console, click Services.
Click Create Service.
Enter or select the following information, and then click Next:
- Service Name:
TestDB - Service Description (optional)
- Metering Frequency: Hourly
- Service Name:
-
Enter or select the following information, and then click Next:
- Compute Shape: OC3-1.0 OCPU, 7.5GB RAM
- SSH Public Key (Enter the public key.)
- Usable Database Storage(GB):
25 - Administration User:
root - Administration Password
- Confirm Administration Password
- Database Schema Name:
mydatabase - Server Character Set: utf8mb4 - UTF-8 Unicode
- Configure MySQL Enterprise Monitor: No
- Backup Destination: None
Review the details of your instance and then click Create.
Wait until the instance is created.
Description of this image
Deploying Your Application to Oracle Application Container Cloud Service
Go back to your Oracle Cloud account, click
, and select Oracle Application Container Cloud Service.To open the Oracle Application Container Cloud Service console, click Services.
-
In the Applications list view, click Create Application.
-
Click Python.
-
In the Application section, enter a name for your application and click Browse next to Archive.
-
In the File Upload window, select the
python-service-dist.zipfile and click Open. If your account has access to Oracle Cloud Infrastructure regions, in the Region field select the same region that you used to create your Oracle Database Cloud Service instance.
-
Keep the default values in the Topology section and click Create.
-
Wait until the application is completely created.
Your application could take a few minutes to complete the process.
Description of this image
Adding the Database Service Binding
-
In the Applications list view, click your application.
-
Click the Deployments tab and in the Service Binding section, click Add.
-
In the Add Service Binding dialog box, select MySQLCS Service in the Service Type field, enter or select values in the Service Name, Username, and Password fields, and click Save.
-
In the Deployments dialog box, click Apply Edits.
Copy the URL of your application, you'll use it in the next section.
Description of this image
Testing Your Application
Open a command-line window (or terminal in Linux).
Create the
EMPLOYEEtable. Replace the app_endpoint placeholder with the URL of your application.curl -X GET -i app_endpoint/employees/setupdbCreate an employee.
curl -X POST -i -H "Content-Type: application/json" -d "{\"firstName\":\"Luis\",\"lastName\":\"Gray\",\"email\":\"john.gray@example.com\",\"phone\":\"1203123\",\"birthDate\":\"1975-05-14\",\"title\":\"Developer Manager\",\"dept\":\"IT\"}" app_endpoint/employeesGet all the employees.
curl -X GET -i app_endpoint/employeesUpdate the employee.
curl -X DELETE -i app_endpoint/employees/1Get the employee by ID.
curl -X GET -i app_endpoint/1
Want to Learn More?
- Oracle Application Container Cloud Service in the Oracle Help Center
-
Flask website flask.pocoo.org
-
PyMysql website pymysql.readthedocs.io