Create a web server that can perform CRUD operations on the DB. I explained it carefully. We welcome you.
○ Premise -Create a list type as a temporary DB and perform CRUD operations on it. I think you should rewrite the operation for the temporary DB to the operation for the actual DB. -It is assumed that python and pip (python package manager) are installed. ○ Introduction As a motivation to create webApi with python, ・ Because I want to use the numpy library to handle DB data mathematically However, when I investigated later, it was faster to leave the web communication itself to js etc. and leave only the data processing to python + numpy. Reference: https://qiita.com/KatsunoriNakamura/items/dd567ea7cfaa99685453
-Flask: A web application framework that runs on python. I was able to easily create a web application. -WebApi: In this article, it refers to the web server that operates the DB when you hit the URI.
From the command line, type the following command.
pip install Flask
As a flow of explanation, we will first show the entire code and then briefly explain each code.
Create and execute the following file to start the server. You can operate the DB by hitting the URI set in the CRUD method while the server is starting.
sampleapp.py
from flask import Flask, jsonify, request, render_template
app = Flask(__name__)
# DB
stores = [
{
'name': 'my_store',
'items': [
{
'name': 'chocolate',
'price': 120
}
]
}
]
#CRUD for store--------------
# GET /store/<string:name>
@app.route('/stores/<string:name>') # 'http://127.0.0.1:5000/store/some_name'
def get_store(name):
for store in stores:
if store["name"] == name:
return jsonify(store)
return jsonify({"message": "no store named {} found.".format(name)})
# POST /store data: {name:}
@app.route('/stores', methods=['POST'])
def create_store():
request_data = request.get_json()
store = next(filter(lambda x: x["name"]==request_data["name"], stores), None)
if store != None:
return jsonify({"message": "store named {} already exist.".format(request_data["name"])})
else:
new_store = {
"name": request_data["name"],
"items": request_data["items"]
}
stores.append(new_store)
return jsonify({"message": "{} store is added.".format(request_data["name"])})
# PUT /store data: {name:}
@app.route('/stores/<string:name>', methods=['PUT'])
def update_store(name):
request_data = request.get_json()
store = next(filter(lambda x: x["name"] == name, stores), None)
if store == None:
return jsonify({"message": "no store named {} found.".format(name)})
else:
store["items"] = request_data["items"]
return jsonify({"message": "{} is updated.".format(name)})
# DELETE /stores/<string:name>
@app.route('/stores/<string:name>', methods=['DELETE'])
def delete_store(name):
global stores
stores = list(filter(lambda x: x["name"] != name, stores))
return jsonify({"message": "Delete store named {}".format(name)})
# --------------------CRUD for store
# GET /stores
@app.route('/stores')
def get_stores():
return jsonify({'stores': stores})
#Try loading html on the home screen.
# GET /
@app.route('/')
def home():
return render_template("index.html")
app.run(port=5000)
sampleapp.py
from flask import Flask, jsonify, request, render_template
I'm importing the required modules from the Flask library.
sampleapp.py
app = Flask(__name__)
Create the application body. In python, there is a special default variable surrounded by underscores, and name corresponds to the file name, so in this case it corresponds to sampleapp. However, the name of the executable file (the file executed by python ~ from the terminal) returns main. Flask can only work properly on the executable, so I'm making sure name = main for the called file.
sampleapp.py
# DB
stores = [
{
'name': 'my_store',
'items': [
{
'name': 'chocolate',
'price': 120
}
]
}
]
It is a temporary DB. It is assumed that multiple stores are stored, and each store contains a store name and multiple product data.
sampleapp.py
# GET /store/<string:name>
@app.route('/stores/<string:name>') # 'http://127.0.0.1:5000/store/some_name'
def get_store(name):
for store in stores:
if store["name"] == name:
return jsonify({"stores": store})
return jsonify({"message": "no store named {} found.".format(name)})
GET method. Specify the store name and return it as a json type response if it exists. Even if the store does not exist, the message is returned as a json type response.
The URI is registered in app with @ app.route ('/ stores / << string: name >>'). (The default IP is automatically specified as'http://127.0.0.1:5000'.) When this URI is hit, the method below will be called. The << string: name >> in the URI is assigned to the argument. jsonify () is a method to create a json type from a dictionary type.
sampleapp.py
# POST /store data: {name:}
def create_store():
request_data = request.get_json()
store = next(filter(lambda x: x["name"]==request_data["name"], stores), None)
if store != None:
return jsonify({"message": "store named {} already exist.".format(request_data["name"])})
else:
new_store = {
"name": request_data["name"],
"items": request_data["items"]
}
stores.append(new_store)
return jsonify({"message": "{} store is added.".format(request_data["name"])})
This is the POST method. POST is specified when specifying the URI. (GET is specified by default.) You can get the request body with request.get_json (). If there is no store with the same name, add the store with the request body data to the database.
I will omit the PUT method and DELETE method because there is no additional information.
sampleapp.py
# GET /stores
@app.route('/stores')
def get_stores():
return jsonify({'stores': stores})
I have created an API to get the entire DB for checking CRUD operations.
sampleapp.py
#Try loading html on the home screen.
# GET /
@app.route('/')
def home():
return render_template("index.html")
You can call an html file. The callee is set to call the GET method for the entire DB.
sampleapp.py
app.run(port=5000)
Finally, write the description to start the application. The default 5000 is the default even if you do not specify the port number, but I am writing it for the sake of clarity. Of course, you can specify other port numbers as well.
$ python sampleapp.py
* Serving Flask app "sampleapp" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
I checked using Postman (a tool that makes HTTP requests easy). I was able to confirm the operation of CRUDapi.
GET (stores) Get data for the entire stores
POST Register the new store by putting it in the quest body. Confirmation (GET (stores))
Other CRUDs work as well.
If you use python / Flask, It seems that you can create a web API with simple code in a short time.
I will not use it for the original purpose, so I would like to mourn it as a bot webApi.
Recommended Posts