Skip to content

Commit

Permalink
[fix] linters
Browse files Browse the repository at this point in the history
  • Loading branch information
vkuzmenkova committed Apr 29, 2024
1 parent bae9379 commit 9fd3d40
Show file tree
Hide file tree
Showing 18 changed files with 55 additions and 155 deletions.
3 changes: 1 addition & 2 deletions .github/workflows/python-app.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,4 @@ jobs:
- run: |
python -m pip install --upgrade pip
pip install flake8
pip install isort
make lint
flake8 --config flake8
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ migrations:

lint:
isort *
flake8 --config flake8


start:
docker-compose up
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
How to play:

1. run `make start`
2. go to http://localhost:5173/
2. go to http://localhost:5173/
3. click on `Create user / Login`
4. enter username and password and press `Create user`
5. log in with created user
Expand Down
2 changes: 1 addition & 1 deletion alembic/versions/68cb451e6f2c_add_unique_contsraint.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa

from alembic import op

# revision identifiers, used by Alembic.
revision: str = '68cb451e6f2c'
Expand Down
29 changes: 10 additions & 19 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
import json
import os

from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from sqlalchemy import MetaData, create_engine
from sqlalchemy.orm import (Session, sessionmaker)

from src.db.orm_models import Base, UserORM
from src.game import (ConnectionManager, Game, Player,
PlayerOptions, Room, RoomManager, GameStatus)
from sqlalchemy import create_engine

from src.db.db import DB
from src.errors import UserAlreadyExists, UserNotFoundError, WrongPassword
from src.game import (ConnectionManager, Game, GameStatus, Player,
PlayerOptions, Room, RoomManager)
from src.models import CreateUserRequest
from src.errors import UserNotFoundError, UserAlreadyExists, WrongPassword
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
import os

app = FastAPI()

Expand All @@ -41,7 +37,7 @@
room_manager = RoomManager()

engine = create_engine(
f'postgresql+psycopg://postgres:qwerty@{db_host}/postgres',
f'postgresql+psycopg://postgres:qwerty@{db_host}/postgres',
echo=True,
pool_size=5,
max_overflow=10,
Expand All @@ -57,8 +53,7 @@ async def websocket_endpoint(websocket: WebSocket, username: str):
# Create player
player = Player(ws=websocket, id=username)
playing_room = None



try:
while True:
# If user already in a room
Expand Down Expand Up @@ -100,7 +95,6 @@ async def websocket_endpoint(websocket: WebSocket, username: str):
playing_room.game.p2_option = playing_room.player2.choice
result = playing_room.game.find_winner()

# перенести в room manager?
await playing_room.announce_result(result)
db.save_result(
playing_room.player1.id,
Expand All @@ -113,9 +107,6 @@ async def websocket_endpoint(websocket: WebSocket, username: str):
await playing_room.send_message_to_another_player(player, GameStatus.WAITING.name)
# remove user
room_manager.remove_player(player.id)





@app.get("/rating")
Expand All @@ -124,6 +115,7 @@ async def rating():

return JSONResponse(json.dumps(users_rated))


@app.post("/users/create")
async def create_user(request: CreateUserRequest):
try:
Expand All @@ -140,6 +132,5 @@ async def login(request: CreateUserRequest):
return JSONResponse('{}')
except UserNotFoundError as e:
return JSONResponse(json.dumps(e.message), status_code=400)
except WrongPassword as e:
return JSONResponse(json.dumps(e.message), status_code=401)

except WrongPassword as e:
return JSONResponse(json.dumps(e.message), status_code=401)
1 change: 0 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ services:
app:
build: ./
command: bash -c "./wait-for-postgres.sh db && uvicorn app:app --proxy-headers --host 0.0.0.0 --port 8000"
# - alembic upgrade head
ports:
- 8000:8000
depends_on:
Expand Down
3 changes: 3 additions & 0 deletions flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[flake8]
ignore = D203,E501,W293,W292,W291
exclude = .git,__pycache__,docs/source/conf.py,old,build,dist,./.venv,./alembic
67 changes: 0 additions & 67 deletions game-client/src/components/AuthForm.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,9 @@ import { ref } from 'vue'
import { useUsersStore } from '../../store/users'
const usersStore = useUsersStore()
const message=ref('')
// const username=ref('')
const password=ref('')
// function createUser(event) {
// if (username.value && password.value){
// axios({
// method: 'post',
// url: 'http://127.0.0.1:8000/users/create',
// data: {
// username: username.value.toLowerCase(),
// password: password.value,
// },
// })
// .then(function (response) {
// console.log(response.data)
// message.value = `User "${username.value}" created`
// })
// .catch(function (error, response) {
// console.log(error);
// message.value = error.response.data;
// })
// }
// }
function createUser(event) {
if (usersStore.userName && password.value){
axios({
Expand All @@ -41,11 +18,9 @@ function createUser(event) {
},
})
.then(function (response) {
// console.log(response.data)
message.value = `User "${usersStore.userName}" created`
})
.catch(function (error, response) {
// console.log(error);
message.value = error.response.data;
})
}
Expand All @@ -62,38 +37,15 @@ function login(event) {
},
})
.then(function (response) {
// console.log(response.data)
message.value = `You logged in as "${usersStore.userName}"`
usersStore.setIsLoggedIn(true)
})
.catch(function (error, response) {
// console.log(error);
message.value = error.response.data;
})
}
}
// function login(event) {
// if (username.value && password.value){
// axios({
// method: 'post',
// url: 'http://127.0.0.1:8000/auth/login',
// data: {
// username: username.value.toLowerCase(),
// password: password.value,
// },
// })
// .then(function (response) {
// console.log(response.data)
// message.value = `You logged in as "${username.value}"`
// })
// .catch(function (error, response) {
// console.log(error);
// message.value = error.response.data;
// })
// }
// }
const handleChange = (event) => {
usersStore.setUserName(event.target.value);
};
Expand All @@ -108,7 +60,6 @@ const handleChange = (event) => {
<form @submit.prevent="onSubmit">
<div class="form-group">
<label>Username:</label>
<!-- <input v-model="username" placeholder="username" required> -->
<input @input="handleChange" placeholder="username" required>
</div>
<div class="form-group">
Expand All @@ -124,24 +75,6 @@ const handleChange = (event) => {
</div>
</template>

<!-- <template>
<div class="container">
<form @submit.prevent="onSubmit">
<div class="form-group">
<label>Username:</label>
<input v-model="username" placeholder="username" required>
</div>
<div class="form-group">
<label>Password:</label>
<input v-model="password" placeholder="password" required>
</div>
<button type="submit" @click="createUser">Create user</button>
<p align="center">or</p>
<button type="submit" @click="login">Login</button>
</form>
<p>{{ message }}</p>
</div>
</template> -->

<style scoped>
.authForm {
Expand Down
3 changes: 1 addition & 2 deletions game-client/src/components/GamePlay.vue
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ ws.onmessage = function(event) {
setTimer(timer_sec)
break;
default:
// results
status.value=event.data;
isOneMoreShown.value = true
Expand All @@ -70,7 +69,7 @@ function setTimer(sec) {
timer.value = sec
timerId.value = setInterval(() => {
if (timer.value > 0) {
timer.value--; // уменьшаем значение таймера каждую секунду
timer.value--;
}
}, 1000);
Expand Down
9 changes: 1 addition & 8 deletions game-client/src/components/LeaderBoard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,9 @@ axios({
})
.then(function (response) {
users.value = JSON.parse(response.data)
users.value = users.value.map(user=>JSON.parse(user))
// console.log(users)
users.value = users.value.map(user=>JSON.parse(user))
})
.catch(function (error) {
// console.log(error);
})
.finally(function () {
});
Expand All @@ -32,7 +30,6 @@ axios({

<template>
<p v-if="usersStore.isLoggedIn" align="right">{{ usersStore.userName }}</p>
<!-- <p align="right">{{ username }}</p> -->
<table align="center">
<caption>
Leader Board
Expand Down Expand Up @@ -82,8 +79,4 @@ th {
border: 1px solid black;
font-weight: bold;
}
</style>
1 change: 0 additions & 1 deletion game-client/src/router/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import AuthFormView from '../views/AuthFormView.vue'

const router = createRouter({
history: createWebHistory(),
// history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
Expand Down
1 change: 0 additions & 1 deletion game-client/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
Expand Down
5 changes: 4 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ fastapi-users-db-sqlalchemy==6.0.1
fastapi_auth_middleware==1.0.2
fastjsonschema==2.19.1
filelock==3.13.4
flake8==7.0.0
Flask==3.0.3
Flask-Caching==2.1.0
Flask-Cors==4.0.0
Expand Down Expand Up @@ -61,9 +62,11 @@ psycopg2-binary==2.9.9
ptyprocess==0.7.0
pwdlib==0.2.0
pyasn1==0.6.0
pycodestyle==2.11.1
pycparser==2.22
pydantic==2.7.0
pydantic_core==2.18.1
pyflakes==3.2.0
PyJWT==2.8.0
pylint==3.1.0
pyproject_hooks==1.0.0
Expand Down Expand Up @@ -93,4 +96,4 @@ websocket-client==1.7.0
websockets==12.0
Werkzeug==3.0.2
wheel==0.43.0
xattr==1.1.0
xattr==1.1.0
25 changes: 11 additions & 14 deletions src/db/db.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
from sqlalchemy import MetaData, create_engine
from sqlalchemy.orm import (Session, sessionmaker)
from src.db.orm_models import Base, UserORM
from src.models import User
import json
import uuid as pyuuid

from src.errors import UserNotFoundError, UserAlreadyExists, WrongPassword
from sqlalchemy import MetaData
from sqlalchemy.orm import sessionmaker

from src.db.orm_models import Base, UserORM
from src.errors import UserAlreadyExists, UserNotFoundError, WrongPassword
from src.game import Result
from src.models import User


class DB:
def __init__(self, engine):
Expand All @@ -15,11 +16,9 @@ def __init__(self, engine):
Session = sessionmaker(engine)
self.session = Session()


def get_rating(self) -> list[User]:
users = self.session.query(UserORM).order_by(UserORM.wins.desc()).all()
usersDTO: list[User] = [User.model_validate(user).model_dump_json() for user in users]

return usersDTO

def create_user(self, username: str, password: str):
Expand All @@ -46,21 +45,19 @@ def login(self, username: str, password: str):
raise UserNotFoundError(f"User `{username}` not found")
elif user.password != password:
raise WrongPassword(f"Wrong password for user `{username}`")


def save_result(self, username1: str, username2: str, result: Result):
# updated_at
player1 = self.find_by_username(username1)
player2 = self.find_by_username(username2)

player1.total +=1
player2.total +=1
player1.total += 1
player2.total += 1

if result is Result.PLAYER1_WON:
player1.wins +=1
player1.wins += 1
elif result is Result.PLAYER2_WON:
player2.wins +=1
player2.wins += 1

self.session.add_all([player1, player2])
self.session.commit()

Loading

0 comments on commit 9fd3d40

Please sign in to comment.