I participated in Nagoya.Swift + May Study Session. This is a summary of what I did.
I usually write Swift, but I was interested in machine learning and so on, so I decided to get used to the Python syntax for the time being, so I implemented a REST API that I have experience in implementing in other languages.
Implemented GET by referring to @ Morinikki's Implementing REST API quickly with Python.
Now that I know how to create an endpoint, I'll use POST, PUT, and DELETE as well, and read peewee's Document. I implemented it.
api.py
# -*- coding: utf-8 -*-
from flask import Flask, jsonify, abort, make_response, request
import peewee as pe
import random
import json
#Random string
def random_string(length, seq='0123456789abcdefghijklmnopqrstuvwxyz'):
sr = random.SystemRandom()
return ''.join([sr.choice(seq) for i in range(length)])
db = pe.SqliteDatabase("datas.db")
#model
class User(pe.Model):
userId = pe.TextField()
name = pe.TextField()
caption = pe.TextField()
old = pe.IntegerField()
class Meta:
database = db
api = Flask(__name__)
#Get user
@api.route('/user/<string:userId>', methods=['GET'])
def get_user(userId):
try:
user = User.get(User.userId == userId)
except User.DoesNotExist:
abort(404)
result = {
"result":True,
"data":{
"userId":user.userId,
"name":user.name,
"caption":user.caption,
"old":int(user.old)
}
}
return make_response(jsonify(result))
#add to
@api.route('/user', methods=['POST'])
def post_user():
userId = 'us_'+random_string(6)
dataDict = json.loads(request.data)
try:
q = User.insert(userId=userId, name=dataDict["name"], caption=dataDict["caption"], old=dataDict["old"])
q.execute() # perform the insert.
user = User.get(User.userId == userId)
except User.DoesNotExist:
abort(404)
result = {
"result":True,
"data":{
"userId":user.userId,
"name":user.name,
"caption":user.caption,
"old":int(user.old)
}
}
return make_response(jsonify(result))
#update
@api.route('/user/<string:userId>', methods=['PUT'])
def put_user(userId):
dataDict = json.loads(request.data)
try:
q = User.update(name=dataDict["name"], caption=dataDict["caption"], old=dataDict["old"]).where(User.userId == userId)
q.execute()
except User.DoesNotExist:
abort(404)
result = {
"result":True
}
return make_response(jsonify(result))
#Delete
@api.route('/user/<string:userId>', methods=['DELETE'])
def del_user(userId):
try:
q = User.delete().where(User.userId == userId)
q.execute()
except User.DoesNotExist:
abort(404)
result = {
"result":True,
}
return make_response(jsonify(result))
#Get all users
@api.route('/users', methods=['GET'])
def get_users():
try:
users = User.select()
except User.DoesNotExist:
abort(404)
arr = []
for user in users:
arr.append({
"userId":user.userId,
"name":user.name,
"caption":user.caption,
"old":int(user.old)
})
result = {
"result":True,
"data":arr
}
return make_response(jsonify(result))
@api.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
if __name__ == '__main__':
api.run(host='0.0.0.0', port=3000)
It took about 5 hours to implement this. I think it was pretty good for the first Python. However, I didn't write it while understanding it, so it is necessary to deepen my understanding.
After this, it was good to be able to create an iOS client (implementing only GET and DELETE due to time constraints) and demo it in the spare time (I wanted to write Swift somewhere because it was a study session called Nagoya.Swift +).
Recommended Posts