Skip to content

Commit

Permalink
[feat]:サーバーのコードを追加
Browse files Browse the repository at this point in the history
  • Loading branch information
tmrkw1497 committed Dec 12, 2019
1 parent ec48119 commit 17aa8c4
Show file tree
Hide file tree
Showing 9 changed files with 218 additions and 0 deletions.
5 changes: 5 additions & 0 deletions server/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
fakeCloud
.vscode
main/__pycache__
main/test.db
main/config.py
1 change: 1 addition & 0 deletions server/Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: gunicorn run:app --log-file -
25 changes: 25 additions & 0 deletions server/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# サーバー
## 仮想環境を作ろう!!
python3が入った状態で
`$ py -m venv [newenvname]`
仮想環境アクティベート!!
`$ .\[newenvname]\Scripts\activate`
## やれ!! ↓
```$ pip install -r requirements.txt```
ライブラリを追加した際は報告すること
また、ライブラリを追加した際は```$ pip freeze > requirements.txt```を実行すること
## 起動方法について
仮想環境に入り必要なライブラリをインストールした状態で`$ python run.py`を実行する
また、初回起動時は`$ python -c "import main.models; main.models.init()"`を実行する
## apiの仕様について
基本的には`https://p2server.herokuapp.com`にサーバーを構築する(基本的にサーバーは閉じているので使いたいときは連絡する slackなどで連絡)

`/user`に対し`{"mail":"任意の文字列","address":"任意の文字列"}`のようなJSONをPOSTするとデータベースにユーザーが登録される

`/user/<user_mail>`に対しGETするとuser_mailに対応したユーザーのIDを取得できる

`/answer`に対し`{"id":整数値,"result":[要素数17の1から5の値の格納された配列]}`のようなJSONをPOSTすると質問結果を計算し解答をデータベースに格納する

`/answer/<user_mail>`に対しGETするとuser_mailに対応した質問結果を取得できる

`/all_users`に対しGETすると登録されているユーザーの一覧を取得できる
11 changes: 11 additions & 0 deletions server/main/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS

app=Flask(__name__)
app.config.from_object('main.config')
CORS(app)

db=SQLAlchemy(app)

import main.views
23 changes: 23 additions & 0 deletions server/main/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from main import db
from flask_sqlalchemy import SQLAlchemy


class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
mail = db.Column(db.Text,nullable=False,unique=True)
address = db.Column(db.Text)
results=db.relationship("Result",backref="user",lazy=True)

def __repr__(self):
return "<User id={} mail={!r} address={!r}>".format(self.id,self.mail,self.address)

class Result(db.Model):
id=db.Column(db.Integer,primary_key=True)
user_mail=db.Column(db.Text,db.ForeignKey("user.mail"),nullable=False)
answer=db.Column(db.String(50))

def __repr__(self):
return "<Result id={} user_mail={!r} answer={!r}>".format(self.id,self.user_mail,self.answer)

def init():
db.create_all()
68 changes: 68 additions & 0 deletions server/main/util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
def calcResultData(inputData):
paramatas = {
"A1": ["h", "h", "n", "n", "h", "a", "h", "h", "n", "h", "h", "n", "n", "n", "h", "n", "n"],
"A2": ["a", "h", "n", "n", "h", "n", "h", "h", "n", "h", "h", "n", "n", "n", "n", "n", "n"],
"A3": ["a", "n", "h", "n", "h", "n", "a", "h", "n", "h", "h", "a", "h", "h", "h", "h", "n"],
"A4": ["h", "a", "n", "n", "h", "n", "h", "n", "n", "h", "h", "h", "a", "n", "n", "n", "n"],
"A5": ["h", "l", "n", "n", "h", "n", "h", "n", "n", "h", "h", "h", "h", "n", "n", "n", "n"],
"A6": ["n", "n", "n", "n", "n", "n", "n", "n", "h", "n", "n", "n", "n", "h", "n", "n", "n"],
"A7": ["n", "n", "a", "n", "n", "n", "n", "a", "h", "n", "n", "n", "h", "h", "n", "h", "n"],
"A8": ["n", "n", "a", "h", "n", "n", "n", "n", "h", "n", "n", "n", "h", "n", "n", "n", "n"],
"A9": ["n", "n", "n", "n", "n", "n", "n", "n", "n", "n", "n", "h", "n", "n", "n", "h", "a"],
"A12": ["n", "a", "a", "n", "h", "n", "a", "a", "h", "h", "h", "a", "a", "n", "n", "n", "n"],
"A13": ["n", "n", "n", "n", "n", "n", "n", "n", "n", "n", "n", "n", "n", "n", "n", "n", "n"]
}

levelData = []

for i in range(0, len(inputData)):
if inputData[i] == 1 or inputData[i] == 2:
levelData.append("l")
elif inputData[i] == 3:
levelData.append("m")
elif inputData[i] == 4 or inputData[i] == 5:
levelData.append("h")

score = {"A1": 0, "A2": 0, "A3": 0, "A4": 0, "A5": 0,
"A6": 0, "A7": 0, "A8": 0, "A9": 0, "A12": 0, "A13": 0}
highestScore = 0
datas = []

def check(levelData, paramata):
score = 0
for i in range(0, len(levelData)):
if levelData[i] == paramata[i] and levelData[i] != "n":
score += 1
return score

for key, value in paramatas.items():
score[key] = check(levelData, value)

for key, value in score.items():
if highestScore < value:
highestScore = value
highestScore

for key, value in score.items():
if value == highestScore:
datas.append(key)

return datas


def checkInputData(data):
"""
この関数は整数のlistを受け取りbool型の値を返す
listの長さが17でありかつlistのすべての要素が1から5の間にある場合Trueを返しそれ以外ではFalseを返す
ex)
[3, 1, 3, 4, 5, 4, 3, 2, 3, 4, 3, 1, 5, 1, 2, 2, 1] --> True
[3, 1, 3, 4, 5, 4, 3, 2, 3, 4, 3, 1, 5, 1, 2, 2] --> False
[3, 1, 3, 4, 5, 4, 3, 2, 3, 4, 3, 1, 5, 1, 2, 2, 6] --> False
[3, 1, 3, 4, 5, 4, 3, 2, 3, 4, 3, 1, 5, 1, 2, 2, 0] --> False
"""
if len(data) != 17:
return False
boolData = [1 <= i <= 5 for i in data]
if not all(boolData):
return False
return True
69 changes: 69 additions & 0 deletions server/main/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# coding:utf-8

import flask
from flask import jsonify,request,abort
from main import app,db
from main.models import User,Result
from main.util import calcResultData,checkInputData


@app.route("/")
def show():
return "Hello"

@app.route("/user",methods=["POST"])
def registerUser():
registerInfo=request.get_json()
if "mail" in registerInfo and "address" in registerInfo:
user=User(mail=registerInfo["mail"],address=registerInfo["address"])
db.session.add(user)
db.session.commit()
return jsonify(registerInfo)
abort(400)

@app.route("/user/<user_mail>",methods=["GET"])
def getUserID(user_mail):
users=db.session.query(User).filter(User.mail==user_mail).all()
if len(users)<=0:
abort(400)
user=users[0]
return jsonify({"id":user.id})

@app.route("/answer",methods=["POST"])
def addAnswer():
answer=request.get_json()
if "id" in answer and "result" in answer:
inputData = answer["result"]
if not checkInputData(inputData):
abort(400)

datas = calcResultData(inputData)
results = {}
results["result"]=datas
tmp_ans=",".join(datas)
users = db.session.query(User).filter(User.id == answer["id"]).all()
if len(users) <= 0:
abort(400)
user=users[0]
mail=user.mail
ans = Result(user_mail=mail, answer=tmp_ans)
db.session.add(ans)
db.session.commit()
return jsonify(results)

@app.route("/answer/<user_mail>",methods=["GET"])
def getResult(user_mail):
results=db.session.query(Result).filter(Result.user_mail==user_mail).all()
if len(results)<=0:
abort(404)
result=[i.answer.split(",") for i in results]
res={}
res["results"]=result
return jsonify(res)

@app.route("/all_users",methods=["GET"])
def unsafe_getAllUsers():
users = db.session.query(User).all()
user_list=[{"id":i.id,"mail":i.mail,"address":i.address} for i in users]
return jsonify(user_list)

12 changes: 12 additions & 0 deletions server/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Click==7.0
Flask==1.1.1
Flask-Cors==3.0.8
Flask-SQLAlchemy==2.4.1
gunicorn==20.0.4
itsdangerous==1.1.0
Jinja2==2.10.3
MarkupSafe==1.1.1
psycopg2-binary==2.8.4
six==1.13.0
SQLAlchemy==1.3.11
Werkzeug==0.16.0
4 changes: 4 additions & 0 deletions server/run.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from main import app

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

0 comments on commit 17aa8c4

Please sign in to comment.